-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.go
64 lines (49 loc) · 1.25 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
package parser
import (
"errors"
"github.com/alecthomas/participle/v2"
"github.com/alecthomas/participle/v2/lexer"
"github.com/klvnptr/k/utils"
)
func BuildParser[T any]() *participle.Parser[T] {
return participle.MustBuild[T](
participle.Lexer(BuildLexer()),
participle.UseLookahead(1024*4),
participle.Elide("Whitespace"),
participle.Elide("MultiLineComment"),
participle.Elide("Comment"),
)
}
type Parser struct {
// contains filtered or unexported fields
}
func NewParser() *Parser {
return &Parser{}
}
func (p *Parser) Parser(lexer *lexer.StatefulDefinition) *participle.Parser[Module] {
return BuildParser[Module]()
}
func (p *Parser) ParseString(s string) (*Module, error) {
return p.ParseFile(&utils.File{
// TODO: fix hardcoded name
Name: "main.c",
Contents: s,
})
}
func (p *Parser) ParseFile(file *utils.File) (*Module, error) {
l := BuildLexer()
parser := p.Parser(l)
program, err := parser.ParseString(file.Name, file.Contents)
if err != nil {
var parseError participle.Error
if errors.As(err, &parseError) {
return nil, utils.WithPos(err, file, parseError.Position())
}
return nil, err
}
return program, nil
}
func (p *Parser) String() string {
parser := p.Parser(BuildLexer())
return parser.String()
}