Search code examples
abstract-syntax-treecompiler-construction

Function Parameters in an AST?


Im writing a Complier, and currently im trying to sketch out ASTs of my example codes that I know how it works. What confuses me though, is, how exactly I would represent it. I looked online for JavaScript ASTs, but they didn't have any Parameter declarations in a function declaration, which confused me. So how exactly do I draw an AST for a function with two parameters? Do I put them in the function declaration at all?


Solution

  • I have no experience with compiler design, but my job leads me to stare at a lot of ASTs. Here are a few examples of the specific topic you mentioned — parameters in a function declaration.

    JavaScript (via esprima) includes function parameters as a property of the function declaration node. An example declaration of myFunction with arguments argOne and argTwo is below:

    {
      "type": "FunctionDeclaration",
      "id": {
        "type": "Identifier",
        "name": "myFunction"
      },
      "params": [
        {
          "type": "Identifier",
          "name": "argOne"
        },
        {
          "type": "Identifier",
          "name": "argTwo"
        }
      ],
      "body": { ... }
    }
    

    As another example, consider the golang type for a FuncDecl.

    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
    }
    

    Function parameters are kept under the Type key, whose type includes a Params list:

    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
    }
    

    As a final example, for variety, consider the quoted form of an Elixir function with two parameters.

    {:def, [context: Elixir, import: Kernel],
      [
        {:myFunction, [context: Elixir],
         [{:argOne, [], Elixir}, {:argTwo, [], Elixir}]},
        [
          do: ...
        ]
      ]}
    

    Here, the third element of a tuple is the "argument list," whether that's the list of arguments accepted by a function (as above) or the arguments applied to a function call.

    Good luck in your compiler adventures!