-
Notifications
You must be signed in to change notification settings - Fork 10
/
vimlparser.go
95 lines (87 loc) · 2 KB
/
vimlparser.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
package vimlparser
import (
"bufio"
"fmt"
"io"
"github.com/vim-jp/go-vimlparser/ast"
internal "github.com/vim-jp/go-vimlparser/go"
)
// ErrVimlParser represents VimLParser error.
type ErrVimlParser struct {
Filename string
Offset int
Line int
Column int
Msg string
}
func (e *ErrVimlParser) Error() string {
if e.Filename != "" {
return fmt.Sprintf("%v:%d:%d: vimlparser: %v", e.Filename, e.Line, e.Column, e.Msg)
}
return fmt.Sprintf("vimlparser: %v: line %d col %d", e.Msg, e.Line, e.Column)
}
// ParseOption is option for Parse().
type ParseOption struct {
Neovim bool
}
// ParseFile parses Vim script.
// filename can be empty.
func ParseFile(r io.Reader, filename string, opt *ParseOption) (node *ast.File, err error) {
defer func() {
if r := recover(); r != nil {
node = nil
if e, ok := r.(*internal.ParseError); ok {
err = &ErrVimlParser{
Filename: filename,
Offset: e.Offset,
Line: e.Line,
Column: e.Column,
Msg: e.Msg,
}
} else {
err = fmt.Errorf("%v", r)
}
// log.Printf("%s", debug.Stack())
}
}()
lines := readlines(r)
reader := internal.NewStringReader(lines)
neovim := false
if opt != nil {
neovim = opt.Neovim
}
node = internal.NewVimLParser(neovim).Parse(reader, filename).(*ast.File)
return
}
// ParseExpr parses Vim script expression.
func ParseExpr(r io.Reader) (node ast.Expr, err error) {
defer func() {
if r := recover(); r != nil {
node = nil
if e, ok := r.(*internal.ParseError); ok {
err = &ErrVimlParser{
Offset: e.Offset,
Line: e.Line,
Column: e.Column,
Msg: e.Msg,
}
} else {
err = fmt.Errorf("%v", r)
}
// log.Printf("%s", debug.Stack())
}
}()
lines := readlines(r)
reader := internal.NewStringReader(lines)
p := internal.NewExprParser(reader)
node = p.Parse()
return
}
func readlines(r io.Reader) []string {
lines := []string{}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines
}