summaryrefslogtreecommitdiff
path: root/s2/rhoc.y
blob: 63f0b9c9d2d69148e2fbb557b22710ab03fa7105 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
%{
double mem[26];
%}
%union {
	double val;
	int idx;
}
%token	<val> NUMBER
%token	<idx> VAR
%type	<val> expr
%right	'='
%left	'+' '-'
%left	'*' '/'
%left	UNMIN
%%
list:	/* ε */
	| list '\n'
	| list expr '\n'	{ print("\t%.8g\n", $2); }
	| list expr ';'		{ print("\t%.8g\n", $2); }
	| list error '\n'	{ yyerrok; }
	;
expr:	  NUMBER
	| VAR			{ $$ = mem[$1]; }
	| VAR '=' expr		{ $$ = mem[$1] = $3; }
	| '-' expr	%prec UNMIN { $$ = -$2; }
	| expr '+' expr		{ $$ = $1 + $3; }
	| expr '-' expr 	{ $$ = $1 - $3; }
	| expr '*' expr 	{ $$ = $1 * $3; }
	| expr '/' expr
	{
		if($3 == 0)
			rterror("division by zero");
		$$ = $1 / $3;
	}
	| expr '%' expr 	{ $$ = fmod($1, $3); }
	| expr '(' expr ')'	{ $$ = $1 * $3; }
	| '(' expr ')'		{ $$ = $2; }
	;
%%
#include <u.h>
#include <libc.h>
#include <ctype.h>
#include <bio.h>

Biobuf *bin;
jmp_buf begin;
int lineno;
int prompt;

int yyparse(void);

void
error(char *msg, int ln)
{
	fprint(2, "%s at line %d\n", msg, ln);
}

void
yyerror(char *msg)
{
	error(msg, lineno);
}

int
yylex(void)
{
	int c;

	if(prompt){
		print("%d: ", lineno);
		prompt--;
	}
	while((c = Bgetc(bin)) == ' ' || c == '\t')
		;
	if(c == '.' || isdigit(c)){
		Bungetc(bin);
		Bgetd(bin, &yylval.val);
		return NUMBER;
	}
	if(islower(c)){
		yylval.idx = c - 'a';
		return VAR;
	}
	if(c == '\n'){
		lineno++;
		prompt++;
	}
	return c;
}

void
rterror(char *msg)
{
	error(msg, lineno-1);
	longjmp(begin, 0);
}

int
catch(void *ureg, char *msg)
{
	if(strncmp(msg, "sys: fp", 7) == 0){
		error("floating point exception", lineno-1);
		notejmp(ureg, begin, 0);
	}
	return 0;
}

void
usage(void)
{
	fprint(2, "usage: %s\n", argv0);
	exits("usage");
}

void
main(int argc, char *argv[])
{
	ARGBEGIN{
	default: usage();
	}ARGEND;

	if(argc > 0)
		usage();
	bin = Bfdopen(0, OREAD);
	if(bin == nil)
		sysfatal("Bfdopen: %r");
	lineno++;
	prompt++;
	setjmp(begin);
	atnotify(catch, 1);
	yyparse();
	Bterm(bin);
	exits(0);
}