-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple.y
121 lines (103 loc) · 1.57 KB
/
simple.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
109
110
111
112
113
114
115
116
117
118
119
120
121
// playing with goyacc
// http://acm.tju.edu.cn/toj/showp3638.html
%{
package main
import (
"fmt"
"os"
"unicode"
)
%}
%union {
s string;
val bool;
}
%token WRITE IF ELSE
%token<s> LITERAL
%token<val> COND
%type <s> stmt
%%
list:
| list stmt { if ($2 != "") {fmt.Println($2)}}
;
stmt: WRITE '(' LITERAL ')' { $$ = $3 }
| IF '(' COND ')' stmt { if ($3) {$$=$5} else {$$=""} }
| IF '(' COND ')' stmt ELSE stmt { if ($3) {$$=$5} else {$$=$7}}
;
%%
func lookup(s string) int {
if (s == "if") {
return IF
}
if (s == "else") {
return ELSE
}
if (s == "write") {
return WRITE
}
return LITERAL
}
var peek = false
var pchar int
const buflen = 1024
var where = buflen
var buf []byte
func next() int {
if peek {
peek = false
return pchar
}
if where < buflen {
c := buf[where]
where++
return int(c)
}
n, err := os.Stdin.Read(buf)
if n == 0 && err == os.EOF {
return 0
}
where = 1
return int(buf[0])
}
func unget(c int) {
peek = true
pchar = c
}
func getword() string {
c := next()
s := ""
for (unicode.IsLower(c)) {
s += string(c)
c = next()
}
unget(c)
return s
}
type dummy int
func (_ dummy) Lex(yylval *yySymType) int {
c := next()
for (unicode.IsSpace(c)) {
c = next()
}
if (unicode.IsLower(c)) {
unget(c)
return lookup(getword())
}
if (c == '"') {
yylval.s = getword()
next() // '"'
return LITERAL
}
if (c == '1' || c == '0') {
yylval.val = c == '1'
return COND
}
return c
}
func (_ dummy) Error(s string) {
fmt.Println("got error", s)
}
func main() {
buf = make([]byte, buflen)
yyParse(dummy(0));
}