-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregexl.go
executable file
·97 lines (74 loc) · 1.58 KB
/
regexl.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package regexl
import (
"encoding/json"
"fmt"
"regexp"
)
// @TODO: remove or make something nicer
// Debug options
var (
PrintTokens bool
PrintAstJson bool
PrintAstTree bool
)
type Regexl struct {
Query string
CompiledRegexp *regexp.Regexp
}
func NewRegexl(query string) *Regexl {
rl := &Regexl{
Query: query,
}
return rl
}
// Compile tries to compile the query within this Regexl object and then sets Regexl.CompiledRegexp.
// Regexl.CompiledRegexp is only set if no error is found, otherwise the error is returned and Regexl.CompiledRegexp is unchanged.
func (rl *Regexl) Compile() error {
parser := NewParser(rl.Query)
// Tokenize
tokens, err := parser.Tokenize()
if err != nil {
return err
}
if PrintTokens {
b, err := json.MarshalIndent(tokens, "", " ")
if err != nil {
return err
}
fmt.Printf("%d Tokens: %s\n", len(tokens), string(b))
}
if len(tokens) == 0 {
return fmt.Errorf("empty query is not allowed")
}
// Gen AST
ast := NewAst(tokens)
err = ast.Gen()
if err != nil {
return err
}
if PrintAstJson {
b, err := json.MarshalIndent(ast.Nodes, "", " ")
if err != nil {
return err
}
fmt.Printf("AST JSON: %s\n", b)
}
if PrintAstTree {
ast.PrintTree()
}
gb := &GoBackend{}
goRegexp, _, err := gb.AstToGoRegex(ast)
if err != nil {
return err
}
rl.CompiledRegexp = goRegexp
return nil
}
// MustCompile compiles the query within this regexl object by calling Regexl.Compile and panics if an error is thrown
func (rl *Regexl) MustCompile() *Regexl {
err := rl.Compile()
if err != nil {
panic(err)
}
return rl
}