/
lexem.go
59 lines (47 loc) · 967 Bytes
/
lexem.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
package assembler
import (
"fmt"
"regexp"
)
type Lexem interface {
Category() Category
Matches(string) bool
}
func NewLexemLiteral(c Category, v string) Lexem {
return &lexemLiteral{
category: c,
value: v,
}
}
type lexemLiteral struct {
category Category
value string
}
func (l *lexemLiteral) Category() Category {
return l.category
}
func (l *lexemLiteral) Matches(s string) bool {
return l.value == s
}
func (l *lexemLiteral) String() string {
return fmt.Sprintf("%d : %s", l.category, l.value)
}
func NewLexemRegexp(c Category, r string) Lexem {
return &lexemRegex{
category: c,
regexp: regexp.MustCompile(r),
}
}
type lexemRegex struct {
category Category
regexp *regexp.Regexp
}
func (l *lexemRegex) Category() Category {
return l.category
}
func (l *lexemRegex) Matches(s string) bool {
return l.regexp.MatchString(s)
}
func (l *lexemRegex) String() string {
return fmt.Sprintf("%d : %s", l.category, l.regexp)
}