lexanth / python-ast

Python (3) Parser for JavaScript/TypeScript (based on antlr4ts)
MIT License
14 stars 5 forks source link

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

Open genderev opened 2 years ago

genderev commented 2 years ago

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 commented 2 years ago

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