github.com/MontFerret/ferret@v0.18.0/pkg/runtime/expressions/operators/unary.go (about) 1 package operators 2 3 import ( 4 "context" 5 6 "github.com/MontFerret/ferret/pkg/runtime/core" 7 "github.com/MontFerret/ferret/pkg/runtime/values" 8 ) 9 10 type ( 11 UnaryOperatorVariant string 12 13 UnaryOperator struct { 14 *baseOperator 15 fn OperatorFunc 16 } 17 ) 18 19 const ( 20 UnaryOperatorVariantNoop UnaryOperatorVariant = "" 21 UnaryOperatorVariantNot UnaryOperatorVariant = "!" 22 UnaryOperatorVariantNot2 UnaryOperatorVariant = "NOT" 23 UnaryOperatorVariantNegative UnaryOperatorVariant = "-" 24 UnaryOperatorVariantPositive UnaryOperatorVariant = "+" 25 ) 26 27 var unaryOperatorVariants = map[UnaryOperatorVariant]OperatorFunc{ 28 UnaryOperatorVariantNoop: ToBoolean, 29 UnaryOperatorVariantNot: Not, 30 UnaryOperatorVariantNot2: Not, 31 UnaryOperatorVariantNegative: Negative, 32 UnaryOperatorVariantPositive: Positive, 33 } 34 35 func NewUnaryOperator( 36 src core.SourceMap, 37 exp core.Expression, 38 variantStr string, 39 ) (*UnaryOperator, error) { 40 variant := UnaryOperatorVariant(variantStr) 41 fn, exists := unaryOperatorVariants[variant] 42 43 if !exists { 44 return nil, core.Error(core.ErrInvalidArgument, "operator") 45 } 46 47 return &UnaryOperator{ 48 &baseOperator{ 49 src, 50 exp, 51 nil, 52 }, 53 fn, 54 }, nil 55 } 56 57 func (operator *UnaryOperator) Exec(ctx context.Context, scope *core.Scope) (core.Value, error) { 58 value, err := operator.left.Exec(ctx, scope) 59 60 if err != nil { 61 return nil, core.SourceError(operator.src, err) 62 } 63 64 return operator.Eval(ctx, value, nil) 65 } 66 67 func (operator *UnaryOperator) Eval(_ context.Context, left, _ core.Value) (core.Value, error) { 68 return operator.fn(left, values.None), nil 69 }