我正在编写一个编译器,目前正在尝试勾勒出示例代码的 AST,我知道它是如何工作的。但令我困惑的是,我该如何准确地表达它。我在网上查找了 JavaScript AST,但它们在函数声明中没有任何参数声明,这让我很困惑。那么,如何为具有两个参数的函数绘制 AST 呢?我是否将它们放在函数声明中?
最佳答案
我没有编译器设计的经验,但我的工作让我盯着很多 AST。以下是您提到的特定主题的一些示例 - 函数声明中的参数。
JavaScript(通过 esprima )包含函数参数作为函数声明节点的属性。下面是带有参数 argOne
和 argTwo
的 myFunction
声明示例:
{
"type": "FunctionDeclaration",
"id": {
"type": "Identifier",
"name": "myFunction"
},
"params": [
{
"type": "Identifier",
"name": "argOne"
},
{
"type": "Identifier",
"name": "argTwo"
}
],
"body": { ... }
}
作为另一个例子,考虑 FuncDecl 的 golang 类型.
type FuncDecl struct {
Doc *CommentGroup // associated documentation; or nil
Recv *FieldList // receiver (methods); or nil (functions)
Name *Ident // function/method name
Type *FuncType // function signature: parameters, results, and position of "func" keyword
Body *BlockStmt // function body; or nil for external (non-Go) function
}
函数参数保存在Type
键下,其类型包括一个Params
列表:
type FuncType struct {
Func token.Pos // position of "func" keyword (token.NoPos if there is no "func")
Params *FieldList // (incoming) parameters; non-nil
Results *FieldList // (outgoing) results; or nil
}
作为最后一个示例,为了多样化,请考虑具有两个参数的 Elixir 函数的引用形式。
{:def, [context: Elixir, import: Kernel],
[
{:myFunction, [context: Elixir],
[{:argOne, [], Elixir}, {:argTwo, [], Elixir}]},
[
do: ...
]
]}
这里,元组的第三个元素是“参数列表”,无论是函数接受的参数列表(如上所述)还是应用于函数调用的参数。
祝你的编译器冒险之旅好运!
关于abstract-syntax-tree - AST 中的函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49949510/