Search code examples
python-3.xcompiler-constructionantlr

ANTLR4: Use getText() in label of python


I'm currently having one issue with ANTLR4. I have previously worked with ANTLR4 and generated the classes in Java. I would then be able whenever I found a label to do: ctx.label.getText() to get the text in the label.

Now I'm trying to do the same thing in Python3, however, it is not working. For example in this grammar when I try to access the value.

expression
    : LPARENS expression RPARENS       
    | ...                                     
    | value=(INTEGER | FLOAT | BOOLEAN | STRING | HOLE)                         
    ;

When trying to access ctx.value.getText() it gives me the following error:

print(ctx.value.getText()) AttributeError: 'CommonToken' object has no attribute 'getText'

Since I'm pretty new in using antlr4 with python was wondering what workaround exists for this.


Solution

  • In case of tokens, value=TOKEN, it’s .text:

    print(ctx.value.text)
    

    In case of a parser rule, value=expression, then it is value.getText(), I believe.