-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
64 lines (51 loc) · 1.16 KB
/
main.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
package parser
import (
"github.com/alecthomas/participle/v2"
"regexp"
"strings"
)
//goland:noinspection GoUnusedExportedFunction
func ParseFromFile(filePath string) (*Up, error) {
code, err := readFile(filePath)
if err != nil {
return nil, err
}
return Parse(code)
}
func Parse(rawCode string) (*Up, error) {
parser, err := participle.Build(&Up{})
if err != nil {
return nil, err
}
rootNode := &Up{}
err = parser.ParseString("", RemoveComments(rawCode), rootNode)
if err != nil {
return nil, err
}
err = postProcess(rootNode)
if err != nil {
return nil, err
}
return rootNode, nil
}
func RemoveComments(raw string) string {
// block comments
// [\s\S] is like . except it also matches newlines
// replace with nothing to entirely remove
noBlockComments := regexp.MustCompile("~~~[\\s\\S]*~~~").ReplaceAllString(raw, "")
// line comments
lines := strings.Split(noBlockComments, "\n")
sb := strings.Builder{}
for i := range lines {
for i2 := range lines[i] {
if lines[i][i2] == '~' {
break
}
sb.WriteRune(rune(lines[i][i2]))
}
if i+1 < len(lines) { // if not the last item
sb.WriteRune('\n')
}
}
return sb.String()
}