SlideShare a Scribd company logo
1 of 8
Download to read offline
You have already implemented a lexical analyzer in Assignment #1 and a parser to recognize
grammatical rules in Assignment #2. In this assignment, you will be adding semantics to the
design of a small programming language to help implement blockchain. The goal of blockchain
is to allow digital information to be recorded and distributed, but not edited. In this way, a
blockchain is a foundation for immutable records of transactions that cannot be altered, deleted,
or destroyed. The semantics that you must implement in this assignment is as follows: 1. Each
time a new blockchain is created, you must extract attributes and verifies if each attribute has a
valid type. Returns false if at least one is invalid or returns true otherwise. 2. When the add
operator (keyword) is used, the data must be stored in a dictionary. 3. When errors are detected,
the parser must describe the error, including the line of the code where it occurs. 4. When
arithmetic expressions are used, the parser will implement the corresponding arithmetic
operations. For simplicity purposes, the blockchain only will store arithmetic expressions and
strings.
import ply.lex as lex
import ply.yacc as yacc
tokens = (
'ID',
'BLOCK',
'VAR',
'ADD',
'PRINT',
'VIEW',
'RUN',
'MINE',
'EXPORT',
'STRING',
'INT',
'LONG',
'FLOAT',
'LIST',
'TUPLE',
'DICT',
'NUMBER',
'ASSIGN',
'TYPEASSIGN',
'SEPARATOR',
'LPAREN',
'RPAREN',
'NE',
'LT',
'GT',
'LE',
'GE',
'PLUS',
'MINUS',
'STAR',
'SLASH',
'PCT',
'COMMENT',
'WHITESPACE'
)
t_ASSIGN = r'='
t_TYPEASSIGN = r':'
t_SEPARATOR = r','
t_LPAREN = r'('
t_RPAREN = r')'
t_NE = r'!='
t_LT = r'<'
t_GT = r'>'
t_LE = r'<='
t_GE = r'>='
t_PLUS = r'+'
t_MINUS = r'-'
t_STAR = r'*'
t_SLASH = r'/'
t_PCT = r'%'
t_ignore_COMMENT = r'#.'
t_ignore_WHITESPACE = r's+'
keywords = {
'BLOCK': 'KEYWORD',
'VAR': 'KEYWORD',
'ADD': 'KEYWORD',
'PRINT': 'KEYWORD',
'VIEW': 'KEYWORD',
'RUN': 'KEYWORD',
'MINE': 'KEYWORD',
'EXPORT': 'KEYWORD',
'STR':'KEYWORD',
'INT': 'KEYWORD',
'LONG': 'KEYWORD',
'FLOAT': 'KEYWORD',
'LIST': 'KEYWORD',
'TUPLE': 'KEYWORD',
'DICT':'KEYWORD',
}
tokens1 = ['ID',
'BLOCK','VAR','ADD','PRINT','VIEW','RUN','MINE','EXPORT','STRING','LONG','FLOAT','L
IST','TUPLE','DICT','NUMBER','ASSIGN','TYPEASSIGN','SEPARATOR','LPAREN','RPARE
N','NE','LT','GT','LE','GE','PLUS','MINUS','STAR','SLASH', 'PCT',
'COMMENT','WHITESPACE']
+ list(keywords.values())
# dictionary to store values
values = {}
def t_KEYWORD(t):
r'DEF | VAR | INT | IF | ELSE'
t.type = keywords.get(t.value, 'KEYWORD')
return t
def t_ID(t):
r'[a-zA-Z_][a-zA-Z_0-9]*'
t.type = keywords.get(t.value, 'ID')
return t
def t_NUM(t):
r'[0-9]+'
t.type = keywords.get(t.value, 'INT')
return t
def t_COMMENT(t):
r'//.'
t.type = keywords.get(t.value, 'COMMENT')
pass
def t_newline(t):
r'n+'
t.lexer.lineno += len(t.value)
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
def p_block(p):
"""
block : BLOCK ID ASSIGN LPAREN attributes RPAREN
| ADD ID ASSIGN LPAREN new_atts RPAREN
| PRINT ID
| RUN ID
| MINE ID
| EXPORT ID
| VIEW ID
"""
pass
def p_type(p):
"""
type : STRING
| INT
| LONG
| FLOAT
| LIST
| TUPLE
| DICT
"""
pass
def p_attribute(p):
"""
attribute : ID TYPEASSIGN type
"""
pass
def p_attributes(p):
"""
attributes : attribute
| attributes SEPARATOR attribute
"""
pass
def p_new_att(p):
"""
new_att : ID TYPEASSIGN STRING
| ID TYPEASSIGN NUMBER
"""
pass
def p_new_atts(p):
"""
new_atts : new_att
| new_atts SEPARATOR new_att
"""
pass
def p_expr(p):
"""
expr : term
| expr PLUS term
| expr MINUS term
"""
pass
def p_term(p):
"""
term : factor
| term STAR factor
| term SLASH factor
| term PCT factor
"""
pass
def p_factor(p):
"""
factor : ID
| NUMBER
| LPAREN expr RPAREN
| factor LPAREN argsopt RPAREN
"""
pass
def p_test(p):
"""
test : expr NE expr
| expr LT expr
| expr LE expr
| expr GE expr
| expr GT expr
"""
pass
def p_argsopt(p):
"""
argsopt : args
|
"""
pass
def p_args(p):
"""
args : expr SEPARATOR args
| expr
"""
pass
def p_error(p):
print("Syntax error at token", p, "line:", p.lexer.lineno)
textfile = open("TestFile.txt","r")
data = textfile.read()
parser = yacc.yacc()
lexer = lex.lex()
lexer.input(data)
while True:
try:
s = input(data)
except EOFError:
break
if not s: continue
result = parser.parse(s)
print(result)

