github.com/MontFerret/ferret@v0.18.0/pkg/runtime/expressions/variable.go (about)

     1  package expressions
     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  	VariableExpression struct {
    12  		src  core.SourceMap
    13  		name string
    14  	}
    15  
    16  	VariableDeclarationExpression struct {
    17  		*VariableExpression
    18  		init core.Expression
    19  	}
    20  )
    21  
    22  func NewVariableExpression(src core.SourceMap, name string) (*VariableExpression, error) {
    23  	if name == "" {
    24  		return nil, core.Error(core.ErrMissedArgument, "variable name")
    25  	}
    26  
    27  	return &VariableExpression{src, name}, nil
    28  }
    29  
    30  func NewVariableDeclarationExpression(src core.SourceMap, name string, init core.Expression) (*VariableDeclarationExpression, error) {
    31  	v, err := NewVariableExpression(src, name)
    32  
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  
    37  	if init == nil {
    38  		return nil, core.Error(core.ErrMissedArgument, "missed variable initializer")
    39  	}
    40  
    41  	return &VariableDeclarationExpression{v, init}, nil
    42  }
    43  
    44  func (e *VariableExpression) Exec(_ context.Context, scope *core.Scope) (core.Value, error) {
    45  	return scope.GetVariable(e.name)
    46  }
    47  
    48  func (e *VariableDeclarationExpression) Exec(ctx context.Context, scope *core.Scope) (core.Value, error) {
    49  	val, err := e.init.Exec(ctx, scope)
    50  
    51  	if err != nil {
    52  		return values.None, err
    53  	}
    54  
    55  	return values.None, scope.SetVariable(e.name, val)
    56  }