-
Notifications
You must be signed in to change notification settings - Fork 137
/
parser.go
105 lines (87 loc) · 2.58 KB
/
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
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
package texttemplate
import (
"fmt"
"github.com/k14s/ytt/pkg/filepos"
)
type Parser struct {
associatedName string
}
func NewParser() *Parser {
return &Parser{}
}
func (p *Parser) Parse(dataBs []byte, associatedName string) (*NodeRoot, error) {
return p.parse(dataBs, associatedName, filepos.NewPosition(1))
}
func (p *Parser) ParseWithPosition(dataBs []byte, associatedName string, startPos *filepos.Position) (*NodeRoot, error) {
return p.parse(dataBs, associatedName, startPos)
}
func (p *Parser) parse(dataBs []byte, associatedName string, startPos *filepos.Position) (*NodeRoot, error) {
p.associatedName = associatedName
var lastChar rune
var currLine int = 1
var currCol int = 1
if startPos.IsKnown() {
currLine = startPos.Line()
}
var lastNode interface{} = &NodeText{Position: p.newPosition(currLine)}
var nodes []interface{}
data := string(dataBs)
for i, currChar := range data {
if lastChar == '(' && currChar == '@' {
switch typedLastNode := lastNode.(type) {
case *NodeText:
typedLastNode.Content = data[typedLastNode.startOffset : i-1]
nodes = append(nodes, lastNode)
lastNode = &NodeCode{
Position: p.newPosition(currLine),
startOffset: i + 1,
}
case *NodeCode:
return nil, fmt.Errorf(
"Unexpected code opening '(@' at line %d col %d", currLine, currCol)
default:
panic(fmt.Sprintf("unknown string template piece %T", typedLastNode))
}
}
if lastChar == '@' && currChar == ')' {
switch typedLastNode := lastNode.(type) {
case *NodeText:
return nil, fmt.Errorf(
"Unexpected code closing '@)' at line %d col %d", currLine, currCol)
case *NodeCode:
typedLastNode.Content = data[typedLastNode.startOffset : i-1]
nodes = append(nodes, lastNode)
lastNode = &NodeText{
Position: p.newPosition(currLine),
startOffset: i + 1,
}
default:
panic(fmt.Sprintf("unknown string template piece %T", typedLastNode))
}
}
if currChar == '\n' {
currLine += 1
currCol = 1
} else {
currCol += 1
}
lastChar = currChar
}
// close last node
switch typedLastNode := lastNode.(type) {
case *NodeText:
typedLastNode.Content = data[typedLastNode.startOffset:len(data)]
nodes = append(nodes, lastNode)
case *NodeCode:
return nil, fmt.Errorf(
"Missing code closing '@)' at line %d col %d", currLine, currCol)
default:
panic(fmt.Sprintf("unknown string template piece %T", typedLastNode))
}
return &NodeRoot{Items: nodes}, nil
}
func (p *Parser) newPosition(line int) *filepos.Position {
pos := filepos.NewPosition(line)
pos.SetFile(p.associatedName)
return pos
}