-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathternary.y
108 lines (84 loc) · 2.19 KB
/
ternary.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
96
97
98
99
100
101
102
103
104
105
106
107
108
%{
#include <stdio.h>
#include <stdlib.h>
int yylex();
int yyerror();
/*
This yacc program defines Grammar for ternary operator of C language,
to generate the parser for the same.
Parser created by lex is a LALR parser.
* TERNARY OPERATOR
ternary operator takes 3 argumen
1. The first is a comparison argument
2. The second is the result upon a true comparision.
3. the third is the result upon false comparision.
* The program will check the given input is vaild or not based on the grammar rules defined.
INPUT : Nested or not nested expression on ternary operator.
OUTPUT : Displays 'input accepted' for a vaild input.
otherwise, displays 'Expression is not vaild' for invaild input.
Names of symbols in the parser that are tokens:
NUM : for any numeric value
ID : for any variable.
NEWLINE : for newline character.
LE : for less than equal to "<=".
GE : for greater than equal to ">=".
EQ : for equals to "==".
NE : for not equals "!="
OR : for logical OR '||'
AND for logical AND '&&''
GRAMMAR RULES:
smallest string accepted by the language generated by the grammar
is : statement ? statement : statement
Assumption : the parser only accept boolean , logical and comparission statements.
*/
%}
%token NUM ID NEWLINE LE GE EQ NE OR AND T F NOT
%right '?' ':'
%left OR
%left AND
%left EQ NE
%left LE GE '<' '>'
%right NOT
%left '(' ')'
%%
ST :
|ST S NEWLINE {printf("Input accepted.\n");}
;
S :EXP S1
|'(' S ')'
|'(' S ')' S1
;
S1 :'?' S2
;
S2 :EXP S3
|S S3
;
S3 :':' S4
;
S4 :EXP
|S
;
EXP : EXP'<'EXP
| EXP'>'EXP
| EXP LE EXP
| EXP GE EXP
| EXP EQ EXP
| EXP NE EXP
| EXP OR EXP
| EXP AND EXP
| NOT EXP
|ID
|NUM
|'(' EXP ')'
|T
|F
;
%%
int main() {
printf("Enter expression: \n");
yyparse();
return 0;
}
int yyerror(char* s) {
printf("Expression is not valid\n");
}