如何实现词法范围? [英] How is Lexical Scoping implemented?

查看:120
本文介绍了如何实现词法范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几年前,我开始为一个领域特定语言编写一个解释器,其中包括程序员定义的函数。

A couple of years ago I started writing an interpreter for a little Domain Specific Language which included programmer-defined functions.

一开始,我使用一个简单的符号表栈实现了变量范围。但现在我想移动到正确的词法作用域(使用闭包的选项)。任何人都可以解释或指出一个很好的解释词汇范围后的数据结构和算法?

At first I implemented variable scope using a simple stack of symbol-tables. But now I want to move to proper lexical scoping (with the option of closures). Can anyone explain or point me at a good explanation of the data-structure and algorithm behind lexical scope?

推荐答案

要在解释器中获得正确的词法作用域和闭包,所有您需要做的是遵循以下规则:

To get correct lexical scoping and closures in an interpreter, all you need to do is follow these rules:


  • 在解释器中,变量总是在调用者传递的环境表中查找/保存为变量,而不是一些全局环境栈。也就是说, eval(expression,env)=> value

  • 当解释的代码调用函数时,环境是 NOT 传递给该函数。 apply(function,arguments)=> value

  • 当一个解释的函数被调用时,它的主体被评估的环境是在其中进行函数定义的环境,并且没有任何东西做与调用者。所以如果你有一个局部函数,那么它是一个闭包,即一个包含字段 {function definition,env-at-definition-time}的数据结构

  • In your interpreter, variables are always looked up in an environment table passed in by the caller/kept as a variable, not some global env-stack. That is, eval(expression, env) => value.
  • When interpreted code calls a function, the environment is NOT passed to that function. apply(function, arguments) => value.
  • When an interpreted function is called, the environment its body is evaluated in is the environment in which the function definition was made, and has nothing whatsoever to do with the caller. So if you have a local function, then it is a closure, that is, a data structure containing fields {function definition, env-at-definition-time}.

要扩展Python-ish语法中的最后一位:

To expand on that last bit in Python-ish syntax:

x = 1
return lambda y: x + y

被执行,好像是

x = 1
return makeClosure(<AST for "lambda y: x + y">, {"x": x})

第二个dict参数可能只是current-env,而不是当时构建的数据结构。 (另一方面,保留整个env而不仅仅是关闭的变量会导致内存泄漏。)

where the second dict argument may be just the current-env rather than a data structure constructed at that time. (On the other hand, retaining the entire env rather than just the closed-over variables can cause memory leaks.)

这篇关于如何实现词法范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