1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-21 01:21:34 +02:00
ferret/pkg/runtime/expressions/condition.go

68 lines
1.2 KiB
Go
Raw Normal View History

2018-09-22 17:24:35 +02:00
package expressions
import (
"context"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
)
type ConditionExpression struct {
src core.SourceMap
test core.Expression
consequent core.Expression
alternate core.Expression
}
func NewConditionExpression(
src core.SourceMap,
test core.Expression,
consequent core.Expression,
alternate core.Expression,
) (*ConditionExpression, error) {
2018-10-28 07:45:26 +02:00
if test == nil {
2018-09-22 17:24:35 +02:00
return nil, core.Error(core.ErrMissedArgument, "test expression")
}
2018-10-28 07:45:26 +02:00
if alternate == nil {
2018-09-22 17:24:35 +02:00
return nil, core.Error(core.ErrMissedArgument, "alternate expression")
}
return &ConditionExpression{
src,
test,
consequent,
alternate,
}, nil
}
func (e *ConditionExpression) Exec(ctx context.Context, scope *core.Scope) (core.Value, error) {
out, err := e.test.Exec(ctx, scope)
if err != nil {
return values.None, core.SourceError(e.src, err)
}
2018-09-23 02:28:33 +02:00
cond := values.ToBoolean(out)
2018-09-22 17:24:35 +02:00
var next core.Expression
if cond == values.True {
next = e.consequent
// shortcut version
if next == nil {
return out, nil
}
} else {
next = e.alternate
}
res, err := next.Exec(ctx, scope)
if err != nil {
return values.None, core.SourceError(e.src, err)
}
return res, nil
}