AST in JSON format

Kevin Curtis kevinc1846 at googlemail.com
Sun Dec 6 04:19:01 PST 2009


Re the idea of standardizing a serialization format in JsonML of the
ECMAScript AST based on the ECMAScript grammar.

The ecmascript-ast project's JSON.AST.parse() function now serializes
all of the grammar/AST to JsonML (I think). JSON.AST.evaluate() is
rudimentary (example.js and ast-test/if.js and while.js work!) The
code to build JSON.AST on V8 is at:
http://code.google.com/p/ecmascript-ast/

JSON.AST - like the JSON object - could initially be implemented in
pure javascript. (evaluate() could parse JsonML and generate JS which
could then be eval'ed). Then engines could determine whether to do
native implementations. A native JSON.AST.parse() outputting JsonML
should be relatively straighforward. JSON.AST.evaluate() is more
tricky - 2 alternatives. Parse and execute the JsonML directly. Or
parse the JsonML to JS - and then the JS can be eval'ed. (A JsonML to
JS function is probably desirable in any case).

Here's an example of parsing JS source to JsonML AST:

>./ast.sh ast-test/while.js
--- js source ---
x = 1;
while (x < 5) { print(x); x = x + 1; };

--- ast ---
["Program",
  ["ExprStmt",
    ["Assign",
      {"op":"="},
      ["Id",
        {"name":"x"}
      ],
      ["Literal",
        {"handle":1}
      ]
    ]
  ],
  ["While",
    ["CompareOp",
      {"op":"<"},
      ["Id",
        {"name":"x"}
      ],
      ["Literal",
        {"handle":5}
      ]
    ],
    ["Block",
      ["ExprStmt",
        ["Call",
          ["Id",
            {"name":"print"}
          ],
          ["Id",
            {"name":"x"}
          ]
        ]
      ],
      ["ExprStmt",
        ["Assign",
          {"op":"="},
          ["Id",
            {"name":"x"}
          ],
          ["BinOp",
            {"op":"+"},
            ["Id",
              {"name":"x"}
            ],
            ["Literal",
              {"handle":1}
            ]
          ]
        ]
      ]
    ]
  ]
]

--- evaluate(ast) ---
1
2
3
4


More information about the es-discuss mailing list