Skip to content

Assignment statement grammar (version 1)

Main script for grammar AssignmentStatement1 (version 1)

author

Morteza Zakeri, (http://webpages.iust.ac.ir/morteza_zakeri/)

date

20201029

Required

  • Compiler generator: ANTLR 4.x
  • Target language(s): Python 3.8.x

Changelog

v2.0.0

  • A lexer and parser for simple grammar without any attribute or listener

Refs

  • Reference: Compiler book by Dr. Saeed Parsa (http://parsa.iust.ac.ir/)
  • Course website: http://parsa.iust.ac.ir/courses/compilers/
  • Laboratory website: http://reverse.iust.ac.ir/

main(args)

Create lexer and parser

Parameters:

Name Type Description Default
args str required
return None required
Source code in language_apps\assignment_statement_v1\assignment_statement1main.py
def main(args):
    """
    Create lexer and parser

    Args:

        args (str):
        return (None):
    """
    # Step 1: Load input source into stream
    stream = FileStream(args.file, encoding='utf8')
    # input_stream = StdinStream()
    # Step 2: Create an instance of AssignmentStLexer
    lexer = AssignmentStatement1Lexer(stream)
    # Step 3: Convert the input source into a list of tokens
    token_stream = CommonTokenStream(lexer)
    #
    # quit()

    # Step 4: Create an instance of the AssignmentStParser
    parser = AssignmentStatement1Parser(token_stream)
    # parser._interp.predictionMode = PredictionMode.SLL

    #x = DescriptiveErrorListener()
    #parser.addErrorListener()

    # Step 5: Create parse tree
    parse_tree = parser.start()

    # print(parse_tree)
    # quit()

    # Step 6: Create an instance of AssignmentStListener
    my_listener = MyListener()
    walker = ParseTreeWalker()
    walker.walk(t=parse_tree, listener=my_listener)

    print(f'Number of "+" operators: {my_listener.get_count()}')

    # print(parse_tree.getText())
    quit()



    # return
    lexer.reset()
    token = lexer.nextToken()
    while token.type != Token.EOF:
        print('Token text: ', token.text, 'Token line: ', token.line)
        token = lexer.nextToken()