The user wants a program that implements a compiler with lexical analysis and parsing.
-
Scope the Request:
- "Write a program": Needs code.
- "Compiler": A full compiler is huge (Lexing -> Parsing -> Semantic Analysis -> IR Generation -> Optimization -> Assembly/Bytecode Generation -> Linking).
- "Lexical Analysis and Parsing": The user explicitly requested these two specific phases. I shouldn't overcomplicate it with machine code generation unless I keep it very simple (like a calculator or an interpreter). An interpreter is often easier to demonstrate the structure of a compiler without getting bogged down in target-specific assembly.
-
Choose a Language:
- Python is readable, concise, and great for educational examples.
- C++ is traditional but verbose.
- Rust/Go are modern but might distract from the core logic.
- Decision: Python.
-
Define the Source Language:
- A simple calculator language is the standard "Hello World" for compilers.
- Let's support: Integers,
+, -, *, /, parentheses ().
- Maybe variable assignment to show how state works? Let's stick to arithmetic expressions first, maybe add variables if it doesn't clutter the code too much. Let's stick to pure arithmetic for maximum clarity on the phases.
-
Design the Components:
-
Lexer (Lexical Analysis):
- Input: String (source code).
- Output: Stream of Tokens.
- Token Types:
INTEGER, PLUS, MINUS, MUL, DIV, LPAREN, RPAREN, EOF.
- Logic: Read character by character. Skip whitespace. Group digits into numbers. Match operators.
-
Parser (Syntactic Analysis):
- Input: Stream of Tokens.
- Output: Abstract Syntax Tree (AST).
- Grammar (Standard expression grammar):
expr : term ((PLUS | MINUS) term)*
term : factor ((MUL | DIV) factor)*
factor : INTEGER | LPAREN expr RPAREN
- Method: Recursive Descent Parser (easiest to write/read).
-
Evaluator (Interpreter/Execution):
- Even though the user asked for "compiler", usually in this context, showing the result of the AST traversal effectively "compiles" the logic into a result. If I stop at the AST, the user can't see it "working". I'll add a quick interpreter step to prove the parsing worked.
-
Drafting the Code (Mental or Scratchpad):
- Token class:
Type, Value.
- Lexer class:
text, pos, current_char. advance(), skip_whitespace(), integer(), get_next_token().
- AST Nodes:
BinOp(left, op, right), Num(token).
- Parser class:
lexer, current_token. eat(type), factor(), term(), expr().
- Interpreter class:
visit(node), visit_Num, visit_BinOp.
-
Refining the Code Structure:
- I need to ensure error handling is present (e.g., "Invalid character" or "Unexpected token").
- I should encapsulate everything in a single block or class structure for easy copy-pasting.
-
Implementation Details (Self-Correction during drafting):
- Precedence: The grammar handles this.
term is higher precedence than expr. factor is highest.
- Associativity: Left recursion removal handles left associativity naturally in the loops (
while current_token in (PLUS, MINUS)).
-
Final Code Plan:
- Step 1: The Lexer. Define Token types. define the Lexer class that turns string into tokens.
- Step 2: The AST. Define simple node classes.
- Step 3: The Parser. Implement the recursive descent logic based on the grammar.
- Step 4: The Driver. Main loop to take user input and print the result.
-
Adding Explanations:
- Explain Lexical Analysis (Tokenization).
- Explain Parsing (AST creation).
- Explain the Grammar used.
-
Review against User Request:
- "Implements a compiler": Yes, the front-end (Lex + Parse) + a backend (Interpreter).
- "Lexical analysis": Yes.
- "Parsing": Yes.
-
Constructing the Output: (Proceed to generate Python code based on the plan). Self-correction: Keep it in one file.
(Drafting the Python code in the response...)
- Import
enum? No, just use basic classes for simplicity to avoid dependencies.
- Classes:
Token, Lexer, Parser, AST, BinOp, Num, Interpreter.
-
Final Polish: Add comments to the code explaining what specific parts do. Ensure the "Main" section runs an interactive shell.
(Self-Correction during final code generation):
Wait, usually a "compiler" generates code. An interpreter executes it. Since writing an assembly generator is very specific to the architecture (x86 vs ARM vs bytecode), an Interpreter is the standard academic response to "build a simple compiler/parser" because it demonstrates the semantic correctness of the parse. I will stick to an interpreter but explicitly mention that the Interpreter class acts as the back-end processing the AST.
Let's refine the grammar.
Expr -> Term + Term
Term -> Factor * Factor
Factor -> Number | (Expr)
This is standard and handles precedence correctly.
Let's write the code.
Here is a complete, working implementation of a simple compiler front-end (Lexer and Parser) written in Python.
To make this example runnable and understandable, we will implement a compiler for a simple arithmetic language that supports:
- Integers.
- Basic operators (
+, -, *, /).
- Parentheses
(, ).
The Architecture
- The Lexer (Lexical Analyzer): Converts the raw string of characters (source code) into a stream of Tokens (identifiers, keywords, symbols).
- The Parser (Syntax Analyzer): Takes the tokens and builds an Abstract Syntax Tree (AST) based on the grammar rules (precedence and associativity).
- The Interpreter (Execution): Traverses the AST to calculate the result.
The Python Code
You can save this code into a file named compiler.py and run it.
import re
# ==========================================
# 1. TOKEN DEFINITIONS
# ==========================================
class Token:
def __init__(self, type_, value=None):
self.type = type_
self.value = value
def __repr__(self):
return f"Token({self.type}, {self.value})"
# Define Token Types
class TokenType:
INTEGER = 'INTEGER'
PLUS = 'PLUS'
MINUS = 'MINUS'
MUL = 'MUL'
DIV = 'DIV'
LPAREN = 'LPAREN'
RPAREN = 'RPAREN'
EOF = 'EOF' # End of File
# ==========================================
# 2. LEXER (Lexical Analyzer)
# ==========================================
class Lexer:
def __init__(self, text):
self.text = text
self.pos = 0
self.current_char = self.text[self.pos] if self.text else None
def advance(self):
"""Advance the 'pos' pointer and set the 'current_char' variable."""
self.pos += 1
if self.pos > len(self.text) - 1:
self.current_char = None
else:
self.current_char = self.text[self.pos]
def skip_whitespace(self):
while self.current_char is not None and self.current_char.isspace():
self.advance()
def integer(self):
"""Return a (multidigit) integer consumed from the input."""
result = ''
while self.current_char is not None and self.current_char.isdigit():
result += self.current_char
self.advance()
return int(result)
def get_next_token(self):
"""Lexical analyzer (also known as scanner or tokenizer)."""
while self.current_char is not None:
if self.current_char.isspace():
self.skip_whitespace()
continue
if self.current_char.isdigit():
return Token(TokenType.INTEGER, self.integer())
if self.current_char == '+':
self.advance()
return Token(TokenType.PLUS, '+')
if self.current_char == '-':
self.advance()
return Token(TokenType.MINUS, '-')
if self.current_char == '*':
self.advance()
return Token(TokenType.MUL, '*')
if self.current_char == '/':
self.advance()
return Token(TokenType.DIV, '/')
if self.current_char == '(':
self.advance()
return Token(TokenType.LPAREN, '(')
if self.current_char == ')':
self.advance()
return Token(TokenType.RPAREN, ')')
raise Exception(f'Invalid character: {self.current_char}')
return Token(TokenType.EOF, None)
# ==========================================
# 3. AST (Abstract Syntax Tree) Nodes
# ==========================================
class AST:
pass
class BinOp(AST):
def __init__(self, left, op, right):
self.left = left
self.op = op
self.right = right
class Num(AST):
def __init__(self, token):
self.token = token
self.value = token.value
# ==========================================
# 4. PARSER (Syntax Analyzer)
# ==========================================
class Parser:
def __init__(self, lexer):
self.lexer = lexer
self.current_token = self.lexer.get_next_token()
def error(self):
raise Exception('Invalid syntax')
def eat(self, token_type):
"""Compare the current token type with the passed token type."""
if self.current_token.type == token_type:
self.current_token = self.lexer.get_next_token()
else:
self.error()
def factor(self):
"""
factor : INTEGER | LPAREN expr RPAREN
"""
token = self.current_token
if token.type == TokenType.INTEGER:
self.eat(TokenType.INTEGER)
return Num(token)
elif token.type == TokenType.LPAREN:
self.eat(TokenType.LPAREN)
node = self.expr()
self.eat(TokenType.RPAREN)
return node
def term(self):
"""
term : factor ((MUL | DIV) factor)*
"""
node = self.factor()
while self.current_token.type in (TokenType.MUL, TokenType.DIV):
token = self.current_token
if token.type == TokenType.MUL:
self.eat(TokenType.MUL)
elif token.type == TokenType.DIV:
self.eat(TokenType.DIV)
node = BinOp(left=node, op=token, right=self.factor())
return node
def expr(self):
"""
expr : term ((PLUS | MINUS) term)*
term : factor ((MUL | DIV) factor)*
factor : INTEGER | LPAREN expr RPAREN
"""
node = self.term()
while self.current_token.type in (TokenType.PLUS, TokenType.MINUS):
token = self.current_token
if token.type == TokenType.PLUS:
self.eat(TokenType.PLUS)
elif token.type == TokenType.MINUS:
self.eat(TokenType.MINUS)
node = BinOp(left=node, op=token, right=self.term())
return node
def parse(self):
return self.expr()
# ==========================================
# 5. INTERPRETER (Backend)
# ==========================================
class NodeVisitor:
def visit(self, node):
method_name = 'visit_' + type(node).__name__
visitor = getattr(self, method_name, self.generic_visit)
return visitor(node)
def generic_visit(self, node):
raise Exception(f'No visit_{type(node).__name__} method')
class Interpreter(NodeVisitor):
def __init__(self, parser):
self.parser = parser
def visit_BinOp(self, node):
if node.op.type == TokenType.PLUS:
return self.visit(node.left) + self.visit(node.right)
elif node.op.type == TokenType.MINUS:
return self.visit(node.left) - self.visit(node.right)
elif node.op.type == TokenType.MUL:
return self.visit(node.left) * self.visit(node.right)
elif node.op.type == TokenType.DIV:
return self.visit(node.left) // self.visit(node.right)
def visit_Num(self, node):
return node.value
# ==========================================
# 6. MAIN DRIVER
# ==========================================
def main():
while True:
try:
text = input("calc> ")
except EOFError:
break
if not text:
continue
try:
lexer = Lexer(text)
parser = Parser(lexer)
interpreter = Interpreter(parser)
result = interpreter.interpret()
print(result)
except Exception as e:
print(e)
if __name__ == '__main__':
main()
How it works
If you run the program and type 2 + 3 * 4, here is what happens internally:
-
Lexical Analysis:
The string "2 + 3 * 4" is split into a list of tokens:
Token(INTEGER, 2)
Token(PLUS, +)
Token(INTEGER, 3)
Token(MUL, *)
Token(INTEGER, 4)
Token(EOF, None)
-
Parsing (Recursive Descent):
The parser looks at the grammar rules defined in methods expr, term, and factor.
- It sees
2 and starts building the tree.
- It sees
+. Because of the rule expr : term ((PLUS | MINUS) term)*, it knows + is part of an expression.
- It calls
term on the right side (3 * 4).
- Inside
term, it sees *. Because of the rule term : factor ((MUL | DIV) factor)*, it groups 3 and 4 together first.
- Resulting Tree:
+
/ \
2 *
/ \
3 4
- Note that the tree structure naturally enforces Order of Operations (Precedence). Multiplication happens lower in the tree than addition, so it is evaluated first.
-
Interpretation:
The NodeVisitor walks the tree.
- It visits the
+ node.
- It visits the left child
2. Result: 2.
- It visits the right child
*.
- It visits left
3.
- It visits right
4.
- Returns 12.
- It adds 2 + 12.
- Final Result: 14.