-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
75 lines (62 loc) · 1.78 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
package diceprob
import (
"github.com/alecthomas/participle/v2"
"github.com/alecthomas/participle/v2/lexer"
)
// Dice expression lexer.
var diceLexer = lexer.MustSimple([]lexer.SimpleRule{
{Name: "DiceRoll", Pattern: `(\d+|[mM][iI])[dD](\d+|[fF])`},
{Name: "Modifier", Pattern: `\d+`},
{Name: "+", Pattern: `\+`},
{Name: "-", Pattern: `-`},
{Name: "*", Pattern: `\*`},
{Name: "/", Pattern: `/`},
{Name: "(", Pattern: `\(`},
{Name: ")", Pattern: `\)`},
})
// Parser for our dice expressions.
var diceParser = participle.MustBuild[Expression](participle.Lexer(diceLexer), participle.UseLookahead(2))
// Operator type
type Operator int
// Operator constants
const (
OpMul Operator = iota
OpDiv
OpAdd
OpSub
)
// operatorMap - Map parsed operators to constants.
var operatorMap = map[string]Operator{"+": OpAdd, "-": OpSub, "*": OpMul, "/": OpDiv}
// Capture - Capture the costants while parsing.
func (o *Operator) Capture(s []string) error {
*o = operatorMap[s[0]]
return nil
}
// DiceRoll - String representing a dice roll atomic expression.
type DiceRoll string
// Expression - Top level parsing unit.
type Expression struct {
Left *Term `parser:"@@"`
Right []*OpTerm `parser:"@@*"`
}
// OpTerm - Expression Operator and Term.
type OpTerm struct {
Operator Operator `parser:"@('+' | '-')"`
Term *Term `parser:"@@"`
}
// Term - Expression Term
type Term struct {
Left *Atom `parser:"@@"`
Right []*OpAtom `parser:"@@*"`
}
// OpAtom - Expression Operator and Atom.
type OpAtom struct {
Operator Operator `parser:"@('*' | '/')"`
Atom *Atom `parser:"@@"`
}
// Atom - Smallest unit of an expression.
type Atom struct {
Modifier *int64 `parser:"@Modifier"`
RollExpr *DiceRoll `parser:"| @DiceRoll"`
SubExpression *Expression `parser:"| '(' @@ ')'"`
}