Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views5 pages

Pes1ug22am181 CD Lab2

The document presents a Python script for a symbol table implementation used in compiler design. It includes functionalities to add, display, search, and delete symbols, as well as parse Python code to extract variable declarations. The script also provides a user interface for performing various operations on the symbol table.

Uploaded by

vivirocz
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)
9 views5 pages

Pes1ug22am181 CD Lab2

The document presents a Python script for a symbol table implementation used in compiler design. It includes functionalities to add, display, search, and delete symbols, as well as parse Python code to extract variable declarations. The script also provides a user interface for performing various operations on the symbol table.

Uploaded by

vivirocz
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/ 5

COMPILER DESIGN

LAB -2

VAISHNAVI P KUDALKAR
PES1UG22AM181
AIML C-SECTION

CODE:

symboltable.py

import re

class SymbolTable:
def __init__(self):
self.table = []

def add_symbol(self, token_name, var_type, line_number, storage, scope,


value):
symbol = {
"Token Name": token_name,
"Type": var_type,
"Line Number": line_number,
"Storage": storage,
"Scope": scope,
"Value": value
}
self.table.append(symbol)

def display_symbol_table(self):
if not self.table:
print("Symbol Table is empty.")
return

print("\n{:<15} {:<10} {:<12} {:<10} {:<10} {:<10}".format(


"Token Name", "Type", "Line Number", "Storage", "Scope", "Value"
))
print("-" * 70)
for symbol in self.table:
print("{:<15} {:<10} {:<12} {:<10} {:<10} {:<10}".format(
symbol["Token Name"], symbol["Type"], symbol["Line Number"],
symbol["Storage"], symbol["Scope"], symbol["Value"]
))

def search_symbol(self, token_name):


for symbol in self.table:
if symbol["Token Name"] == token_name:
print("Symbol Found:")
print(symbol)
return
print("Symbol not found.")

def delete_symbol(self, token_name):


for symbol in self.table:
if symbol["Token Name"] == token_name:
self.table.remove(symbol)
print(f"Symbol '{token_name}' deleted successfully.")
return
print("Symbol not found.")

def parse_python_code(file_name):
"""Parse Python-style code to extract variable declarations."""
symbol_table = SymbolTable()
storage_map = {
"int": 4,
"float": 4,
"str": 50, # Assume max string size for storage
"list": 40, # Placeholder storage size
"dict": 40, # Placeholder storage size
"bool": 1
}

try:
with open(file_name, "r") as file:
lines = file.readlines()

scope = "global" # Default scope


for line_number, line in enumerate(lines, start=1):
# Check for variable assignments
match = re.match(r"(\w+)\s*=\s*(.+)", line.strip())
if match:
var_name, value = match.groups()
# Infer the type based on the value
try:
eval_value = eval(value)
var_type = type(eval_value).__name__
except:
var_type = "unknown"

storage = storage_map.get(var_type, 0)
symbol_table.add_symbol(var_name, var_type, line_number, storage,
scope, value)

return symbol_table
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return None

def main():
file_name = input("Enter the input file name (e.g., input.py): ").strip()
symbol_table = parse_python_code(file_name)

if symbol_table:
while True:
print("\nSymbol Table Operations:")
print("1. Display Symbol Table")
print("2. Search for a Symbol")
print("3. Delete a Symbol")
print("4. Exit")
choice = input("Enter your choice: ")

if choice == "1":
symbol_table.display_symbol_table()
elif choice == "2":
token_name = input("Enter the token name to search: ")
symbol_table.search_symbol(token_name)
elif choice == "3":
token_name = input("Enter the token name to delete: ")
symbol_table.delete_symbol(token_name)
elif choice == "4":
print("Exiting...")
break
else:
print("Invalid choice! Please try again.")

if __name__ == "__main__":
main()

Input :
x = 10
y = 3.14
name = "John"
is_valid = True
my_list = [1, 2, 3]
config = {"key": "value"}

Output:

You might also like