github.com/MontFerret/ferret@v0.18.0/pkg/runtime/expressions/body.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 BodyExpression struct {
    11  	statements []core.Expression
    12  	expression core.Expression
    13  }
    14  
    15  func NewBodyExpression(size int) *BodyExpression {
    16  	return &BodyExpression{make([]core.Expression, 0, size), nil}
    17  }
    18  
    19  func (b *BodyExpression) Add(exp core.Expression) error {
    20  	switch exp.(type) {
    21  	case *ForExpression, *ReturnExpression:
    22  		if b.expression != nil {
    23  			return core.Error(core.ErrInvalidOperation, "return expression is already defined")
    24  		}
    25  
    26  		b.expression = exp
    27  	default:
    28  		b.statements = append(b.statements, exp)
    29  	}
    30  
    31  	return nil
    32  }
    33  
    34  func (b *BodyExpression) Exec(ctx context.Context, scope *core.Scope) (core.Value, error) {
    35  	select {
    36  	case <-ctx.Done():
    37  		return values.None, core.ErrTerminated
    38  	default:
    39  	}
    40  
    41  	for _, exp := range b.statements {
    42  		if _, err := exp.Exec(ctx, scope); err != nil {
    43  			return values.None, err
    44  		}
    45  	}
    46  
    47  	if b.expression != nil {
    48  		return b.expression.Exec(ctx, scope)
    49  	}
    50  
    51  	return values.None, nil
    52  }