-
Notifications
You must be signed in to change notification settings - Fork 24
/
regexp.go
71 lines (58 loc) · 1.51 KB
/
regexp.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
package tengo
import (
"regexp"
tengoLib "github.com/d5/tengo/v2"
"github.com/d5/tengo/v2/token"
)
// Regexp struct create regexp in tengo VM
type Regexp struct {
tengoLib.ObjectImpl
Value *regexp.Regexp
}
// String return regexp in string
func (o *Regexp) String() string {
return o.Value.String()
}
// BinaryOp not implemented
func (o *Regexp) BinaryOp(op token.Token, rhs tengoLib.Object) (tengoLib.Object, error) {
return nil, tengoLib.ErrInvalidOperator
}
// IsFalsy return true if regexp is nil
func (o *Regexp) IsFalsy() bool {
return o.Value == nil
}
// Equals return true if regexp string are equal
func (o *Regexp) Equals(x tengoLib.Object) bool {
return o.Value.String() == o.Value.String()
}
func (o *Regexp) Copy() tengoLib.Object {
return &Regexp{
Value: o.Value,
}
}
func (o *Regexp) TypeName() string {
return "Regexp-object"
}
func (o *Regexp) CanCall() bool {
return true
}
// Call can executed regexp on given value and return immutable map with matches
func (o *Regexp) Call(args ...tengoLib.Object) (ret tengoLib.Object, err error) {
if len(args) != 1 {
err = tengoLib.ErrWrongNumArguments
return
}
val := args[0].(*tengoLib.String)
matches := o.Value.FindStringSubmatch(val.Value)
if matches == nil {
return &tengoLib.Map{}, nil
}
subMatchMap := make(map[string]tengoLib.Object)
for i, name := range o.Value.SubexpNames() {
if i != 0 && name != "" {
subMatchMap[name] = &tengoLib.String{Value: matches[i]}
}
}
ret = &tengoLib.ImmutableMap{Value: subMatchMap}
return
}