nurse/grammar/parser.go

50 lines
1.5 KiB
Go
Raw Permalink Normal View History

2022-04-28 16:35:02 +00:00
package grammar
import (
"github.com/alecthomas/participle/v2"
"github.com/alecthomas/participle/v2/lexer"
)
func NewParser[T any]() (*Parser[T], error) {
def, err := lexer.NewSimple([]lexer.SimpleRule{
{Name: "Comment", Pattern: `(?:#|//)[^\n]*\n?`},
{Name: `Module`, Pattern: `[a-z]{1}[A-z0-9]+`},
{Name: `Ident`, Pattern: `[A-Z][a-zA-Z0-9_]*`},
{Name: `CIDR`, Pattern: `(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/(3[0-2]|[1-2][0-9]|[1-9])`},
{Name: `IP`, Pattern: `(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}`},
{Name: `Float`, Pattern: `\d+\.\d+`},
{Name: `Int`, Pattern: `[-]?\d+`},
{Name: `RawString`, Pattern: "`[^`]*`"},
{Name: `String`, Pattern: `'[^']*'|"[^"]*"`},
{Name: `Arrows`, Pattern: `(->|=>)`},
{Name: "whitespace", Pattern: `\s+`},
{Name: "Punct", Pattern: `[-[!@#$%^&*()+_={}\|:;\."'<,>?/]|]`},
})
if err != nil {
return nil, err
}
2022-08-18 17:25:07 +00:00
grammarParser, err := participle.Build[T](
2022-04-28 16:35:02 +00:00
participle.Lexer(def),
participle.Unquote("String", "RawString"),
participle.Elide("Comment"),
)
if err != nil {
return nil, err
}
return &Parser[T]{grammarParser: grammarParser}, nil
}
type Parser[T any] struct {
2022-08-18 17:25:07 +00:00
grammarParser *participle.Parser[T]
2022-04-28 16:35:02 +00:00
}
func (p Parser[T]) Parse(rawRule string) (*T, error) {
2022-08-18 17:25:07 +00:00
return p.grammarParser.ParseString("", rawRule)
2022-04-28 16:35:02 +00:00
}
2022-05-13 13:38:19 +00:00
func (p Parser[T]) ParseBytes(data []byte) (*T, error) {
2022-08-18 17:25:07 +00:00
return p.grammarParser.ParseBytes("", data)
2022-05-13 13:38:19 +00:00
}