Chris@0: JSON representation Chris@0: =================== Chris@0: Chris@0: Nodes (and comments) implement the `JsonSerializable` interface. As such, it is possible to JSON Chris@0: encode the AST directly using `json_encode()`: Chris@0: Chris@0: ```php Chris@0: create(ParserFactory::PREFER_PHP7); Chris@0: Chris@0: try { Chris@0: $stmts = $parser->parse($code); Chris@0: Chris@0: echo json_encode($stmts, JSON_PRETTY_PRINT), "\n"; Chris@0: } catch (PhpParser\Error $e) { Chris@0: echo 'Parse Error: ', $e->getMessage(); Chris@0: } Chris@0: ``` Chris@0: Chris@0: This will result in the following output (which includes attributes): Chris@0: Chris@0: ```json Chris@0: [ Chris@0: { Chris@0: "nodeType": "Stmt_Function", Chris@0: "byRef": false, Chris@0: "name": { Chris@0: "nodeType": "Identifier", Chris@0: "name": "printLine", Chris@0: "attributes": { Chris@0: "startLine": 4, Chris@0: "endLine": 4 Chris@0: } Chris@0: }, Chris@0: "params": [ Chris@0: { Chris@0: "nodeType": "Param", Chris@0: "type": null, Chris@0: "byRef": false, Chris@0: "variadic": false, Chris@0: "var": { Chris@0: "nodeType": "Expr_Variable", Chris@0: "name": "msg", Chris@0: "attributes": { Chris@0: "startLine": 4, Chris@0: "endLine": 4 Chris@0: } Chris@0: }, Chris@0: "default": null, Chris@0: "attributes": { Chris@0: "startLine": 4, Chris@0: "endLine": 4 Chris@0: } Chris@0: } Chris@0: ], Chris@0: "returnType": null, Chris@0: "stmts": [ Chris@0: { Chris@0: "nodeType": "Stmt_Echo", Chris@0: "exprs": [ Chris@0: { Chris@0: "nodeType": "Expr_Variable", Chris@0: "name": "msg", Chris@0: "attributes": { Chris@0: "startLine": 5, Chris@0: "endLine": 5 Chris@0: } Chris@0: }, Chris@0: { Chris@0: "nodeType": "Scalar_String", Chris@0: "value": "\n", Chris@0: "attributes": { Chris@0: "startLine": 5, Chris@0: "endLine": 5, Chris@0: "kind": 2 Chris@0: } Chris@0: } Chris@0: ], Chris@0: "attributes": { Chris@0: "startLine": 5, Chris@0: "endLine": 5 Chris@0: } Chris@0: } Chris@0: ], Chris@0: "attributes": { Chris@0: "startLine": 4, Chris@0: "comments": [ Chris@0: { Chris@0: "nodeType": "Comment_Doc", Chris@0: "text": "\/** @param string $msg *\/", Chris@0: "line": 3, Chris@0: "filePos": 9, Chris@0: "tokenPos": 2 Chris@0: } Chris@0: ], Chris@0: "endLine": 6 Chris@0: } Chris@0: } Chris@0: ] Chris@0: ``` Chris@0: Chris@0: The JSON representation may be converted back into an AST using the `JsonDecoder`: Chris@0: Chris@0: ```php Chris@0: decode($json); Chris@0: ``` Chris@0: Chris@0: Note that not all ASTs can be represented using JSON. In particular: Chris@0: Chris@0: * JSON only supports UTF-8 strings. Chris@0: * JSON does not support non-finite floating-point numbers. This can occur if the original source Chris@0: code contains non-representable floating-pointing literals such as `1e1000`. Chris@0: Chris@0: If the node tree is not representable in JSON, the initial `json_encode()` call will fail. Chris@0: Chris@0: From the command line, a JSON dump can be obtained using `vendor/bin/php-parse -j file.php`.