Skip to content

nvs ast

nvs ast <file> parses one file and prints its syntax tree (the structure that the parser builds from the code).

The tree is printed with one level of indentation for each node, and each node has the position of its text in the file. The command only parses. It does not check names or types, so it can print a tree for a file that has errors in nvs check.

--json prints the tree as JSON for a tool. Each node has kind, span and children. Comments and whitespace are nodes too.

The command prints a tree for a file with syntax errors too. With --strict, it prints no tree when the parser reported an error.

Good to know: the JSON does not contain the text of a string or a number written in the code. Use the span of the node to read the text from the file.

Examples

How an expression is grouped

<?nvs
// Shows how `nvs ast --json` tells you which operator runs first.
// Run `nvs ast --json 01-how-an-expression-is-grouped.nvs` to see the tree of this file.
// In the tree, the `Binary` node with `"op":"Add"` has the `Binary` node with
// `"op":"Mul"` as its second child. So `3 * 4` runs first, and this prints `14`.
echo 2 + 3 * 4, "\n";
// The parentheses change the tree. Now the first child of `Mul` is a `Paren` node,
// and `Add` is inside it. So `2 + 3` runs first, and this prints `20`.
echo (2 + 3) * 4, "\n";
Output
14
20