// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.

// operand-var.go
package expr

import "fmt"

// -------- variable term
func newVarTerm(tk *Token) *term {
	t := &term{
		tk:       *tk,
		parent:   nil,
		children: nil,
		position: posLeaf,
		priority: priValue,
		evalFunc: evalVar,
	}
	t.tk.Sym = SymVariable
	return t
}

// -------- eval func
func evalVar(ctx ExprContext, opTerm *term) (v any, err error) {
	var exists bool
	name := opTerm.source()
	if v, exists = GetVar(ctx, name); !exists {
		if info, exists := GetFuncInfo(ctx, name); exists {
			v = info.Functor()
		} else {
			err = fmt.Errorf("undefined variable or function %q", name)
		}
	}
	return
}

// init
func init() {
	registerTermConstructor(SymIdentifier, newVarTerm)
}
