AST 中的函数参数?

Function Parameters in an AST?

我正在编写一个 Complier,目前我正在尝试草拟我的示例代码的 AST,我知道它是如何工作的。但是,让我感到困惑的是,我将如何准确地表达它。我在网上查找 JavaScript AST,但它们在函数声明中没有任何参数声明,这让我感到困惑。那么我该如何为具有两个参数的函数绘制 AST 呢?我是否将它们放在函数声明中?

我没有编译器设计经验,但我的工作让我盯着很多 AST。以下是您提到的特定主题的几个示例 — 函数声明中的参数。

JavaScript(通过esprima)包括函数参数作为函数声明节点的属性。下面是带有参数 argOneargTwomyFunction 声明示例:

{
  "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: ...
    ]
  ]}

在这里,元组的第三个元素是 "argument list," 无论是函数接受的参数列表(如上所述)还是应用于函数调用的参数。

祝你在编译器冒险中好运!