This mini-project was developed as part of a course on Automata, Formal Languages, and Logic.
It uses PLY (Python Lex-Yacc) to perform syntax validation of a simple subset of the C programming language. It supports:
- Constant and variable declarations
- Arithmetic expressions
- Basic syntax error detection
This project demonstrates how context-free grammars can be applied to perform syntax validation on simplified C-like statements using Python's PLY (Lex and Yacc) library. It helps understand the fundamentals of parsing and compiler construction.
- Tokenizes input using a custom lexer
- Parses statements using defined CFG rules
- Supports:
int
andconst int
declarations- Arithmetic operations:
+
,-
,*
,/
- Grouped expressions using
{}
and()
- Syntax error detection and handling
main1.py
- Main interactive promptlexer1.py
- Tokenizer using PLYparser1.py
- Grammar rules and CFG parser using PLY
Make sure you have PLY installed:
pip install ply
Then run the program:
python main1.py
You will get a prompt like this:
>
Now you can input C statements. Example:
const int x = 5;
x + 3 * 2;
It will output:
Declared constant x = 5
Expression evaluated: 11
The input is read line-by-line. If you want to enter code blocks using { ... }, you must enter the entire block on a single line. For example:
{ int x = 3; int b = 10; x + b; }
int a = 5;
a + 4;
const int b = 10;
{ int x = 3; x + b; }
> int a = 5;
Declared a = 5
> const int b = 10;
Declared constant b = 10
> a + b;
Expression evaluated: 15
> y = 2;
y = 2
> b + ;
Syntax error at ';'
Shree Raksha (she/her)
B.Tech in Computer Science, PES University
GitHub: @shreeraksha-cs