aboutsummaryrefslogtreecommitdiff
path: root/11/main.y
blob: 256195125ef412b9a4baa4a0af633e17debd3461 (plain)
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
%{
#include <stdio.h>
#include <stdlib.h>
int yylex();
int yyerror(char *);
int loop_count = 0;
%}

%token ADD SUB MUL DIV INC DEC
%token LT GT LTE GTE EQ NEQ ASSIGN
%token FOR
%token ENDL
%token NUM ID

%start statement

%%
primary_expr: NUM
            | ID
            ;

postfix_expr: postfix_expr INC
            | postfix_expr DEC
            | primary_expr
            ;

unary_expr: INC unary_expr
          | DEC unary_expr
          | postfix_expr
          ;

boolean_expr: unary_expr LT unary_expr
            | unary_expr GT unary_expr
            | unary_expr LTE unary_expr
            | unary_expr GTE unary_expr
            | unary_expr EQ unary_expr
            | unary_expr NEQ unary_expr
            ;

assignment_expr: unary_expr ASSIGN unary_expr
               | unary_expr ASSIGN boolean_expr
               ;

expression: unary_expr
          | boolean_expr
          | assignment_expr
          ;

block: '{' statement block_cont
     ;
block_cont: statement block_cont
          | '}'
          ;

statement: expression ENDL
         | block
         | for_expr {loop_count++;}
         | ENDL
         ;

for_expr: FOR '(' statement statement expression ')' statement
        | FOR '(' statement statement ')' statement
        ;

%%

int main() {
    yyparse();
    printf("valid expression, nested %d", loop_count);
}

int yyerror(char *s) {
    printf("error: %s", s);
    exit(0);
}