Website Summary Files Commits Branches @commit @diff @stats
path: root / demo / bison / associativity / parser.y
blob: 3852e39728d0cf6a671163f93cb88e63113bcbc5 (plain) (blame)
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
%{
#include <stdio.h>
int yylex();
int yyerror(const char* error);
#define YYDEBUG 0
#include <iostream>
#include <string>
using namespace std::string_literals;
%}

%start input
%define api.value.type {std::string}

%token NUMBER
%token IDENT
%token PLUS
%token MINUS
%token MULT
%token DIV
%token ASSIGN

/* Define both - precedence and associativity */
%right ASSIGN
%left PLUS MINUS
%left MULT DIV

%%

input:  /* empty */
        | expr  { std::cout << $1 << std::endl; }
        ;

expr:   NUMBER  { $$ = $1; }
        | IDENT { $$ = $1; }
        | '(' expr ')' { $$ = "( "s + $2 + " )"; }
        | expr PLUS  expr { $$ = "{ "s + $1 + " + " + $3 + " }"; }
        | expr MINUS expr { $$ = "{ "s + $1 + " - " + $3 + " }"; }
        | expr MULT  expr { $$ = "{ "s + $1 + " * " + $3 + " }"; }
        | expr DIV   expr { $$ = "{ "s + $1 + " / " + $3 + " }"; }
        | expr ASSIGN expr { $$ = "{ "s + $1 + " = " + $3 + " }"; }

%%

int yyerror(const char* error)
{
    extern int current_line;
    fprintf(stderr, "input:%d: error: %s\n", current_line, error);
    return 0;
}

int main()
{
#if YYDEBUG
    yydebug = 1;
#endif

    yyparse();
    return 0;
}