Basic Compiler Design Gaming Project in C++

Explanation

  1. Token Types:
    • TokenType is an enum class that defines different types of tokens: NUMBER, PLUS, MINUS, MULTIPLY, DIVIDE, END, and INVALID.
  2. Token Structure:
    • Token holds the type of token and its value (if it’s a number).
  3. Lexer Class:
    • Purpose: Breaks the input text into tokens.
    • Methods:
      • getNextToken(): Reads characters from the input and generates tokens. It handles numbers and arithmetic operators.
      • advance(): Moves to the next character in the input.
      • skipWhitespace(): Skips over whitespace characters.
      • getNumber(): Extracts multi-digit numbers from the input.
  4. Parser Class:
    • Purpose: Parses the tokens generated by the lexer and evaluates the arithmetic expression.
    • Methods:
      • parse(): Starts the parsing process and returns the result.
      • eat(TokenType type): Consumes a token of the specified type.
      • factor(): Parses a number token.
      • term(): Handles multiplication and division operations.
      • expression(): Handles addition and subtraction operations.
  5. Main Function (main):
    • Reads an arithmetic expression from the user.
    • Initializes the lexer and parser.
    • Parses the expression and outputs the result.
    • Handles errors gracefully using exception handling.

Leave a Comment

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

Scroll to Top