solidity-parser / parser

A Solidity parser for JS built on top of a robust ANTLR4 grammar
MIT License
157 stars 44 forks source link

AST to code? #117

Closed maytinhdibo closed 2 months ago

maytinhdibo commented 7 months ago

How to export code from AST?

nicolasembleton commented 2 months ago

Get your node, look for the range, then take your initial string and just do

const source = readFileSync("/path/to/your/file.sol").toString();
const ast = parse(source, {range: true});

// find node / subnode
const oneNode = ast.children[0];
const myCode = source.slice(oneNode.range[0], oneNode.range[1]);
console.log("MyCode", myCode);

And you're done. Make sure to pass range: true in the parse options.