forked from AplaProject/go-apla
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lextable.go
279 lines (266 loc) · 8.64 KB
/
lextable.go
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// MIT License
//
// Copyright (c) 2016-2018 GenesisKernel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"strings"
)
// The program creates packages/script/lex_table.go files.
// Action is a map of actions
type Action map[string][]string
// States is a map of states
type States map[string]Action
const (
// AlphaSize is the length of alphabet
AlphaSize = 33
)
/* Здесь мы определяем алфавит, с которым будет работать наш язык и описываем конечный автомат, который
переходит из одного состояния в другое в зависимости от очередного полученного символа.
Данная программа переводит список состояний в числовой массив и сохраняет его как
packages/script/lex_table.go
*/
var (
table [][AlphaSize]uint32
lexem = map[string]uint32{``: 0, `sys`: 1, `oper`: 2, `number`: 3, `ident`: 4, `newline`: 5, `string`: 6,
`comment`: 7}
flags = map[string]uint32{`next`: 1, `push`: 2, `pop`: 4, `skip`: 8}
alphabet = []byte{0x01, 0x0a, ' ', '`', '"', ';', '(', ')', '[', ']', '{', '}', '&',
// default n s q Q
'|', '#', '.', ',', '<', '>', '=', '!', '*', '$', '@',
'+', '-', '/', '\\', '0', '1', 'a', '_', 128}
// r
// В states мы обозначили за d - все символы, которые не указаны в состоянии
// n - 0x0a, s - пробел, q - обратные кавычки `, Q - двойные кавычки, r - символы >= 128
// a - A-Z и a-z, 1 - 1-9
// В качестве ключей выступаю имена состояний, a в объекте-значении перечислены возможные наборы символов
// и затем для каждого такого набора идет новое состояние, куда следует сделать переход, далее имя лексемы,
// если нам нужно вернуться в начальное состояние и третьим параметром идут служебные флаги,
// которые указывают, что делать с текущим символом.
// Например, у нас сотояние main и входящий символ /. push говорит запомнить его в отедльном стеке и
// next - перейти к следующему символу, при этом мы меняе состояние на solidus.
// Берем следующий символ и смотрим на состоние solidus
// Если у нас / или * - то мы переходим в состояние комментарий, так они начинаются с // или /*.
// При этом видно, что для каждого комментария разные последующие состояния, так как заканчиваются
// они разными символами. А если у нас следующий символ не / и не *, то мы все что у нас положено
// в стэк (/) записываем как лексему с типом oper, очищаем стэк и возвращаемся в состояние main.
states = `{
"main": {
"n;": ["main", "newline", "next"],
"()#[],{}": ["main", "sys", "next"],
"s": ["main", "", "next"],
"q": ["string", "", "push next"],
"Q": ["dstring", "", "push next"],
"&": ["and", "", "push next"],
"|": ["or", "", "push next"],
"=": ["eq", "", "push next"],
"/": ["solidus", "", "push next"],
"<>!": ["oneq", "", "push next"],
"*+-": ["main", "oper", "next"],
"01": ["number", "", "push next"],
"@$a_r": ["ident", "", "push next"],
".": ["dot", "", "push next"],
"d": ["error", "", ""]
},
"string": {
"q": ["main", "string", "pop next"],
"d": ["string", "", "next"]
},
"dstring": {
"Q": ["main", "string", "pop next"],
"\\": ["dslash", "", "skip"],
"d": ["dstring", "", "next"]
},
"dslash": {
"d": ["dstring", "", "next"]
},
"dot": {
".": ["ddot", "", "next"],
"d": ["main", "sys", "pop"]
},
"ddot": {
".": ["main", "ident", "pop next"],
"d": ["error", "", ""]
},
"and": {
"&": ["main", "oper", "pop next"],
"d": ["error", "", ""]
},
"or": {
"|": ["main", "oper", "pop next"],
"d": ["error", "", ""]
},
"eq": {
"=": ["main", "oper", "pop next"],
"d": ["main", "sys", "pop"]
},
"solidus": {
"/": ["comline", "", "pop next"],
"*": ["comment", "", "next"],
"d": ["main", "oper", "pop"]
},
"oneq": {
"=": ["main", "oper", "pop next"],
"d": ["main", "oper", "pop"]
},
"number": {
"01.": ["number", "", "next"],
"a_r": ["error", "", ""],
"d": ["main", "number", "pop"]
},
"ident": {
"01a_r": ["ident", "", "next"],
"d": ["main", "ident", "pop"]
},
"comment": {
"*": ["comstop", "", "next"],
"d": ["comment", "", "next"]
},
"comstop": {
"/": ["main", "comment", "pop next"],
"d": ["comment", "", "next"]
},
"comline": {
"n": ["main", "", ""],
"d": ["comline", "", "next"]
}
}`
)
func main() {
var alpha [129]byte
for ind, ch := range alphabet {
i := byte(ind)
switch ch {
case ' ':
alpha[0x09] = i
alpha[0x0d] = i
alpha[' '] = i
case '1':
for k := '1'; k <= '9'; k++ {
alpha[k] = i
}
case 'a':
for k := 'A'; k <= 'Z'; k++ {
alpha[k] = i
}
for k := 'a'; k <= 'z'; k++ {
alpha[k] = i
}
case 128:
alpha[128] = i
default:
alpha[ch] = i
}
}
out := `package script
// This file was generated with lextable.go
var (
alphabet = []byte{`
for i, ch := range alpha {
out += fmt.Sprintf(`%d,`, ch)
if i > 0 && i%24 == 0 {
out += "\r\n\t\t\t"
}
}
out += "\r\n\t\t}\r\n"
var (
data States
)
state2int := map[string]uint{`main`: 0}
if err := json.Unmarshal([]byte(states), &data); err == nil {
for key := range data {
if key != `main` {
state2int[key] = uint(len(state2int))
}
}
table = make([][AlphaSize]uint32, len(state2int))
for key, istate := range data {
curstate := state2int[key]
for i := range table[curstate] {
table[curstate][i] = 0xFE0000
}
for skey, sval := range istate {
var val uint32
if sval[0] == `error` {
val = 0xff0000
} else {
val = uint32(state2int[sval[0]] << 16) // new state
}
val |= uint32(lexem[sval[1]] << 8) // lexem
cmds := strings.Split(sval[2], ` `)
var flag uint32
for _, icmd := range cmds {
flag |= flags[icmd]
}
val |= flag
for _, ch := range []byte(skey) {
var ind int
switch ch {
case 'd':
ind = 0
case 'n':
ind = 1
case 's':
ind = 2
case 'q':
ind = 3
case 'Q':
ind = 4
case 'r':
ind = AlphaSize - 1
default:
for k, ach := range alphabet {
if ach == ch {
ind = k
break
}
}
}
table[curstate][ind] = val
if ind == 0 { // default value
for i := range table[curstate] {
if table[curstate][i] == 0xFE0000 {
table[curstate][i] = val
}
}
}
}
}
}
out += "\t\tlexTable = [][" + fmt.Sprint(AlphaSize) + "]uint32{\r\n"
for _, line := range table {
out += "\t\t\t{"
for _, ival := range line {
out += fmt.Sprintf(" 0x%x,", ival)
}
out += "\r\n\t\t\t},\r\n"
}
out += "\t\t\t}\r\n)\r\n"
err = ioutil.WriteFile("../lex_table.go", []byte(out), 0644)
if err != nil {
fmt.Println(err.Error())
}
} else {
fmt.Println(err.Error())
}
}