Making a Programming Language in Python – Part 5 – Parsing Variables

Python

Video is ready, Click Here to View ×


In this part, we start parsing variable declarations by getting all the important values we need for doing object generation and we also do some error validation. The main purpose of this is to setup the foundation for the object generation stage.

Previous video – https://youtu.be/ljkbswfeZLY
Full Playlist – https://www.youtube.com/playlist?list=PLP7hn9TNf1CEl8A8jQfZSRYcgUIqBhIJU

Website – https://ryanmaugin.github.io
Instagram – @bufferscope

6 thoughts on “Making a Programming Language in Python – Part 5 – Parsing Variables

  1. I get the following error when running "var hello = 5;" Also, you can have a variable name of "var". I've included the code below and the output.
    Output:
    [['VAR_DECLARATION', 'var'], ['ERROR', 'var'], ['IDENTIFIER', 'hello'], ['ERROR', 'hello'], ['OPERATOR', '='], ['ERROR', '='], ['INTEGER', '5;'], ['ERROR', '5;']]
    Variable type: var
    ERROR! Missing or invalid assignment operator: hello. It should be '='

    Code:
    def parse(self): # Initiates the parse(self) function.
    while self.token_index < len(self.tokens):
    token_type = self.tokens[self.token_index][0] # Holds all the types of tokens we may come across.
    token_value = self.tokens[self.token_index][1] # Holds all the values of tokens we may com across.

    if token_type == "VAR_DECLARATION" and token_value == "var":
    self.parse_variable_declaration(self.tokens[self.token_index:len(self.tokens)])

    self.token_index += 1 # Increase the index value so we can increment through the whole value.

    def parse_variable_declaration(self, token_stream):
    tokens_checked = 0
    for token in range(0, len(token_stream)):
    token_type = token_stream[tokens_checked][0]
    token_value = token_stream[tokens_checked][1]

    if token_type == "STATEMENT_END": break

    if token == 0:
    print('Variable type: ' + token_value)

    elif token == 1 and token_type == "IDENTIFIER":
    print('ERROR! Invalid variable name '' + token_value + ''')
    quit()

    elif token == 2 and token_type == "OPERATOR":
    print('Assignment operator: ' + token_value)

    elif token == 2 and token_type != "OPERATOR":
    print('ERROR! Missing or invalid assignment operator: ' + token_value + '. It should be '='')
    quit()

    elif token == 2 and token_type in ['STRING', 'INTEGER', 'IDENTIFIER']:
    print('Variable value: ' + token_value)

    elif token == 2 and token_type not in ['STRING', 'INTEGER', 'IDENTIFIER']:
    print("Invalid variable assignment value '" + token_value + "'.")
    quit()

    tokens_checked += 1

Leave a Reply

Your email address will not be published. Required fields are marked *