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

How do you walk the AST with the use of ctx? #2

Open
genderev opened this issue Nov 29, 2021 · 1 comment
Open

How do you walk the AST with the use of ctx? #2

genderev opened this issue Nov 29, 2021 · 1 comment

Comments

@genderev
Copy link

I think that in order to use this library, I need to do something like:

import { walk, parse, createVisitor } from 'python-ast';

let ast = parse(`
print("hello world!)
`);

let listener = createVisitor(ast);

walk(ast, listener);

but I got this error:

no viable alternative at input '!'
ctx.enterRule(listener);
            ^
TypeError: Cannot read property 'enterRule' of undefined

This library is quite opaque to me. I've been unable to use antlr4 directly (by installing antlr4 using npm). I'm not sure why I'm getting this error.

@lexanth
Copy link
Owner

lexanth commented Nov 29, 2021

First off, your python is broken:

print("hello world!)

should be

print("hello world!")

Then there are two APIs - visitors and listeners. Your example mixes the two. You need to say what you want the visitor or listener to do (or you can read from the AST directly, but it's not as useful normally).

The visitor API is on the README.
The listener API is something like this

const ast = parse(`
print("hello world!")
`);

 walk(
    {
      enterAtom: (a) => console.log(a.text),
    },
    ast,
   );

which would log print (for the print function) and "hello world!" for the variable it calls.

I suggest using typescript if possible - the type definitions are the best documentation, followed by https://github.com/antlr/grammars-v4/blob/master/python/python3-ts/Python3.g4 if you can read the ANTLR grammar

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

No branches or pull requests

2 participants