More Related Content

Similar to You have already implemented a lexical analyzer in Assignment #1 and.pdf

Eight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programsEight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programs
Aleksandr Yampolskiy
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
gkgaur1987
 
Cypherock Assessment (1).pdf
Cypherock Assessment (1).pdfCypherock Assessment (1).pdf
Cypherock Assessment (1).pdf
PARNIKA GUPTA
 

Similar to You have already implemented a lexical analyzer in Assignment #1 and.pdf (20)

C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
It’s sometimes useful to make a little language for a simple problem.pdf
It’s sometimes useful to make a little language for a simple problem.pdfIt’s sometimes useful to make a little language for a simple problem.pdf
It’s sometimes useful to make a little language for a simple problem.pdf
 
Useful c programs
Useful c programsUseful c programs
Useful c programs
 
Generating parsers using Ragel and Lemon
Generating parsers using Ragel and LemonGenerating parsers using Ragel and Lemon
Generating parsers using Ragel and Lemon
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB
 
lab-assgn-practical-file-xii-cs.pdf
lab-assgn-practical-file-xii-cs.pdflab-assgn-practical-file-xii-cs.pdf
lab-assgn-practical-file-xii-cs.pdf
 
MLflow with R
MLflow with RMLflow with R
MLflow with R
 
Eight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programsEight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programs
 
Shad_Cryptography_PracticalFile_IT_4th_Year (1).docx
Shad_Cryptography_PracticalFile_IT_4th_Year (1).docxShad_Cryptography_PracticalFile_IT_4th_Year (1).docx
Shad_Cryptography_PracticalFile_IT_4th_Year (1).docx
 
Embedded systemsproject_2020
Embedded systemsproject_2020Embedded systemsproject_2020
Embedded systemsproject_2020
 
python and perl
python and perlpython and perl
python and perl
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
 
Introducing Blockchain with Java Program, Imple.pdf
Introducing Blockchain with Java Program, Imple.pdfIntroducing Blockchain with Java Program, Imple.pdf
Introducing Blockchain with Java Program, Imple.pdf
 
Introduction to Basics of Python
Introduction to Basics of PythonIntroduction to Basics of Python
Introduction to Basics of Python
 
Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019
 
