// EvalExpression returns the value of the given expression.
161300
func (scope *EvalScope) EvalExpression(expr string, cfg LoadConfig) (*Variable, error) {
	t, err := parser.ParseExpr(expr)
	if err != nil {
		return nil, err
	}

	ev, err := scope.evalToplevelTypeCast(t, cfg)
	if ev == nil && err == nil {
		ev, err = scope.evalAST(t)
	}
	if err != nil {
		return nil, err
	}
	ev.loadValue(cfg)
	if ev.Name == "" {
		ev.Name = expr
	}
	return ev, nil
}
155773
func (b *builtinLeftSig) evalString(row chunk.Row) (string, bool, error) {
	str, isNull, err := b.args[0].EvalString(b.ctx, row)
	if isNull || err != nil {
		return "", true, err
	}
	left, isNull, err := b.args[1].EvalInt(b.ctx, row)
	if isNull || err != nil {
		return "", true, err
	}
	runes, leftLength := []rune(str), int(left)
	if runeLength := len(runes); leftLength > runeLength {
		leftLength = runeLength
	} else if leftLength < 0 {
		leftLength = 0
	}
	return string(runes[:leftLength]), false, nil
}
707816
func (i *DefaultInterpreter) Execute(
	expression string,
	ctx *Context) (interface{}, error) {
	funcs := template.FuncMap{}
	for k, v := range i.Funcs {
		funcs[k] = v
	}
	var res interface{}
	resultEvaluated := false
	funcs["set"] = func(r interface{}) interface{} {
		res = r
		resultEvaluated = true
		return r
	}
	funcs["eval"] = func(intrpr, expr string) (interface{}, error) {
		return ctx.EvalExpr(intrpr, expr, ctx)
	}
	templName := fmt.Sprintf("<<%s>>", ctx.LongName)
	left := i.LeftDelim
	right := i.RightDelim
	if left == "" {
		left = "{{"
	}
	if right == "" {
		right = "}}"
	}
	if i.AutoEnclose &&
		!(strings.HasPrefix(expression, left) &&
			strings.HasSuffix(expression, right)) {
		expression = fmt.Sprintf("%s%s%s", left, expression, right)
	}
	t, err := template.
		New(templName).
		Delims(left, right).
		Funcs(funcs).
		Parse(expression)
	if err != nil {
		return nil, err
	}
	var buf bytes.Buffer
	err = t.Execute(&buf, ctx)
	if err != nil {
		return nil, err
	}
	if resultEvaluated {
		return res, nil
	}
	return buf.String(), nil
}
507857
func EvalInput(input interface{}) EvalOption {
	return func(e *EvalContext) {
		e.rawInput = &input
		e.hasInput = true
	}
}
744616
func (col *Column) Eval(row []types.Datum, _ context.Context) (types.Datum, error) {
	return row[col.Index], nil
}
472397
func (rs Rules) Eval(ctx context.Context, e *executor.Event, err error, ch Chain) (context.Context, *executor.Event, error) {
	return ch(rs.Chain()(ctx, e, err))
}
295764
func Expression(data string) *regexp.Regexp {
	if exp, ok := regexpMapping[data]; ok {
		return regexp.MustCompile(exp)
	}

	return nil
}
328233
func EvalBool(expr Expression, row []types.Datum, ctx context.Context) (bool, error) {
	data, err := expr.Eval(row, ctx)
	if err != nil {
		return false, errors.Trace(err)
	}
	if data.IsNull() {
		return false, nil
	}

	i, err := data.ToBool(ctx.GetSessionVars().StmtCtx)
	if err != nil {
		return false, errors.Trace(err)
	}
	return i != 0, nil
}
719252
func (f stringNotEqualsIgnoreCaseFunc) evaluate(values map[string][]string) bool {
	return !f.stringEqualsIgnoreCaseFunc.evaluate(values)
}
1301993
func (v *evalVisitor) evalField(ctx reflect.Value, fieldName string, exprRoot bool) reflect.Value {
	result := zero

	ctx, _ = indirect(ctx)
	if !ctx.IsValid() {
		return result
	}

	// check if this is a method call
	result, isMeth := v.evalMethod(ctx, fieldName, exprRoot)
	if !isMeth {
		switch ctx.Kind() {
		case reflect.Struct:
			// example: firstName => FirstName
			expFieldName := strings.Title(fieldName)

			// check if struct have this field and that it is exported
			if tField, ok := ctx.Type().FieldByName(expFieldName); ok && (tField.PkgPath == "") {
				// struct field
				result = ctx.FieldByIndex(tField.Index)
				break
			}

			// attempts to find template variable name as a struct tag
			result = v.evalStructTag(ctx, fieldName)
		case reflect.Map:
			nameVal := reflect.ValueOf(fieldName)
			if nameVal.Type().AssignableTo(ctx.Type().Key()) {
				// map key
				result = ctx.MapIndex(nameVal)
			}
		case reflect.Array, reflect.Slice:
			if i, err := strconv.Atoi(fieldName); (err == nil) && (i < ctx.Len()) {
				result = ctx.Index(i)
			}
		}
	}

	// check if result is a function
	result, _ = indirect(result)
	if result.Kind() == reflect.Func {
		result = v.evalFieldFunc(fieldName, result, exprRoot)
	}

	return result
}
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
}
579782
func (v *evalVisitor) evalCtxPathExpression(node *ast.PathExpression, exprRoot bool) interface{} {
	v.at(node)

	if node.IsDataRoot() {
		// `@root` - remove the first part
		parts := node.Parts[1:len(node.Parts)]

		result, _ := v.evalCtxPath(v.rootCtx(), parts, exprRoot)
		return result
	}

	return v.evalDepthPath(node.Depth, node.Parts, exprRoot)
}
723550
func (p *Parser) Expression() bool {

	if !p.UnaryExpression() {
		return false
	}

	for {
		p.Space()
		b, ok := p.Operator()
		if ok {
			p.ev.Add(b)
		} else {
			return true
		}
		p.Space()
		if !p.UnaryExpression() {
			return false // error
		}
		p.Space()
	}
}
259368
func (s *state) evalExpr(exp parse.Expr) (v Value, e error) {
	switch exp := exp.(type) {
	case *parse.NullExpr:
		return nil, nil
	case *parse.BoolExpr:
		return exp.Value, nil
	case *parse.NameExpr:
		if val, ok := s.scope.Get(exp.Name); ok {
			v = val
		} else {
			e = errors.New("undefined variable \"" + exp.Name + "\"")
		}
	case *parse.NumberExpr:
		num, err := strconv.ParseFloat(exp.Value, 64)
		if err != nil {
			return nil, err
		}
		return num, nil
	case *parse.StringExpr:
		return exp.Text, nil
	case *parse.GroupExpr:
		return s.evalExpr(exp.X)
	case *parse.UnaryExpr:
		in, err := s.evalExpr(exp.X)
		if err != nil {
			return nil, err
		}
		switch exp.Op {
		case parse.OpUnaryNot:
			return !CoerceBool(in), nil
		case parse.OpUnaryPositive:
			// no-op, +1 = 1, +(-1) = -1, +(false) = 0
			return CoerceNumber(in), nil
		case parse.OpUnaryNegative:
			return -CoerceNumber(in), nil
		}
	case *parse.BinaryExpr:
		left, err := s.evalExpr(exp.Left)
		if err != nil {
			return nil, err
		}
		right, err := s.evalExpr(exp.Right)
		if err != nil {
			return nil, err
		}
		switch exp.Op {
		case parse.OpBinaryAdd:
			return CoerceNumber(left) + CoerceNumber(right), nil
		case parse.OpBinarySubtract:
			return CoerceNumber(left) - CoerceNumber(right), nil
		case parse.OpBinaryMultiply:
			return CoerceNumber(left) * CoerceNumber(right), nil
		case parse.OpBinaryDivide:
			return CoerceNumber(left) / CoerceNumber(right), nil
		case parse.OpBinaryFloorDiv:
			return math.Floor(CoerceNumber(left) / CoerceNumber(right)), nil
		case parse.OpBinaryModulo:
			return float64(int(CoerceNumber(left)) % int(CoerceNumber(right))), nil
		case parse.OpBinaryPower:
			return math.Pow(CoerceNumber(left), CoerceNumber(right)), nil
		case parse.OpBinaryConcat:
			return CoerceString(left) + CoerceString(right), nil
		case parse.OpBinaryEndsWith:
			return strings.HasSuffix(CoerceString(left), CoerceString(right)), nil
		case parse.OpBinaryStartsWith:
			return strings.HasPrefix(CoerceString(left), CoerceString(right)), nil
		case parse.OpBinaryIn:
			return Contains(right, left)
		case parse.OpBinaryNotIn:
			res, err := Contains(right, left)
			if err != nil {
				return false, err
			}
			return !res, nil
		case parse.OpBinaryIs:
			if fn, ok := right.(func(v Value) bool); ok {
				return fn(left), nil
			}
			return nil, errors.New("right operand was of unexpected type")
		case parse.OpBinaryIsNot:
			if fn, ok := right.(func(v Value) bool); ok {
				return !fn(left), nil
			}
			return nil, errors.New("right operand was of unexpected type")
		case parse.OpBinaryMatches:
			reg, err := regexp.Compile(CoerceString(right))
			if err != nil {
				return nil, err
			}
			return reg.MatchString(CoerceString(left)), nil
		case parse.OpBinaryEqual:
			return Equal(left, right), nil
		case parse.OpBinaryNotEqual:
			return !Equal(left, right), nil
		case parse.OpBinaryGreaterEqual:
			return CoerceNumber(left) >= CoerceNumber(right), nil
		case parse.OpBinaryGreaterThan:
			return CoerceNumber(left) > CoerceNumber(right), nil
		case parse.OpBinaryLessEqual:
			return CoerceNumber(left) <= CoerceNumber(right), nil
		case parse.OpBinaryLessThan:
			return CoerceNumber(left) < CoerceNumber(right), nil
		case parse.OpBinaryRange:
			l, r := CoerceNumber(left), CoerceNumber(right)
			res := make([]float64, uint(math.Ceil(r-l))+1)
			for i, k := 0, l; k <= r; i, k = i+1, k+1 {
				res[i] = k
			}
			return res, nil
		case parse.OpBinaryBitwiseAnd:
			return int(CoerceNumber(left)) & int(CoerceNumber(right)), nil
		case parse.OpBinaryBitwiseOr:
			return int(CoerceNumber(left)) | int(CoerceNumber(right)), nil
		case parse.OpBinaryBitwiseXor:
			return int(CoerceNumber(left)) ^ int(CoerceNumber(right)), nil
		case parse.OpBinaryAnd:
			return CoerceBool(left) && CoerceBool(right), nil
		case parse.OpBinaryOr:
			return CoerceBool(left) && CoerceBool(right), nil
		}
	case *parse.FuncExpr:
		return s.evalFunction(exp)
	case *parse.FilterExpr:
		return s.evalFilter(exp)
	case *parse.GetAttrExpr:
		c, err := s.evalExpr(exp.Cont)
		if err != nil {
			return nil, err
		}
		k, err := s.evalExpr(exp.Attr)
		if err != nil {
			return nil, err
		}
		exargs := exp.Args
		args := make([]Value, len(exargs))
		for k, e := range exargs {
			v, err := s.evalExpr(e)
			if err != nil {
				return nil, err
			}
			args[k] = v
		}
		if set, ok := c.(macroSet); ok {
			if macro, ok := set.defs[CoerceString(k)]; ok {
				return s.callMacro(macro, args...)
			}
			return nil, errors.New("undefined macro: " + CoerceString(k))
		}
		v, err = GetAttr(c, k, args...)
		if err != nil {
			return nil, err
		}
	case *parse.TestExpr:
		if tfn, ok := s.env.Tests[exp.Name]; ok {
			eargs := exp.Args
			args := make([]Value, len(eargs))
			for i, e := range eargs {
				v, err := s.evalExpr(e)
				if err != nil {
					return nil, err
				}
				args[i] = v
			}
			return func(v Value) bool {
				return tfn(s, v, args...)
			}, nil
		}
		return nil, fmt.Errorf(`unknown test "%v"`, exp.Name)
	case *parse.TernaryIfExpr:
		cond, err := s.evalExpr(exp.Cond)
		if err != nil {
			return nil, err
		}
		if CoerceBool(cond) == true {
			return s.evalExpr(exp.TrueX)
		}
		return s.evalExpr(exp.FalseX)

	case *parse.HashExpr:
		vals := make(map[string]Value)
		for _, v := range exp.Elements {
			var key Value
			var err error
			if k, ok := v.Key.(*parse.NameExpr); ok {
				key = k.Name
			} else {
				key, err = s.evalExpr(v.Key)
				if err != nil {
					return nil, err
				}
			}
			val, err := s.evalExpr(v.Value)
			if err != nil {
				return nil, err
			}
			vals[CoerceString(key)] = val
		}
		return vals, nil

	case *parse.ArrayExpr:
		vals := make([]Value, len(exp.Elements))
		for i, v := range exp.Elements {
			val, err := s.evalExpr(v)
			if err != nil {
				return nil, err
			}
			vals[i] = val
		}
		return vals, nil
	}

	return v, nil
}
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
}
837313
func (b *builtinLTrimSig) evalString(row chunk.Row) (d string, isNull bool, err error) {
	d, isNull, err = b.args[0].EvalString(b.ctx, row)
	if isNull || err != nil {
		return d, isNull, err
	}
	return strings.TrimLeft(d, spaceChars), false, nil
}
226580
func Eval(expr string, context interface{}) (val interface{}, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("Eval paniked. %s", r)
		}
	}()

	exp, err := parser.ParseExpr(expr)

	if err != nil {
		return nilInterf, err
	}

	ctxt := createContext(context)

	val, err = eval(exp, ctxt)
	return val, err
}