// Eval evaluates the given AST tree and returns its output value, the type
// of the output, and any error that occurred.
13585
func internalEval(root ast.Node, config *EvalConfig) (interface{}, ast.Type, error) {
	// Copy the scope so we can add our builtins
	if config == nil {
		config = new(EvalConfig)
	}
	scope := registerBuiltins(config.GlobalScope)
	implicitMap := map[ast.Type]map[ast.Type]string{
		ast.TypeFloat: {
			ast.TypeInt:    "__builtin_FloatToInt",
			ast.TypeString: "__builtin_FloatToString",
		},
		ast.TypeInt: {
			ast.TypeFloat:  "__builtin_IntToFloat",
			ast.TypeString: "__builtin_IntToString",
		},
		ast.TypeString: {
			ast.TypeInt:   "__builtin_StringToInt",
			ast.TypeFloat: "__builtin_StringToFloat",
			ast.TypeBool:  "__builtin_StringToBool",
		},
		ast.TypeBool: {
			ast.TypeString: "__builtin_BoolToString",
		},
	}

	// Build our own semantic checks that we always run
	tv := &TypeCheck{Scope: scope, Implicit: implicitMap}
	ic := &IdentifierCheck{Scope: scope}

	// Build up the semantic checks for execution
	checks := make(
		[]SemanticChecker,
		len(config.SemanticChecks),
		len(config.SemanticChecks)+2)
	copy(checks, config.SemanticChecks)
	checks = append(checks, ic.Visit)
	checks = append(checks, tv.Visit)

	// Run the semantic checks
	for _, check := range checks {
		if err := check(root); err != nil {
			return nil, ast.TypeInvalid, err
		}
	}

	// Execute
	v := &evalVisitor{Scope: scope}
	return v.Visit(root)
}
56203
func (lsf *LeastSquaresFunction) Eval(x float64) float64 {
	slope := lsf.slope()
	result := lsf.intercept(slope) + slope*x
	return result
}
703691
func Eval(n EvalNode, ctx EvalContext) (interface{}, error) {
	// Call the lower level eval which doesn't understand early exit,
	// and if we early exit, it isn't an error.
	result, err := EvalRaw(n, ctx)
	if err != nil {
		if _, ok := err.(EvalEarlyExitError); ok {
			return nil, nil
		}
	}

	return result, err
}
844542
func (csf *CubicSplineFunction) Eval(x float64) float64 {
	if !csf.points.XInRange(x) {
		panic("X out of range!")
	}
	idx := csf.points.SearchNextIndex(x)
	if idx >= len(csf.polynomials) {
		idx = len(csf.polynomials) - 1
	}
	return csf.polynomials[idx].Eval(x - csf.points.XAt(idx))
}
795919
func (n *NodeDestroyDeposedResourceInstanceObject) EvalTree() EvalNode {
	addr := n.ResourceInstanceAddr()

	var provider providers.Interface
	var providerSchema *ProviderSchema
	var state *states.ResourceInstanceObject
	var change *plans.ResourceInstanceChange
	var err error

	return &EvalSequence{
		Nodes: []EvalNode{
			&EvalGetProvider{
				Addr:   n.ResolvedProvider,
				Output: &provider,
				Schema: &providerSchema,
			},
			&EvalReadStateDeposed{
				Addr:           addr.Resource,
				Output:         &state,
				Key:            n.DeposedKey,
				Provider:       &provider,
				ProviderSchema: &providerSchema,
			},
			&EvalDiffDestroy{
				Addr:         addr.Resource,
				ProviderAddr: n.ResolvedProvider,
				State:        &state,
				Output:       &change,
			},
			// Call pre-apply hook
			&EvalApplyPre{
				Addr:   addr.Resource,
				State:  &state,
				Change: &change,
			},
			&EvalApply{
				Addr:           addr.Resource,
				Config:         nil, // No configuration because we are destroying
				State:          &state,
				Change:         &change,
				Provider:       &provider,
				ProviderAddr:   n.ResolvedProvider,
				ProviderSchema: &providerSchema,
				Output:         &state,
				Error:          &err,
			},
			// Always write the resource back to the state deposed... if it
			// was successfully destroyed it will be pruned. If it was not, it will
			// be caught on the next run.
			&EvalWriteStateDeposed{
				Addr:           addr.Resource,
				Key:            n.DeposedKey,
				ProviderAddr:   n.ResolvedProvider,
				ProviderSchema: &providerSchema,
				State:          &state,
			},
			&EvalApplyPost{
				Addr:  addr.Resource,
				State: &state,
				Error: &err,
			},
			&EvalReturnError{
				Error: &err,
			},
			&EvalUpdateStateHook{},
		},
	}
}
175452
func (p *Predicate) Eval(row virtualRow) (bool, error) {

	if p.True {
		return true, nil
	}

	// Find left attribute
	left := p.LeftValue.table + "." + p.LeftValue.lexeme
	val, ok := row[left]
	if !ok {
		return false, fmt.Errorf("Attribute [%s] not found in row", left)
	}
	p.LeftValue.v = val.v

	return p.Operator(p.LeftValue, p.RightValue), nil
}
106732
func evalSliceExpr(slice *SliceExpr, env Env) (reflect.Value, error) {
	xs, err := EvalExpr(slice.X, env)
	if err != nil {
		return reflect.Value{}, err
	}
	x := xs[0]

	var l, h int
	if slice.Low != nil {
		if l, err = evalInteger(slice.Low, env); err != nil {
			return reflect.Value{}, err
		}
	}
	if slice.High != nil {
		if h, err = evalInteger(slice.High, env); err != nil {
			return reflect.Value{}, err
		}
	} else {
		h = x.Len()
	}

	t := slice.KnownType()[0]
	switch t.Kind() {
	case reflect.Ptr:
		// Short hand for array pointers
		x = x.Elem()
		fallthrough
	case reflect.Array, reflect.String:
		if l < 0 || h > x.Len() || h < l {
			return reflect.Value{}, PanicSliceOutOfBounds{}
		}
	case reflect.Slice:
		if l < 0 || h > x.Cap() || h < l {
			return reflect.Value{}, PanicSliceOutOfBounds{}
		}
	}
	return x.Slice(l, h), nil
}
377476
func (e *Expr) Eval(getter VarGetter) (Value, error) {
	if e.root == nil {
		return Zero(), nil
	}
	v, err := eval(e, getter, e.root)
	if err != nil {
		return Zero(), err
	}
	return v, nil
}
1194696
func (col *CorrelatedColumn) Eval(row chunk.Row) (types.Datum, error) {
	return *col.Data, nil
}
883405
func (s *state) eval2def(n1, n2 ast.Node) (data.Value, data.Value) {
	return s.evaldef(n1), s.evaldef(n2)
}
905228
func Eval(js string, expr string, opts ...string) ([]json.RawMessage, error) {
	jq, err := New(bytes.NewReader([]byte(js)), expr, opts...)
	if err != nil {
		return nil, err
	}

	ret := make([]json.RawMessage, 0, 16)
	for {
		next, err := jq.Next()
		switch err {
		case nil:
			ret = append(ret, next)
		case io.EOF:
			return ret, nil
		default:
			return ret, err
		}
	}
	panic("unreachable") // for go 1.0
}
788563
func (e Expr) Eval(m *Model) (Vector, error) {
	if len(e) == 0 {
		return nil, fmt.Errorf("must specify at least one word to evaluate")
	}
	return m.Eval(e)
}
606833
func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
	if !receiver.IsValid() {
		return zero
	}
	typ := receiver.Type()
	receiver, _ = indirect(receiver)
	// Unless it's an interface, need to get to a value of type *T to guarantee
	// we see all methods of T and *T.
	ptr := receiver
	if ptr.Kind() != reflect.Interface && ptr.CanAddr() {
		ptr = ptr.Addr()
	}
	if method := ptr.MethodByName(fieldName); method.IsValid() {
		return s.evalCall(dot, method, node, fieldName, args, final)
	}
	hasArgs := len(args) > 1 || final.IsValid()
	// It's not a method; must be a field of a struct or an element of a map. The receiver must not be nil.
	receiver, isNil := indirect(receiver)
	if isNil {
		s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
	}
	switch receiver.Kind() {
	case reflect.Struct:
		tField, ok := receiver.Type().FieldByName(fieldName)
		if ok {
			field := receiver.FieldByIndex(tField.Index)
			if tField.PkgPath != "" { // field is unexported
				s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
			}
			// If it's a function, we must call it.
			if hasArgs {
				s.errorf("%s has arguments but cannot be invoked as function", fieldName)
			}
			return field
		}
		s.errorf("%s is not a field of struct type %s", fieldName, typ)
	case reflect.Map:
		// If it's a map, attempt to use the field name as a key.
		nameVal := reflect.ValueOf(fieldName)
		if nameVal.Type().AssignableTo(receiver.Type().Key()) {
			if hasArgs {
				s.errorf("%s is not a method but has arguments", fieldName)
			}
			return receiver.MapIndex(nameVal)
		}
	}
	s.errorf("can't evaluate field %s in type %s", fieldName, typ)
	panic("not reached")
}
824107
func EvalRaw(n EvalNode, ctx EvalContext) (interface{}, error) {
	path := "unknown"
	if ctx != nil {
		path = ctx.Path().String()
	}
	if path == "" {
		path = "<root>"
	}

	log.Printf("[TRACE] %s: eval: %T", path, n)
	output, err := n.Eval(ctx)
	if err != nil {
		switch err.(type) {
		case EvalEarlyExitError:
			log.Printf("[TRACE] %s: eval: %T, early exit err: %s", path, n, err)
		case tfdiags.NonFatalError:
			log.Printf("[WARN] %s: eval: %T, non-fatal err: %s", path, n, err)
		default:
			log.Printf("[ERROR] %s: eval: %T, err: %s", path, n, err)
		}
	}

	return output, err
}
612119
func (g *Graph) evalBool(e *Graph) bool {
	i, err := g.Eval(e)
	if err != nil {
		return false
	}
	b, _ := _boolf(i)
	return b
}
867357
func EvalInt(expr string, context interface{}) (int, error) {
	val, err := Eval(expr, context)
	if err != nil {
		return 0, err
	}
	return castInt(val)
}
659973
func (s *state) evalField(dot reflect.Value, fieldName string, node expr.Node, args []expr.Node, final, receiver reflect.Value) reflect.Value {

	//u.Debugf("evalField: valid?%v", receiver.IsValid())
	if !receiver.IsValid() {
		//u.Warnf("bailing")
		return zero
	}
	typ := receiver.Type()
	receiver, _ = findValue(receiver)
	// Unless it's an interface, need to get to a value of type *T to guarantee
	// we see all methods of T and *T.
	ptr := receiver
	if ptr.Kind() != reflect.Interface && ptr.CanAddr() {
		ptr = ptr.Addr()
	}
	if method := ptr.MethodByName(fieldName); method.IsValid() {
		//u.Warnf("unimplemented method: %v", fieldName)
		return s.evalCall(dot, method, node, fieldName, args, final)
	}
	hasArgs := len(args) > 1 || final.IsValid()
	// It's not a method; must be a field of a struct or an element of a map. The receiver must not be nil.
	receiver, isNil := findValue(receiver)
	//u.Debugf("fld:%s  receiver kind():%v  val: %v", fieldName, receiver.Kind(), receiver)
	if isNil {
		return zero
	}
	switch receiver.Kind() {
	case reflect.Struct:
		tField, ok := receiver.Type().FieldByName(fieldName)
		if !ok {
			tField, ok = receiver.Type().FieldByNameFunc(lowerFieldMatch(fieldName))
			if !ok {
				tagName := strings.ToLower(fieldName)
				// Wow, this is pretty bruttaly expensive
				// Iterate over all available fields and read the tag value
				for i := 0; i < receiver.NumField(); i++ {
					// Get the field, returns https://golang.org/pkg/reflect/#StructField
					field := receiver.Type().Field(i)

					// Get the field tag value
					tag := field.Tag.Get("json")
					if tag == tagName {
						tField = field
						ok = true
						break
					}
				}
			}
		}
		//u.Infof("got field? %v", fieldName, tField)
		if ok {
			field := receiver.FieldByIndex(tField.Index)
			if tField.PkgPath != "" { // field is unexported
				return s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
			}
			// If it's a function, we must call it.
			if hasArgs {
				return s.errorf("%s has arguments but cannot be invoked as function", fieldName)
			}
			return field
		}
		//context reader doesn't care about empty values
		return zero
	case reflect.Map:
		// If it's a map, attempt to use the field name as a key.
		nameVal := reflect.ValueOf(fieldName)
		if nameVal.Type().AssignableTo(receiver.Type().Key()) {
			if hasArgs {
				return s.errorf("%s is not a method but has arguments", fieldName)
			}
			result := receiver.MapIndex(nameVal)
			if !result.IsValid() {
				u.Errorf("could not evaluate %v", nameVal)
				// switch s.tmpl.option.missingKey {
				// case mapInvalid:
				// 	// Just use the invalid value.
				// case mapZeroValue:
				// 	result = reflect.Zero(receiver.Type().Elem())
				// case mapError:
				// 	s.errorf("map has no entry for key %q", fieldName)
				// }
			}
			return result
		}
	}
	s.errorf("can't evaluate field %s in type %s", fieldName, typ)
	panic("not reached")
}