Cypherock Assessment (1).pdf
Cypherock Assessment (1).pdfCypherock Assessment (1).pdf
Cypherock Assessment (1).pdf
 
Rails and security
Rails and securityRails and security
Rails and security
 

More from albert20021

Write this in C language. This project will require students to si.pdf
Write this in C language. This project will require students to si.pdfWrite this in C language. This project will require students to si.pdf
Write this in C language. This project will require students to si.pdf
albert20021
 
Write in Python please Web Server Python Assignment You will dev.pdf
Write in Python please Web Server Python Assignment You will dev.pdfWrite in Python please Web Server Python Assignment You will dev.pdf
Write in Python please Web Server Python Assignment You will dev.pdf
albert20021
 

More from albert20021 (20)

You observe that company A has just paid its most recent dividend D0.pdf
You observe that company A has just paid its most recent dividend D0.pdfYou observe that company A has just paid its most recent dividend D0.pdf
You observe that company A has just paid its most recent dividend D0.pdf
 
You notice that, in western society, there is an association of hype.pdf
You notice that, in western society, there is an association of hype.pdfYou notice that, in western society, there is an association of hype.pdf
You notice that, in western society, there is an association of hype.pdf
 
You have been hired as a social media consultant to develop social m.pdf
You have been hired as a social media consultant to develop social m.pdfYou have been hired as a social media consultant to develop social m.pdf
You have been hired as a social media consultant to develop social m.pdf
 
You have been hired to design a database for the University of Mpuma.pdf
You have been hired to design a database for the University of Mpuma.pdfYou have been hired to design a database for the University of Mpuma.pdf
You have been hired to design a database for the University of Mpuma.pdf
 
You are given n observations X1, X2, . . . , Xn that are i.i.d. and .pdf
You are given n observations X1, X2, . . . , Xn that are i.i.d. and .pdfYou are given n observations X1, X2, . . . , Xn that are i.i.d. and .pdf
You are given n observations X1, X2, . . . , Xn that are i.i.d. and .pdf
 
You decide to put your plan into Microsoft Project for easier manage.pdf
You decide to put your plan into Microsoft Project for easier manage.pdfYou decide to put your plan into Microsoft Project for easier manage.pdf
You decide to put your plan into Microsoft Project for easier manage.pdf
 
you cross two individuals that are heterozygous at the R locus. if t.pdf
you cross two individuals that are heterozygous at the R locus. if t.pdfyou cross two individuals that are heterozygous at the R locus. if t.pdf
you cross two individuals that are heterozygous at the R locus. if t.pdf
 
You are member of Chens care team. You do not speak Chinese. You fi.pdf
You are member of Chens care team. You do not speak Chinese. You fi.pdfYou are member of Chens care team. You do not speak Chinese. You fi.pdf
You are member of Chens care team. You do not speak Chinese. You fi.pdf
 
You are given a phage lysate and a culture of bacterial cells. You a.pdf
You are given a phage lysate and a culture of bacterial cells. You a.pdfYou are given a phage lysate and a culture of bacterial cells. You a.pdf
You are given a phage lysate and a culture of bacterial cells. You a.pdf
 
You are assessing a patient for syphilis. 1. What are some of the .pdf
You are assessing a patient for syphilis. 1. What are some of the .pdfYou are assessing a patient for syphilis. 1. What are some of the .pdf
You are assessing a patient for syphilis. 1. What are some of the .pdf
 
You are a computer user. In your academic work, your engagement wit.pdf
You are a computer user.  In your academic work, your engagement wit.pdfYou are a computer user.  In your academic work, your engagement wit.pdf
You are a computer user. In your academic work, your engagement wit.pdf
 
Write this in C language. This project will require students to si.pdf
Write this in C language. This project will require students to si.pdfWrite this in C language. This project will require students to si.pdf
Write this in C language. This project will require students to si.pdf
 
