AST in JSON format

Kevin Curtis kevinc1846 at googlemail.com
Mon Nov 16 16:49:43 PST 2009


I have tweaked the JsonML AST format (shorter element names and
operator tokens not names eg ">=" instead of "GTE") and added an
evaluate() function which can execute the JsonML string. Example:

> more example.js
var source = "x = 2; if (x > 1) print(x + 3);";

print("--- js source ---");
print(source);
print("");

print("--- ast ---");
var ast = JSON.AST.parse(source);
print(ast);
print("");

print("--- evaluate(ast) ---");
JSON.AST.evaluate(ast);


> ./shell_g example.js
--- js source ---
x = 2; if (x > 1) print(x + 3);

--- ast ---
["Program",
  ["ExprStmt",
    ["Assign",
      {"op":"="},
      ["Id",
        {"name":"x"}
      ],
      ["Literal",
        {"handle":2}
      ]
    ]
  ],
  ["If",
    ["CompareOp",
      {"op":">"},
      ["Id",
        {"name":"x"}
      ],
      ["Literal",
        {"handle":1}
      ]
    ],
    ["ExprStmt",
      ["Call",
        ["Id",
          {"name":"print"}
        ],
        ["BinOp",
          {"op":"+"},
          ["Id",
            {"name":"x"}
          ],
          ["Literal",
            {"handle":3}
          ]
        ]
      ]
    ],
    ["EmptyStmt"]
  ]
]

--- evaluate(ast) ---
5


More information about the es-discuss mailing list