0% found this document useful (0 votes)
5 views12 pages

Compiler Design

The document outlines a Compiler Design Lab report for B.Tech (CSE) students, detailing various programming tasks related to automata and grammar analysis. It includes programs for constructing a DFA, finding First and Follow sets, and removing left recursion and left factoring from grammars. Each task is accompanied by code implementations and example outputs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views12 pages

Compiler Design

The document outlines a Compiler Design Lab report for B.Tech (CSE) students, detailing various programming tasks related to automata and grammar analysis. It includes programs for constructing a DFA, finding First and Follow sets, and removing left recursion and left factoring from grammars. Each task is accompanied by code implementations and example outputs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Compiler Design Lab , BTCSE 604

B.Tech (CSE) 6th Semester, 3rd Year


Section – ‘C’

Submitted By - Submitted
To -
PIYUSH CHAUHAN Ms Pooja Gupta
2021-310-173 (Assistant Professor)

Jamia Hamdard
School Of Engineering Sciences & Technology
Department Of Computer Science & Engineering
New Delhi-110062

1
INDEX

Sno TITLE Date Teachers


Signature
1. DFA for all Strings starting with 7-02-2024
a
2 Program to find First of a given 16-02-
grammar 2024
3 Program to find Follow for a 6-03-2024
given grammar
4 Program to remove Left 3-04-2024
Recursion from a given Grammar
5 Program to remove Left Factorial 3-04-2024
from a given Grammar

2
Learning Objective:
DFA for all Strings starting with a

Task:
class DFA:
def __init__(self):
self.states = {'q0', 'q1'}
self.alphabet = {'a', 'b'}
self.start_state = 'q0'
self.accept_states = {'q1'}
self.transitions = {
'q0': {'a': 'q1', 'b': 'q0'},
'q1': {'a': 'q1', 'b': 'q1'}
}

def is_accepted(self, string):


current_state = self.start_state
for symbol in string:
if symbol not in self.alphabet:
return False
current_state = self.transitions[current_state].get(symbol, None)
if current_state is None:
return False
return current_state in self.accept_states

dfa = DFA()
strings = ['a', 'aa', 'ab', 'ba', 'bab', 'bbb', 'aab']
for string in strings:
if dfa.is_accepted(string):
print(f"'{string}' is accepted")
else:
print(f"'{string}' is not accepted")

3
4
Learning Objective:
Program to find First of a given grammar

Task:
def find_first(grammar):
first = {}
def first_of_symbol(symbol):
if symbol in first:
return first[symbol]
first_set = set()
productions = grammar[symbol]
for production in productions:
first_symbol = production[0]
if first_symbol.isupper():
first_set.update(first_of_symbol(first_symbol))
else:
first_set.add(first_symbol)
return first_set
for non_terminal in grammar:
first[non_terminal] = first_of_symbol(non_terminal)
return first
grammar = {
'S': ['aAB', 'bBC', 'c'],
'A': ['d', ''],
'B': ['e', ''],
'C': ['f', '']
}
first_set = find_first(grammar)
for non_terminal, first in first_set.items():
print(f"First({non_terminal}): {first}")

5
Learning Objective:
Program to find Follow for a given grammar

Task:
def find_follow(grammar, start_symbol):
follow = {}
def first_of_string(string):
first_set = set()
for symbol in string:
if symbol.isupper():
first_set.update(first[symbol])
if '' not in first[symbol]:
break
else:
first_set.add(symbol)
break
return first_set
def follow_of_symbol(symbol):
if symbol in follow:
return follow[symbol]
follow_set = set()
if symbol == start_symbol:
follow_set.add('$')
for non_terminal, productions in grammar.items():
for production in productions:
for idx, prod_symbol in enumerate(production):
if prod_symbol == symbol:
if idx < len(production) - 1:
follow_set.update(first_of_string(production[idx +
1:]))
if '' in follow_set:
follow_set.remove('')

follow_set.update(follow_of_symbol(non_terminal))
else:
if non_terminal != symbol:

6
follow_set.update(follow_of_symbol(non_terminal))
return follow_set

for non_terminal in grammar:


follow[non_terminal] = follow_of_symbol(non_terminal)
return follow
grammar = {
'S': ['AB', 'BC'],
'A': ['aA', ''],
'B': ['bB', ''],
'C': ['cC', '']
}
start_symbol = 'S'
follow_set = find_follow(grammar, start_symbol)
for non_terminal, follow in follow_set.items():
print(f"Follow({non_terminal}): {follow}")

7
Leaning Objective:

Program to remove Left Recursion from a given Grammar

Task:
def remove_left_recursion(grammar):
non_terminals = list(grammar.keys())
new_grammar = {}
for A in non_terminals:
productions = grammar[A]
alpha_productions = []
beta_productions = []
for production in productions:
if production.startswith(A):
alpha_productions.append(production[1:])
else:
beta_productions.append(production)
if alpha_productions:
A_prime = A + "'"
new_grammar[A_prime] = [alpha_prod + A_prime for alpha_prod in
alpha_productions] + ['']
new_productions = [beta + A_prime for beta in beta_productions]
else:
new_productions = productions

new_grammar[A] = new_productions

return new_grammar
grammar = {
'E': ['E+T', 'T'],
'T': ['T*F', 'F'],
'F': ['(E)', 'id']
}
new_grammar = remove_left_recursion(grammar)
for non_terminal, productions in new_grammar.items():
print(f"{non_terminal} -> {' | '.join(productions)}")

8
9
Learning Objective:
Program to remove Left Factorial from a given Grammar

Task:

def remove_left_factoring(grammar):
non_terminals = list(grammar.keys())
new_grammar = {}
for A in non_terminals:
productions = grammar[A]
common_prefixes = {}
for production in productions:
prefix = ''
for symbol in production:
prefix += symbol
if prefix in common_prefixes:
common_prefixes[prefix].append(production)
else:
common_prefixes[prefix] = [production]
new_productions = []
for prefix, alternatives in common_prefixes.items():
if len(alternatives) > 1:
A_prime = A + "'"
new_grammar[A_prime] = [alternative[len(prefix):] for
alternative in alternatives]
new_productions.append(prefix + A_prime)
else:
new_productions.extend(alternatives)
new_grammar[A] = new_productions
return new_grammar
grammar = {
'S': ['abA', 'abB', 'cdC', 'cdD'],
'A': ['x', 'y'],
'B': ['p', 'q'],
'C': ['m', 'n'],
'D': ['z', 'w']
}

10
new_grammar = remove_left_factoring(grammar)
for non_terminal, productions in new_grammar.items():
print(f"{non_terminal} -> {' | '.join(productions)}")

11
Thank You

12

You might also like