Write one program with a menu allowing a user to select either an In.pdf
Write one program with a menu allowing a user to select either an In.pdfWrite one program with a menu allowing a user to select either an In.pdf
Write one program with a menu allowing a user to select either an In.pdf
 
Write a statement that calls the function OutputAge. in coral code.pdf
Write a statement that calls the function OutputAge. in coral code.pdfWrite a statement that calls the function OutputAge. in coral code.pdf
Write a statement that calls the function OutputAge. in coral code.pdf
 
Written Assignments 1. Complete a comparative report on concrete ver.pdf
Written Assignments 1. Complete a comparative report on concrete ver.pdfWritten Assignments 1. Complete a comparative report on concrete ver.pdf
Written Assignments 1. Complete a comparative report on concrete ver.pdf
 
Write a MARIE program to allow the user to input 10 integers (positi.pdf
Write a MARIE program to allow the user to input 10 integers (positi.pdfWrite a MARIE program to allow the user to input 10 integers (positi.pdf
Write a MARIE program to allow the user to input 10 integers (positi.pdf
 
Write SQL statements to answer the following queriesQ1 List of n.pdf
Write SQL statements to answer the following queriesQ1 List of n.pdfWrite SQL statements to answer the following queriesQ1 List of n.pdf
Write SQL statements to answer the following queriesQ1 List of n.pdf
 
Write on the research statistics, surveillance baseline - identify a.pdf
Write on the research statistics, surveillance baseline - identify a.pdfWrite on the research statistics, surveillance baseline - identify a.pdf
Write on the research statistics, surveillance baseline - identify a.pdf
 
Write a Recipe website Project Proposal (HTML,CSS)The Project Prop.pdf
Write a Recipe website Project Proposal (HTML,CSS)The Project Prop.pdfWrite a Recipe website Project Proposal (HTML,CSS)The Project Prop.pdf
Write a Recipe website Project Proposal (HTML,CSS)The Project Prop.pdf
 
Write in Python please Web Server Python Assignment You will dev.pdf
Write in Python please Web Server Python Assignment You will dev.pdfWrite in Python please Web Server Python Assignment You will dev.pdf
Write in Python please Web Server Python Assignment You will dev.pdf
 

Recently uploaded

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
Orientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdfOrientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdf
Elizabeth Walsh
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 

Recently uploaded (20)

NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptxMichaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Orientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdfOrientation Canvas Course Presentation.pdf
Orientation Canvas Course Presentation.pdf
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 

You have already implemented a lexical analyzer in Assignment #1 and.pdf

  • 1. You have already implemented a lexical analyzer in Assignment #1 and a parser to recognize grammatical rules in Assignment #2. In this assignment, you will be adding semantics to the design of a small programming language to help implement blockchain. The goal of blockchain is to allow digital information to be recorded and distributed, but not edited. In this way, a blockchain is a foundation for immutable records of transactions that cannot be altered, deleted, or destroyed. The semantics that you must implement in this assignment is as follows: 1. Each time a new blockchain is created, you must extract attributes and verifies if each attribute has a valid type. Returns false if at least one is invalid or returns true otherwise. 2. When the add operator (keyword) is used, the data must be stored in a dictionary. 3. When errors are detected, the parser must describe the error, including the line of the code where it occurs. 4. When arithmetic expressions are used, the parser will implement the corresponding arithmetic operations. For simplicity purposes, the blockchain only will store arithmetic expressions and strings. import ply.lex as lex import ply.yacc as yacc tokens = ( 'ID', 'BLOCK', 'VAR', 'ADD', 'PRINT', 'VIEW', 'RUN', 'MINE', 'EXPORT', 'STRING', 'INT', 'LONG', 'FLOAT', 'LIST', 'TUPLE', 'DICT', 'NUMBER',
  • 2. 'ASSIGN', 'TYPEASSIGN', 'SEPARATOR', 'LPAREN', 'RPAREN', 'NE', 'LT', 'GT', 'LE', 'GE', 'PLUS', 'MINUS', 'STAR', 'SLASH', 'PCT', 'COMMENT', 'WHITESPACE' ) t_ASSIGN = r'=' t_TYPEASSIGN = r':' t_SEPARATOR = r',' t_LPAREN = r'(' t_RPAREN = r')' t_NE = r'!=' t_LT = r'<' t_GT = r'>' t_LE = r'<=' t_GE = r'>=' t_PLUS = r'+' t_MINUS = r'-' t_STAR = r'*' t_SLASH = r'/' t_PCT = r'%' t_ignore_COMMENT = r'#.'
  • 3. t_ignore_WHITESPACE = r's+' keywords = { 'BLOCK': 'KEYWORD', 'VAR': 'KEYWORD', 'ADD': 'KEYWORD', 'PRINT': 'KEYWORD', 'VIEW': 'KEYWORD', 'RUN': 'KEYWORD', 'MINE': 'KEYWORD', 'EXPORT': 'KEYWORD', 'STR':'KEYWORD', 'INT': 'KEYWORD', 'LONG': 'KEYWORD', 'FLOAT': 'KEYWORD', 'LIST': 'KEYWORD', 'TUPLE': 'KEYWORD', 'DICT':'KEYWORD', } tokens1 = ['ID', 'BLOCK','VAR','ADD','PRINT','VIEW','RUN','MINE','EXPORT','STRING','LONG','FLOAT','L IST','TUPLE','DICT','NUMBER','ASSIGN','TYPEASSIGN','SEPARATOR','LPAREN','RPARE N','NE','LT','GT','LE','GE','PLUS','MINUS','STAR','SLASH', 'PCT', 'COMMENT','WHITESPACE'] + list(keywords.values()) # dictionary to store values values = {} def t_KEYWORD(t): r'DEF | VAR | INT | IF | ELSE' t.type = keywords.get(t.value, 'KEYWORD') return t
  • 4. def t_ID(t): r'[a-zA-Z_][a-zA-Z_0-9]*' t.type = keywords.get(t.value, 'ID') return t def t_NUM(t): r'[0-9]+' t.type = keywords.get(t.value, 'INT') return t def t_COMMENT(t): r'//.' t.type = keywords.get(t.value, 'COMMENT') pass def t_newline(t): r'n+' t.lexer.lineno += len(t.value) def t_error(t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1) def p_block(p): """ block : BLOCK ID ASSIGN LPAREN attributes RPAREN | ADD ID ASSIGN LPAREN new_atts RPAREN | PRINT ID | RUN ID | MINE ID | EXPORT ID | VIEW ID """ pass
  • 5. def p_type(p): """ type : STRING | INT | LONG | FLOAT | LIST | TUPLE | DICT """ pass def p_attribute(p): """ attribute : ID TYPEASSIGN type """ pass def p_attributes(p): """ attributes : attribute | attributes SEPARATOR attribute """ pass def p_new_att(p): """ new_att : ID TYPEASSIGN STRING | ID TYPEASSIGN NUMBER """ pass
  • 6. def p_new_atts(p): """ new_atts : new_att | new_atts SEPARATOR new_att """ pass def p_expr(p): """ expr : term | expr PLUS term | expr MINUS term """ pass def p_term(p): """ term : factor | term STAR factor | term SLASH factor | term PCT factor """ pass def p_factor(p): """ factor : ID | NUMBER | LPAREN expr RPAREN | factor LPAREN argsopt RPAREN """ pass
  • 7. def p_test(p): """ test : expr NE expr | expr LT expr | expr LE expr | expr GE expr | expr GT expr """ pass def p_argsopt(p): """ argsopt : args | """ pass def p_args(p): """ args : expr SEPARATOR args | expr """ pass def p_error(p): print("Syntax error at token", p, "line:", p.lexer.lineno) textfile = open("TestFile.txt","r") data = textfile.read() parser = yacc.yacc()
  • 8. lexer = lex.lex() lexer.input(data) while True: try: s = input(data) except EOFError: break if not s: continue result = parser.parse(s) print(result)