-
Notifications
You must be signed in to change notification settings - Fork 67
/
reader.go
86 lines (80 loc) · 1.38 KB
/
reader.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
package core
import (
"io"
)
type (
Reader struct {
runeReader io.RuneReader
rw *RuneWindow
line int
prevLineLength int
column int
isEof bool
rewind int
filename *string
}
)
func NewReader(runeReader io.RuneReader, filename string) *Reader {
return &Reader{
line: 1,
runeReader: runeReader,
rw: &RuneWindow{},
rewind: -1,
filename: STRINGS.Intern(filename),
}
}
func (reader *Reader) Get() rune {
if reader.isEof {
return EOF
}
if reader.rewind > -1 {
r := top(reader.rw, reader.rewind)
reader.rewind--
if r == '\n' {
reader.line++
reader.prevLineLength = reader.column
reader.column = 0
} else {
reader.column++
}
return r
}
r, _, err := reader.runeReader.ReadRune()
switch {
case err == io.EOF:
reader.isEof = true
return EOF
case err != nil:
panic(err)
case r == '\n':
reader.line++
reader.prevLineLength = reader.column
reader.column = 0
add(reader.rw, r)
return r
default:
reader.column++
add(reader.rw, r)
return r
}
}
func (reader *Reader) Unget() {
if reader.isEof {
return
}
reader.rewind++
if reader.column == 0 {
reader.line--
reader.column = reader.prevLineLength
} else {
reader.column--
}
}
func (reader *Reader) Peek() rune {
if reader.isEof {
return EOF
}
r := reader.Get()
reader.Unget()
return r
}