Practical
Practical
Session: 2024-2025
Index
Experiment 1: Introduction to compiler design…1
Experiment 2: Token calculation………………………..2
Experiment 3: Top down parsing to check balance
parenthesis……………………………………………………3-4
Experiment 4: LL(1) parsing……………………………5-7
Experiment 5: Handling basic operator
precedence……………………………………………………8-10
Experiment 6: LALR parsing in bottom-up
parsing…………………………………………………………11-13
Experiment 7: CLR parser in bottom-up parsing…..
…………………………………………………………………14-16
EXPERIMENT: 1 PAGE NO.: 1
AIM: Introduction of compiler design
Theory:
Compiler Design is a branch of computer science that focuses on developing compilers — programs
that translate code written in a high-level programming language (like C, Java, or Python) into
machine code that a computer can execute.
Compilers play a crucial role in software development by bridging the gap between human-readable
code and machine-executable instructions. The process involves analysing, optimizing, and
converting the source code efficiently and correctly.
• Builds strong fundamentals for fields like language processing, AI, cybersecurity, and
operating systems.
Real-World Examples
PROGRAM:
import re def
tokenize(code):
tokens = []
pattern = r"(?P<ID>[a-zA-Z_][a-zA-Z0-9_]*)|(?P<NUM>\d+)|(?P<OP>[+\-
*/=])|(?P<PUNC>[();{}])|(?P<WS>\S+)"
match.group(kind) if kind!=
"WS":#skip whitespace
tokens.append((kind,value)) return
token_value in tokens:
print(f"({token_type}, {token_value})")
OUTPUT:
(ID, x)
(OP, =)
(NUM, 10)
(OP, +)
(ID, y)
(PUNC, ;)
EXPERIMENT:3 PAGE NO.: 3
AIM: Write a program for top-down parsing to check the balance parenthesis PROGRAM:
# Recursive Descent Parser to check balanced parentheses
# Test cases
PAGE NO.:4
test_input = input("Enter a string of parentheses: ")
is_balanced(test_input) OUTPUT:
Input is balanced
EXPERIMENT: 4 PAGE NO.: 5
PROGRAM:
parsing_table = {
'T\'': {'+': ['ε'], '*': ['*', 'F', 'T\''], ')': ['ε'], '$': ['ε']},
def parse(input_tokens):
input_tokens.append('$') index = 0
print(f"\n{'Stack':<20}{'Input':<20}{'Action'}")
while stack:
top = stack[-1]
current_input = input_tokens[index]
print(f"{str(stack):<20}{str(input_tokens[index:]):<20}", end='')
if top == current_input:
stack.pop()
index += 1
print(f"Match '{top}'")
stack.pop()
production = parsing_table[top][current_input]
if production != ['ε']:
PAGE NO.: 6
for symbol in reversed(production):
stack.append(symbol)
else:
return
if index == len(input_tokens):
# Example test
= []
i = 0 while i <
len(expression): if
expression[i:i+2] == 'id':
tokens.append('id')
i += 2
else:
tokens.append(expression[i])
i += 1
parse(tokens)
OUTPUT:
Input Action
['$', "E'", 'T'] ['id', '+', 'id', '*', 'id', '$']Output: T → F T'
['$', "E'", "T'", 'id']['id', '+', 'id', '*', 'id', '$']Match 'id'
Parsing successful
EXPERIMENT: 5 PAGE NO.: 8
PROGRAM:
def precedence(op):
if op in ('+', '-'):
return 1 if
op in ('*', '/'):
return 2
return 0
if op == '+': return a + b
if op == '-': return a - b
if op == '*': return a * b
if op == '/': return a / b
def evaluate(expression):
i=0
i += 1
continue
elif expression[i].isdigit():
val = 0
i += 1
values.append(val)
i -= 1
# Opening bracket
ops.append(expression[i])
val2 = values.pop()
val1 = values.pop() op
= ops.pop()
# Operator
else:
val2 = values.pop()
val1 = values.pop() op
= ops.pop()
ops.append(expression[i])
i += 1
# Final computation
while ops:
val2 = values.pop()
PAGE NO.: 10
return values[0]
OUTPUT:
Enter an arithmetic expression: 3+5*5
Result: 28
EXPERIMENT: 6 PAGE NO.: 11
PROGRAM:
class LALRParser:
def __init__(self):
self.stack = [0]
self.input = []
self.table = {}
self.rules = {
2: ('E', ['id']),
self.table = {
{self.input}")
while True:
state = self.stack[-1]
symbol = self.input[pos]
if action is None:
if action == 'accept':
print("Parse successful")
next_state = int(action[1:])
Stack: {self.stack}")
LALRParser()
parser.build_table()
OUTPUT:
LALR Parser Output:
Parse successful
'
Parse successful
EXPERIMENT: 7 PAGE NO.: 14
PROGRAM:
__init__(self):
self.input = []
self.action = {}
self.goto = {}
self.action = {
self.goto = {
(0, 'E'): 1,
(4, 'E'): 1
PAGE NO.: 15
while True:
if action is None:
if action == 'accept':
print("Parse successful")
if action.startswith('s'):
next_state = int(action[1:])
self.stack.append((next_state, lookahead))
pos += 1
elif action.startswith('r'):
rule = int(action[1:])
# Simulate a generic rule length of 2 for now (should be based on actual grammar)
pop_count = 2 self.stack =
self.stack.append((goto_state, 'E'))
CLRParser()
parser.build_tables(None)
OUTPUT:
Shift to state 2, Stack: [(0, None), (2, 'id'), (4, '+'), (2, 'id')]
'
Error at position 3