-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
52 lines (45 loc) · 972 Bytes
/
parser.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
package main
import (
"bufio"
"bytes"
"fmt"
"io"
)
// https://go.dev/ref/spec
type SourceFile struct {
PackageClause []byte
ImportDecl [][]byte
TopLevelDecl []byte
}
func ParseSourceFile(r io.Reader) (*SourceFile, error) {
section := 0
s := &SourceFile{}
rd := bufio.NewReader(r)
for {
line, err := rd.ReadBytes('\n')
if err != nil {
if err == io.EOF {
return s, nil
}
return nil, fmt.Errorf("read: %s", err)
}
switch section {
case 0: // before import section
s.PackageClause = append(s.PackageClause, line...)
if bytes.Equal(line, []byte("import (\n")) {
// start import block
section = 1
}
case 1: // import section
if bytes.Equal(line, []byte(")\n")) {
// end import block
section = 2
s.TopLevelDecl = append(s.TopLevelDecl, line...)
break
}
s.ImportDecl = append(s.ImportDecl, line)
case 2: // after import section
s.TopLevelDecl = append(s.TopLevelDecl, line...)
}
}
}