Skip to content

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

Open

Description

@genderev

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.

Activity

  1. lexanth commented on Nov 29, 2021

    @lexanth
    Owner

    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions