Skip to content
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

[feature] implement a visitor & filter helper #198

Open
ichiriac opened this issue Oct 7, 2018 · 2 comments
Open

[feature] implement a visitor & filter helper #198

ichiriac opened this issue Oct 7, 2018 · 2 comments

Comments

@ichiriac
Copy link
Member

ichiriac commented Oct 7, 2018

implement a visitor helper in order to handle AST transversal :

const ast = parser.parse('...some code...');

// visiting child nodes :
ast.visit(function(node) {
  // do something
});

// filtering a list of nodes
const nodes = ast.filter(function(node) {
  return node.kind === 'something';
});

NOTE : this is implemented on each node, can be used on program node as in the example, or on any other node

@cedw032
Copy link

cedw032 commented Jan 20, 2021

Is anything happening with this? I'm trying to get a complete traversable AST but from the types and documentation, I cannot tell how basic traversing is supposed to be achieved. I am very interested in using this package but am having trouble getting started. Any help would be appreciated.

Does anyone have a demo of basic tree traversal? I can only see as deep as the class declaration. Also, the AST seems to print nicely but is showing no children of my class, and no errors...

@ichiriac
Copy link
Member Author

ichiriac commented Feb 1, 2021

Hi @cedw032, glad to see your interest for this library.

If you want to see some usage you can check this other project, but it may seem hard to read : https://github.com/glayzzle/php-reflection

You have the documentation here : https://php-parser.glayzzle.com/readme and the structure of nodes is documented here : https://php-parser.glayzzle.com/api/ast.js

The main idea of the visitor is to recursivelly scan each property node, and to launch the visit callback when you find a kind property on an entity.

Here a pseudo example :

function visit(node, parent, cb) {
  cb(node.kind, node, parent);
  for(var k in node) {
    var child = node[k];
    if (typeof child.type === 'string') {
     cb(child.kind, child, node);
    } else if (Array.isArray(child) ... ) {
       ....
    } else if (typeof child === 'object) { 
       ....
    }
  }
}

And the filter is something similar with filtering callback and returns an array of nodes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants