-
Notifications
You must be signed in to change notification settings - Fork 72
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to turn ast into PHP code #969
Comments
I'm new to this project, but I believe you will want to use something like php-writer for that. |
Possibly helpful: It's not exactly turning an AST into code, but if you just want to make changes to some PHP code based on the |
@loilo Hi, do you have a code example for traversing or visitors with php-parser? |
@yaegassy Sure. You basically have to recursively check all properties of a node to find descendant nodes, where a node is defined by having a Here's some code defining a /**
* Check whether a value resembles a php-parser AST node
*
* @param value The value to check
*/
function isNode(value) {
return (
typeof value === 'object' &&
value !== null &&
typeof value.kind === 'string'
)
}
/**
* Collect the child nodes of an AST node
*
* @param node The node to search for child nodes
*/
function collectChildNodes(node) {
const childNodes = []
// Walk all AST node properties, performing a recursive `walk`
// on everything that looks like another AST node
for (const key of Object.keys(node)) {
const property = node[key]
if (Array.isArray(property)) {
// Step into arrays and walk their items
for (const propertyElement of property) {
if (isNode(propertyElement)) {
childNodes.push(propertyElement)
}
}
} else if (isNode(property)) {
childNodes.push(property)
}
}
return childNodes
}
/**
* Walk an AST recursively
*
* @param callback A function to invoke for every node
* @param node The tree to visit
* @param parent The parent of the (sub)tree node
*/
function walk(callback, node, parent = undefined) {
const children = collectChildNodes(node)
for (const child of children) {
walk(callback, child, node)
}
callback(node, parent)
} |
@loilo Thanks, I will refer to it. 🙇 |
const parser = new engine({
// some options :
parser: {
extractDoc: true,
php7: true,
},
ast: {
withPositions: true,
},
});
// Load a static file (Note: this file should exist on your computer)
const phpcode = fs.readFileSync("./1.php", {
encoding: "utf-8"
});
let ast=parser.parseCode(phpcode);
now:
How to turn ast into PHP code?
The text was updated successfully, but these errors were encountered: