-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.y
95 lines (75 loc) · 2.04 KB
/
parser.y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
%{
#include "abstract_syntax_tree.c"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void yyerror(char* s); // error handling function
int yylex(); // declare the function performing lexical analysis
extern int yylineno; // track the line number
%}
%union // union to allow nodes to store return different datatypes
{
char* text;
expression_node* exp_node;
}
%token <text> T_ID T_NUM
%type <exp_node> E T F
/* specify start symbol */
%start START
%%
START : ASSGN {
printf("Valid syntax\n");
YYACCEPT; // If program fits the grammar, syntax is valid
}
/* Grammar for assignment */
ASSGN : T_ID '=' E {
// displaying the expression tree
display_exp_tree($3);
}
;
/* Expression Grammar */
E : E '+' T {
// create a new node of the AST and set left and right children appropriately
$$ = init_exp_node(strdup("+"),$1,$3);
}
| E '-' T {
// create a new node of the AST and set left and right children appropriately
$$ = init_exp_node(strdup("-"),$1,$3);
}
| T { $$ = $1; }
;
T : T '*' F {
// create a new node of the AST and set left and right children appropriately
$$ = init_exp_node(strdup("*"),$1,$3);
}
| T '/' F {
// create a new node of the AST and set left and right children appropriately
$$ = init_exp_node(strdup("/"),$1,$3);
}
| F {
//pass AST node to the parent
$$ = $1;
}
;
F : '(' E ')' { $$ = $2; }
| T_ID {
// creating a terminal node of the AST
$$ = init_exp_node(strdup($1),NULL,NULL);
}
| T_NUM {
// creating a terminal node of the AST
$$ = init_exp_node(strdup($1),NULL,NULL);
}
;
%%
/* error handling function */
void yyerror(char* s)
{
printf("Error :%s at %d \n",s,yylineno);
}
/* main function - calls the yyparse() function which will in turn drive yylex() as well */
int main(int argc, char* argv[])
{
yyparse();
return 0;
}