Discussion forum for David Beazley

Run SLY sample code failed


#1

Hi,

When I tried to run the the sample code with python3.6, it failed with the error message as follwing. Was I missing something?

Traceback (most recent call last):_
  File "C:\BobFeng\ToolDev\Parser\sly_parser_test\Sample.py", line 3, in <module>_
    class CalcLexer(Lexer):_
  File "C:\BobFeng\ToolDev\Parser\sly_parser_test\Sample.py", line 5, in CalcLexer_
    tokens = { ID, NUMBER, PLUS, MINUS, TIMES,DIVIDE, ASSIGN, LPAREN, RPAREN }_
NameError: name 'ID' is not defined_

The sample code:

from sly import Lexer

class CalcLexer(Lexer):
    # Set of token names.   This is always required
     tokens = { ID, NUMBER, PLUS, MINUS, TIMES,
           DIVIDE, ASSIGN, LPAREN, RPAREN }

    # String containing ignored characters between tokens
    ignore = ' \t'

    # Regular expression rules for tokens
    ID      = r'[a-zA-Z_][a-zA-Z0-9_]*'
    NUMBER  = r'\d+'
    PLUS    = r'\+'
    MINUS   = r'-'
    TIMES   = r'\*'
    DIVIDE  = r'/'
    ASSIGN  = r'='
    LPAREN  = r'\('
    RPAREN  = r'\)'

if __name__ == '__main__':
    data = 'x = 3 + 42 * (s - t)'
    lexer = CalcLexer()
    for tok in lexer.tokenize(data):
    print('type=%r, value=%r' % (tok.type, tok.value))

Thanks,
Bob


#2

You’re very likely using an older version of SLY where token names are specified as strings. Consider updating.