Files
hetty/pkg/filter/ast.go

88 lines
1.8 KiB
Go
Raw Normal View History

package filter
2020-11-16 22:14:58 +01:00
2022-01-21 11:45:54 +01:00
import (
"encoding/gob"
"regexp"
2022-03-23 14:31:27 +01:00
"strconv"
2022-01-21 11:45:54 +01:00
"strings"
)
2020-11-16 22:14:58 +01:00
type Expression interface {
String() string
}
type PrefixExpression struct {
Operator TokenType
Right Expression
}
2022-01-21 11:45:54 +01:00
func (pe PrefixExpression) String() string {
2020-11-16 22:14:58 +01:00
b := strings.Builder{}
b.WriteString("(")
b.WriteString(pe.Operator.String())
b.WriteString(" ")
b.WriteString(pe.Right.String())
b.WriteString(")")
return b.String()
}
type InfixExpression struct {
Operator TokenType
Left Expression
Right Expression
}
2022-01-21 11:45:54 +01:00
func (ie InfixExpression) String() string {
2020-11-16 22:14:58 +01:00
b := strings.Builder{}
b.WriteString("(")
b.WriteString(ie.Left.String())
b.WriteString(" ")
b.WriteString(ie.Operator.String())
b.WriteString(" ")
b.WriteString(ie.Right.String())
b.WriteString(")")
return b.String()
}
type StringLiteral struct {
Value string
}
2022-01-21 11:45:54 +01:00
func (sl StringLiteral) String() string {
2022-03-23 14:31:27 +01:00
return strconv.Quote(sl.Value)
2020-11-16 22:14:58 +01:00
}
2022-01-21 11:45:54 +01:00
type RegexpLiteral struct {
*regexp.Regexp
}
2022-03-23 14:31:27 +01:00
func (rl RegexpLiteral) String() string {
return strconv.Quote(rl.Regexp.String())
}
2022-01-21 11:45:54 +01:00
func (rl RegexpLiteral) MarshalBinary() ([]byte, error) {
return []byte(rl.Regexp.String()), nil
}
func (rl *RegexpLiteral) UnmarshalBinary(data []byte) error {
re, err := regexp.Compile(string(data))
if err != nil {
return err
}
*rl = RegexpLiteral{re}
return nil
}
func init() {
// The `filter` package was previously named `search`.
// We use the legacy names for backwards compatibility with existing database data.
gob.RegisterName("github.com/dstotijn/hetty/pkg/search.PrefixExpression", PrefixExpression{})
gob.RegisterName("github.com/dstotijn/hetty/pkg/search.InfixExpression", InfixExpression{})
gob.RegisterName("github.com/dstotijn/hetty/pkg/search.StringLiteral", StringLiteral{})
gob.RegisterName("github.com/dstotijn/hetty/pkg/search.RegexpLiteral", RegexpLiteral{})
2022-01-21 11:45:54 +01:00
}