/
reader.go
75 lines (68 loc) · 1.42 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
// Copyright 2015 Ian Dawes. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"container/list"
"os"
"strings"
)
type reader struct {
filename string
f *os.File
r *bufio.Reader
line int
unreadLines *list.List
err error
}
func newReader(filename string) *reader {
f, err := os.Open(filename)
if err != nil {
return &reader{err: err}
}
return &reader{filename: filename, f: f, r: bufio.NewReader(f), unreadLines: list.New()}
}
func (r *reader) close() {
r.f.Close() // ok to ignore errors here, because f is read-only and this is an ephemeral executable
}
func (r *reader) read() ([]string, error) {
var (
line string
err error
)
if e := r.unreadLines.Front(); e != nil {
r.unreadLines.Remove(e)
return e.Value.([]string), nil
}
inBlockComment := false
for {
r.line++
line, err = r.r.ReadString('\n')
if err != nil {
return nil, err
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
if strings.HasPrefix(line, "//") {
continue
}
if inBlockComment {
if strings.HasSuffix(line, "*/") {
inBlockComment = false
}
continue
}
if strings.HasPrefix(line, "/*") {
inBlockComment = true
continue
}
break
}
return strings.Fields(line), nil
}
func (r *reader) unread(fields []string) {
r.unreadLines.PushFront(fields)
}