-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlexer.go
359 lines (309 loc) · 6.5 KB
/
lexer.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package wfobj
import (
"fmt"
"io/ioutil"
"os"
"strings"
"unicode/utf8"
)
type Kind int
const (
VertexDecl = Kind(iota)
NormalDecl
FaceDecl
NumberLit
SlashLit
Eof
AnyKind
)
const (
Number = "0123456789"
Minus = "-"
Dot = "."
SignedNumber = Minus + Number
FloatNumber = SignedNumber + Dot
)
var kindNames = map[Kind]string{
VertexDecl: "VECTOR_DECLARATION",
NormalDecl: "NORMAL_DECLARATION",
FaceDecl: "FACE_DECLARATION",
NumberLit: "NUMBER_LITERAL",
SlashLit: "SLASH_LITERAL",
Eof: "EOF",
}
func (k Kind) String() string {
return kindNames[k]
}
type Token struct {
Val string
Kind Kind
Pos Position
}
func (t *Token) String() string {
return fmt.Sprintf("[%v @ %v]%v", t.Kind, &t.Pos, t.Val)
}
type Position struct {
// line in the stream
Line int
// column of the current line
Col int
}
func (p *Position) String() string {
return fmt.Sprintf("(line: %v, col: %v)", p.Line, p.Col)
}
type Debug interface {
State(p *Parser)
Emit(t *Token)
}
type Parser struct {
Contents string
VList VertexList
Tokens chan *Token
Debug Debug
sz int
C rune
// position in the stream
pos int
// current line position
cPos Position
// old line position
oPos Position
}
// An error that happened during the parse of the file
type ParseError string
// Return the messsage with the current position of the parser
func NewParseError(p *Parser, msg string) ParseError {
return ParseError(fmt.Sprintf("%v %v", msg, p.cPos))
}
// Error interface
func (p ParseError) Error() string {
return string(p)
}
func NewParserFromFile(fileName string) (p *Parser, err error) {
file, err := os.Open(fileName)
if err != nil {
return
}
defer file.Close()
buff, err := ioutil.ReadAll(file)
if err != nil {
return
}
p = NewLiteralParser(string(buff))
return
}
// Parse the contents of the string variable
func NewLiteralParser(literal string) (p *Parser) {
literal = strings.Replace(literal, "\r\n", "\n", -1)
p = &Parser{literal, make(VertexList, 0), make(chan *Token, 0), nil, 0, 0, 0, Position{1, 1}, Position{1, 0}}
return
}
// Start the parser and emit the tokens in the Tokens channel
func (p *Parser) Parse() (err error) {
defer func() {
close(p.Tokens)
if val := recover(); val != nil {
err = NewParseError(p, fmt.Sprintf("%v", val))
}
}()
for p.Next() {
switch p.C {
case 'v':
ok := p.NextIf(" n")
if !ok {
panic("Expecting Vertex Decl or Normal Decl")
}
switch p.C {
case ' ':
p.Emit("", VertexDecl)
case 'n':
p.Emit("", NormalDecl)
}
p.ReadNumberList()
case 'f':
p.Emit("", FaceDecl)
p.ReadFaceParts()
case '#':
// comment
p.DiscardUntil("\n")
case utf8.RuneError:
panic(fmt.Sprintf("Invalid utf-8 code @ %v", p.pos))
}
}
p.Emit("", Eof)
return
}
// Emit a token
func (p *Parser) Emit(val string, kind Kind) {
t := Token{val, kind, p.cPos}
if p.Debug != nil {
p.Debug.Emit(&t)
}
p.Tokens <- &t
}
// Discard all chars from the stream that match at least one of the chars passed
func (p *Parser) Discard(chars string) {
for p.NextIf(chars) {
}
}
// Discard all the runes until the one of the chars is found
func (p *Parser) DiscardUntil(chars string) {
for p.Next() {
if strings.IndexAny(string(p.C), chars) != -1 {
p.PushBack()
return
}
}
}
// Accumulate the runes from the stream while it matches the chars
func (p *Parser) Acc(chars string) string {
acc := ""
for p.NextIf(chars) {
acc += string(p.C)
}
return acc
}
// Read a variable length list o numbers
func (p *Parser) ReadNumberList() {
p.Discard(" ")
for p.NextIf(FloatNumber) {
// push the last digit/signal back in the stream
p.PushBack()
p.ReadNumberLit()
p.Discard(" ")
}
}
// Read the x y z[ w] information for a vector
func (p *Parser) ReadNumberLit() {
val := ""
if p.NextIf("-") {
val += "-"
}
val += p.ReadInt()
if p.NextIf(".") {
val += "."
val += p.ReadInt()
}
p.Emit(val, NumberLit)
}
// Read the Face declaration supporting the format
// f vIndex/textureIndex/normalIndex
func (p *Parser) ReadFaceParts() {
p.Discard(" ")
fn := func() {
p.ReadNumberLit()
if p.NextIf("/") {
p.Emit("", SlashLit)
}
if p.NextIf(FloatNumber) {
p.PushBack()
p.ReadNumberLit()
}
if p.NextIf("/") {
p.Emit("", SlashLit)
}
if p.NextIf(FloatNumber) {
p.PushBack()
p.ReadNumberLit()
}
}
// while inside a face definition
// the first element will always be a number
// in this case
// after detecting the number, the parser must detect
// if the format is vertex or vertex/texture/normal
// this is done by the fn function defined above
//
// when no numbers are detect
// just exit the loop and return for the previous flow
for p.NextIf(FloatNumber) {
p.PushBack()
fn()
p.Discard(" ")
}
}
// Read a integer and panic if none is found
func (p *Parser) ReadInt() string {
num := p.Acc(Number)
if len(num) == 0 {
panic("Expecting one of: 0123456789")
}
return num
}
// Check if there is more runes in the contents
func (p *Parser) HasNext() bool {
return p.pos < len(p.Contents)
}
// Read the rune and move to the next
func (p *Parser) Next() bool {
// EOF
if !p.HasNext() {
return false
}
p.C, p.sz = utf8.DecodeRuneInString(p.Contents[p.pos:])
if p.C == utf8.RuneError {
return false
}
p.pos += p.sz
// if it is a new line
// increment the line number
if p.C == '\n' {
p.oPos = p.cPos
p.cPos = Position{p.oPos.Line + 1, 1}
}
p.cPos.Col += 1
return true
}
// Read the rune only if it's in the chars
func (p *Parser) NextIf(chars string) bool {
ok, _ := p.Peek(chars)
if ok {
ok = p.Next()
}
return ok
}
// Peek the next run without consuming it
func (p *Parser) Peek(chars string) (ok bool, r rune) {
ok = true
r = utf8.RuneError
if !p.HasNext() {
ok = false
return
}
r, _ = utf8.DecodeRuneInString(p.Contents[p.pos:])
if r == utf8.RuneError {
ok = false
return
}
// no need to check nothing more
if len(chars) == 0 {
return
}
if strings.IndexAny(string(r), chars) == -1 {
ok = false
}
return
}
// Push the last run back in the reader
func (p *Parser) PushBack() {
if p.sz == 0 {
panic("Cannot push more than one time")
}
p.pos -= p.sz
p.sz = 0
// if it was a new line
// decrement the line count
if p.C == '\n' {
p.cPos = p.oPos
p.oPos = Position{}
}
p.C = utf8.RuneError
}
// Return a string representation of the current state of the parser
func (p *Parser) String() string {
part := p.Contents[p.pos:]
if len(part) > 10 {
part = part[:10]
}
return fmt.Sprintf("Contents: %q... @ %v", part, p.cPos)
}