1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-23 01:24:30 +02:00
ferret/pkg/runtime/expressions/operators/math.go
Tim Voronov 5620be211c
Next (#214)
* Renamed DOCUMENT to PAGE

* Added PageLoadParams

* Added PageLoadParams

* Renamed LoadPageParams -> PageLoadParams

* Added support for context.Done() (#201)

* Bug/#189 operators precedence (#202)

* Fixed math operators precedence

* Fixed logical operators precedence

* Fixed array operator

* Added support for parentheses to enforce a different operator evaluation order

* Feature/#200 drivers (#209)

* Added new interfaces

* Renamed dynamic to cdp driver

* Renamed drivers

* Added ELEMENT_EXISTS function (#210)

* Renamed back PAGE to DOCUMENT (#211)

* Added Getter and Setter interfaces
2018-12-21 23:14:41 -05:00

97 lines
2.1 KiB
Go

package operators
import (
"context"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
)
type (
MathOperatorType string
MathOperator struct {
*baseOperator
opType MathOperatorType
fn OperatorFunc
leftOnly bool
}
)
const (
MathOperatorTypeAdd MathOperatorType = "+"
MathOperatorTypeSubtract MathOperatorType = "-"
MathOperatorTypeMultiply MathOperatorType = "*"
MathOperatorTypeDivide MathOperatorType = "/"
MathOperatorTypeModulus MathOperatorType = "%"
MathOperatorTypeIncrement MathOperatorType = "++"
MathOperatorTypeDecrement MathOperatorType = "--"
)
var mathOperators = map[MathOperatorType]OperatorFunc{
MathOperatorTypeAdd: Add,
MathOperatorTypeSubtract: Subtract,
MathOperatorTypeMultiply: Multiply,
MathOperatorTypeDivide: Divide,
MathOperatorTypeModulus: Modulus,
MathOperatorTypeIncrement: Increment,
MathOperatorTypeDecrement: Decrement,
}
func NewMathOperator(
src core.SourceMap,
left core.Expression,
right core.Expression,
operator MathOperatorType,
) (*MathOperator, error) {
fn, exists := mathOperators[operator]
if !exists {
return nil, core.Error(core.ErrInvalidArgument, "operator type")
}
var leftOnly bool
if operator == "++" || operator == "--" {
leftOnly = true
}
return &MathOperator{
&baseOperator{src, left, right},
operator,
fn,
leftOnly,
}, nil
}
func (operator *MathOperator) Type() MathOperatorType {
return operator.opType
}
func (operator *MathOperator) Exec(ctx context.Context, scope *core.Scope) (core.Value, error) {
left, err := operator.left.Exec(ctx, scope)
if err != nil {
return nil, err
}
if operator.leftOnly {
return operator.Eval(ctx, left, values.None)
}
right, err := operator.right.Exec(ctx, scope)
if err != nil {
return nil, err
}
return operator.Eval(ctx, left, right)
}
func (operator *MathOperator) Eval(_ context.Context, left, right core.Value) (core.Value, error) {
if operator.leftOnly {
return operator.fn(left, values.None), nil
}
return operator.fn(left, right), nil
}