summaryrefslogtreecommitdiff
path: root/test/t.y
blob: 40b7f495655b026d2cbad4c85f608b741b64eb5c (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
76
77
78
79
80
81
82
83
84
85
%{
	#include <ctype.h>
	#include <stdio.h>
	#include <stdlib.h>
	#include <string.h>

	int yylex(void);
%}

%union {
	int sum;
	int mul;
	int num;
}

%type <sum> A
%token <num> NUM

%left '+' '-'
%nonassoc '*'
%nonassoc UMIN

%%

S:
 | S A { printf("-> %d\n", $2); }
 ;

A: NUM              { $$ = $1; }
 | A '+' A          { $$ = $1 + $3; }
 | A '-' A          { $$ = $1 - $3; }
 | A '*' A          { $$ = $1 * $3; }
 | '-' A %prec UMIN { $$ = -$2; }
 | '(' A ')'        { $$ = $2; }
 ;

%%

enum {
	MaxLine = 1000,
};

char line[MaxLine], *p;

int
yyerror()
{
	puts("oops");
}

int
yylex()
{
	char c;

	p += strspn(p, "\t ");
	switch ((c=*p++)) {
	case '+':
	case '-':
	case '*':
	case '(':
	case ')':
		return c;
	case 0:
	case '\n':
		p--;
		return 0;
	}
	if (isdigit(c)) {
		yylval.num = strtol(p-1, &p, 0);
		return NUM;
	}
	puts("lex error!");
	return 0;
}

int
main()
{
	while ((p=fgets(line, MaxLine, stdin))) {
		if (yyparse() < 0)
			puts("parse error!");
	}
	return 0;
}