1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/pkg/runtime/expressions/variable.go
Tim Voronov 549b4abd3b
Feature/#5 collect keyword alt (#141)
Implemented COLLECT key word
2018-10-24 21:30:05 -04:00

57 lines
1.3 KiB
Go

package expressions
import (
"context"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
"github.com/pkg/errors"
)
type (
VariableExpression struct {
src core.SourceMap
name string
}
VariableDeclarationExpression struct {
*VariableExpression
init core.Expression
}
)
func NewVariableExpression(src core.SourceMap, name string) (*VariableExpression, error) {
if name == "" {
return nil, errors.Wrap(core.ErrMissedArgument, "missed variable name")
}
return &VariableExpression{src, name}, nil
}
func NewVariableDeclarationExpression(src core.SourceMap, name string, init core.Expression) (*VariableDeclarationExpression, error) {
v, err := NewVariableExpression(src, name)
if err != nil {
return nil, err
}
if core.IsNil(init) {
return nil, errors.Wrap(core.ErrMissedArgument, "missed variable initializer")
}
return &VariableDeclarationExpression{v, init}, nil
}
func (e *VariableExpression) Exec(_ context.Context, scope *core.Scope) (core.Value, error) {
return scope.GetVariable(e.name)
}
func (e *VariableDeclarationExpression) Exec(ctx context.Context, scope *core.Scope) (core.Value, error) {
val, err := e.init.Exec(ctx, scope)
if err != nil {
return values.None, err
}
return values.None, scope.SetVariable(e.name, val)
}