// convert an ast.Expr to an Expr without actually checking it. This
// is useful for avoiding special cases in error messages.
774925
func fakeCheckExpr(expr ast.Expr, env Env) Expr {
	if expr == nil {
		return nil
	}
	switch expr := expr.(type) {
	case *ast.BadExpr:
		return &BadExpr{BadExpr: expr}
	case *ast.Ident:
		return &Ident{Ident: expr}
	case *ast.Ellipsis:
		return &Ellipsis{Ellipsis: expr}
	case *ast.BasicLit:
		return &BasicLit{BasicLit: expr}
	case *ast.FuncLit:
		return &FuncLit{FuncLit: expr}
	case *ast.CompositeLit:
		c := &CompositeLit{CompositeLit: expr}
		if expr.Elts != nil {
			c.Elts = make([]Expr, len(expr.Elts))
			for i := range c.Elts {
				c.Elts[i] = fakeCheckExpr(expr.Elts[i], env)
			}
		}
		return c
	case *ast.ParenExpr:
		p := &ParenExpr{ParenExpr: expr}
		p.X = fakeCheckExpr(expr.X, env)
		return p
	case *ast.SelectorExpr:
		s := &SelectorExpr{SelectorExpr: expr}
		s.X = fakeCheckExpr(expr.X, env)
		s.Sel = &Ident{Ident: expr.Sel}
		return s
	case *ast.IndexExpr:
		i := &IndexExpr{IndexExpr: expr}
		i.X = fakeCheckExpr(expr.X, env)
		i.Index = fakeCheckExpr(expr.Index, env)
		return i
	case *ast.SliceExpr:
		s := &SliceExpr{SliceExpr: expr}
		s.X = fakeCheckExpr(expr.X, env)
		if s.Low != nil {
			s.Low = fakeCheckExpr(expr.Low, env)
		}
		if s.High != nil {
			s.High = fakeCheckExpr(expr.High, env)
		}
		// TODO[crc] go 1.2 introduces the [::] notation. Add after upgrade
		//if s.Max != nil {
			//s.Max = fakeCheckExpr(s.Max, env)
		//}
		return s
	case *ast.TypeAssertExpr:
		a := &TypeAssertExpr{TypeAssertExpr: expr}
		a.X = fakeCheckExpr(a.X, env)
		return a
	case *ast.CallExpr:
		c := &CallExpr{CallExpr: expr}
		if ident, ok := expr.Fun.(*ast.Ident); ok {
			if _, ok := builtinFuncs[ident.Name]; ok {
				c.isBuiltin = true
			}
		}
		if !c.isBuiltin {
			if _, t, isType, _ := checkType(expr.Fun, env); isType {
				c.isTypeConversion = true
				c.knownType = knownType{t}
			}
		}
		c.Fun = fakeCheckExpr(expr.Fun, env)
		if expr.Args != nil {
			c.Args = make([]Expr, len(expr.Args))
			for i := range c.Args {
				c.Args[i] = fakeCheckExpr(expr.Args[i], env)
			}
		}
		return c
	case *ast.StarExpr:
		s := &StarExpr{StarExpr: expr}
		s.X = fakeCheckExpr(expr.X, env)
		return s
	case *ast.UnaryExpr:
		u := &UnaryExpr{UnaryExpr: expr}
		u.X = fakeCheckExpr(expr.X, env)
		return u
	case *ast.BinaryExpr:
		b := &BinaryExpr{BinaryExpr: expr}
		b.X = fakeCheckExpr(expr.X, env)
		b.Y = fakeCheckExpr(expr.Y, env)
		return b
	case *ast.KeyValueExpr:
		kv := &KeyValueExpr{KeyValueExpr: expr}
		kv.Key = fakeCheckExpr(expr.Key, env)
		kv.Value = fakeCheckExpr(expr.Value, env)
		return kv

	// Types
	case *ast.ArrayType:
		arrayT := &ArrayType{ArrayType: expr}
		arrayT.Len = fakeCheckExpr(expr.Len, env)
		arrayT.Elt = fakeCheckExpr(expr.Elt, env)
		return arrayT
	case *ast.StructType:
		structT := &StructType{StructType: expr}
		return structT
	case *ast.FuncType:
		funcT := &FuncType{FuncType: expr}
		return funcT
	case *ast.InterfaceType:
		interfaceT := &InterfaceType{InterfaceType: expr}
		return interfaceT
	case *ast.MapType:
		mapT := &MapType{MapType: expr}
		mapT.Key = fakeCheckExpr(expr.Key, env)
		mapT.Value = fakeCheckExpr(expr.Value, env)
		return mapT
	case *ast.ChanType:
		chanT := &ChanType{ChanType: expr}
		chanT.Value = fakeCheckExpr(expr.Value, env)
		return chanT

	default:
		panic(fmt.Sprintf("fakeCheckExpr(%T)", expr))
	}
}
973485
func (p *Parser) ParseExpr() (Expr, error) {
	var err error
	// Dummy root node.
	root := &BinaryExpr{}

	// Parse a non-binary expression type to start.
	// This variable will always be the root of the expression tree.
	root.RHS, err = p.parseUnaryExpr()
	if err != nil {
		return nil, err
	}

	// Loop over operations and unary exprs and build a tree based on precendence.
	for {
		// If the next token is NOT an operator then return the expression.
		op, _, _ := p.ScanIgnoreWhitespace()
		if !op.isOperator() {
			p.Unscan()
			return root.RHS, nil
		}

		// Otherwise parse the next expression.
		var rhs Expr
		if IsRegexOp(op) {
			// RHS of a regex operator must be a regular expression.
			if rhs, err = p.parseRegex(); err != nil {
				return nil, err
			}
			// parseRegex can return an empty type, but we need it to be present
			if rhs.(*RegexLiteral) == nil {
				tok, pos, lit := p.ScanIgnoreWhitespace()
				return nil, newParseError(tokstr(tok, lit), []string{"regex"}, pos)
			}
		} else {
			if rhs, err = p.parseUnaryExpr(); err != nil {
				return nil, err
			}
		}

		// Find the right spot in the tree to add the new expression by
		// descending the RHS of the expression tree until we reach the last
		// BinaryExpr or a BinaryExpr whose RHS has an operator with
		// precedence >= the operator being added.
		for node := root; ; {
			r, ok := node.RHS.(*BinaryExpr)
			if !ok || r.Op.Precedence() >= op.Precedence() {
				// Add the new expression here and break.
				node.RHS = &BinaryExpr{LHS: node.RHS, RHS: rhs, Op: op}
				break
			}
			node = r
		}
	}
}
639056
func Compile(expr string, opt RegexOptions) (*Regexp, error) {
	// parse it
	tree, err := syntax.Parse(expr, syntax.RegexOptions(opt))
	if err != nil {
		return nil, err
	}

	// translate it to code
	code, err := syntax.Write(tree)
	if err != nil {
		return nil, err
	}

	// return it
	return &Regexp{
		pattern:      expr,
		options:      opt,
		caps:         code.Caps,
		capnames:     tree.Capnames,
		capslist:     tree.Caplist,
		capsize:      code.Capsize,
		code:         code,
		MatchTimeout: DefaultMatchTimeout,
	}, nil
}
852949
func ScalarFuncs2Exprs(funcs []*ScalarFunction) []Expression {
	result := make([]Expression, 0, len(funcs))
	for _, col := range funcs {
		result = append(result, col)
	}
	return result
}
576083
func (c Call) MakeExpr(output *Term) *Expr {
	terms := []*Term(c)
	return NewExpr(append(terms, output))
}
301478
func unparen(x ast.Expr) ast.Expr {
	if p, isParen := x.(*ast.ParenExpr); isParen {
		x = unparen(p.X)
	}
	return x
}
191060
func eval(e *Expr, getter VarGetter, node ast.Expr) (Value, error) {
	switch n := node.(type) {
	case *ast.Ident:
		if getter == nil {
			return e.pool.onVarMissing(n.Name)
		}
		val, ok := getter.GetVar(n.Name)
		if !ok {
			return e.pool.onVarMissing(n.Name)
		}
		return val, nil

	case *ast.BasicLit:
		switch n.Kind {
		case token.INT:
			i, err := strconv.ParseInt(n.Value, 10, 64)
			if err != nil {
				return Zero(), err
			}
			return Int(i), nil
		case token.FLOAT:
			f, err := strconv.ParseFloat(n.Value, 64)
			if err != nil {
				return Zero(), err
			}
			return Float(f), nil
		case token.CHAR, token.STRING:
			s, err := strconv.Unquote(n.Value)
			if err != nil {
				return Zero(), err
			}
			return String(s), nil
		default:
			return Zero(), fmt.Errorf("unsupported token: %s(%v)", n.Value, n.Kind)
		}

	case *ast.ParenExpr:
		return eval(e, getter, n.X)

	case *ast.CallExpr:
		args := make([]Value, 0, len(n.Args))
		for _, arg := range n.Args {
			if val, err := eval(e, getter, arg); err != nil {
				return Zero(), err
			} else {
				args = append(args, val)
			}
		}
		if fnIdent, ok := n.Fun.(*ast.Ident); ok {
			if fn, ok := e.pool.fn(fnIdent.Name); !ok {
				return Zero(), fmt.Errorf("undefined function `%v`", fnIdent.Name)
			} else {
				return fn(args...)
			}
		}
		return Zero(), fmt.Errorf("unexpected func type: %T", n.Fun)

	case *ast.UnaryExpr:
		switch n.Op {
		case token.ADD:
			return eval(e, getter, n.X)
		case token.SUB:
			x, err := eval(e, getter, n.X)
			if err == nil {
				x, err = Zero().Sub(x)
			}
			return x, err
		case token.NOT:
			x, err := eval(e, getter, n.X)
			if err == nil {
				x = x.Not()
			}
			return x, err
		default:
			return Zero(), fmt.Errorf("unsupported unary op: %v", n.Op)
		}

	case *ast.BinaryExpr:
		x, err := eval(e, getter, n.X)
		if err != nil {
			return Zero(), err
		}
		y, err := eval(e, getter, n.Y)
		if err != nil {
			return Zero(), err
		}
		switch n.Op {
		case token.ADD:
			return x.Add(y)
		case token.SUB:
			return x.Sub(y)
		case token.MUL:
			return x.Mul(y)
		case token.QUO:
			return x.Quo(y)
		case token.REM:
			return x.Rem(y)
		case token.XOR:
			return x.Pow(y)
		case token.LAND:
			return x.And(y), nil
		case token.LOR:
			return x.Or(y), nil
		case token.EQL:
			return x.Eq(y)
		case token.NEQ:
			return x.Ne(y)
		case token.GTR:
			return x.Gt(y)
		case token.GEQ:
			return x.Ge(y)
		case token.LSS:
			return x.Lt(y)
		case token.LEQ:
			return x.Le(y)
		default:
			return Zero(), fmt.Errorf("unexpected binary operator: %v", n.Op)
		}

	default:
		return Zero(), fmt.Errorf("unexpected node type %T", n)
	}
}
1043814
func cloneExpr(expr Expression) Expression {
	switch expr := expr.(type) {
	case *ActionExpr:
		return &ActionExpr{
			Code:   expr.Code,
			Expr:   cloneExpr(expr.Expr),
			FuncIx: expr.FuncIx,
			p:      expr.p,
		}
	case *AndExpr:
		return &AndExpr{
			Expr: cloneExpr(expr.Expr),
			p:    expr.p,
		}
	case *AndCodeExpr:
		return &AndCodeExpr{
			Code:   expr.Code,
			FuncIx: expr.FuncIx,
			p:      expr.p,
		}
	case *CharClassMatcher:
		return &CharClassMatcher{
			Chars:          append([]rune{}, expr.Chars...),
			IgnoreCase:     expr.IgnoreCase,
			Inverted:       expr.Inverted,
			posValue:       expr.posValue,
			Ranges:         append([]rune{}, expr.Ranges...),
			UnicodeClasses: append([]string{}, expr.UnicodeClasses...),
		}
	case *ChoiceExpr:
		alts := make([]Expression, 0, len(expr.Alternatives))
		for i := 0; i < len(expr.Alternatives); i++ {
			alts = append(alts, cloneExpr(expr.Alternatives[i]))
		}
		return &ChoiceExpr{
			Alternatives: alts,
			p:            expr.p,
		}
	case *LabeledExpr:
		return &LabeledExpr{
			Expr:  cloneExpr(expr.Expr),
			Label: expr.Label,
			p:     expr.p,
		}
	case *NotExpr:
		return &NotExpr{
			Expr: cloneExpr(expr.Expr),
			p:    expr.p,
		}
	case *NotCodeExpr:
		return &NotCodeExpr{
			Code:   expr.Code,
			FuncIx: expr.FuncIx,
			p:      expr.p,
		}
	case *OneOrMoreExpr:
		return &OneOrMoreExpr{
			Expr: cloneExpr(expr.Expr),
			p:    expr.p,
		}
	case *SeqExpr:
		exprs := make([]Expression, 0, len(expr.Exprs))
		for i := 0; i < len(expr.Exprs); i++ {
			exprs = append(exprs, cloneExpr(expr.Exprs[i]))
		}
		return &SeqExpr{
			Exprs: exprs,
			p:     expr.p,
		}
	case *StateCodeExpr:
		return &StateCodeExpr{
			p:      expr.p,
			Code:   expr.Code,
			FuncIx: expr.FuncIx,
		}
	case *ZeroOrMoreExpr:
		return &ZeroOrMoreExpr{
			Expr: cloneExpr(expr.Expr),
			p:    expr.p,
		}
	case *ZeroOrOneExpr:
		return &ZeroOrOneExpr{
			Expr: expr.Expr,
			p:    expr.p,
		}
	}
	return expr
}
756807
func parseExpr(s, what string) ast.Expr {
	x, err := parser.ParseExpr(s)
	if err != nil {
		fmt.Fprintf(os.Stderr, "parsing %s %s at %s\n", what, s, err)
		os.Exit(2)
	}
	return x
}
361197
func (p *parser) parseExpr(expr interface{}) (interface{}, bool) {

	p.ExprCnt++
	if p.ExprCnt > p.maxExprCnt {
		panic(errMaxExprCnt)
	}

	var val interface{}
	var ok bool
	switch expr := expr.(type) {
	case *actionExpr:
		val, ok = p.parseActionExpr(expr)
	case *andCodeExpr:
		val, ok = p.parseAndCodeExpr(expr)
	case *andExpr:
		val, ok = p.parseAndExpr(expr)
	case *anyMatcher:
		val, ok = p.parseAnyMatcher(expr)
	case *charClassMatcher:
		val, ok = p.parseCharClassMatcher(expr)
	case *choiceExpr:
		val, ok = p.parseChoiceExpr(expr)
	case *labeledExpr:
		val, ok = p.parseLabeledExpr(expr)
	case *litMatcher:
		val, ok = p.parseLitMatcher(expr)
	case *notCodeExpr:
		val, ok = p.parseNotCodeExpr(expr)
	case *notExpr:
		val, ok = p.parseNotExpr(expr)
	case *oneOrMoreExpr:
		val, ok = p.parseOneOrMoreExpr(expr)
	case *recoveryExpr:
		val, ok = p.parseRecoveryExpr(expr)
	case *ruleRefExpr:
		val, ok = p.parseRuleRefExpr(expr)
	case *seqExpr:
		val, ok = p.parseSeqExpr(expr)
	case *throwExpr:
		val, ok = p.parseThrowExpr(expr)
	case *zeroOrMoreExpr:
		val, ok = p.parseZeroOrMoreExpr(expr)
	case *zeroOrOneExpr:
		val, ok = p.parseZeroOrOneExpr(expr)
	default:
		panic(fmt.Sprintf("unknown expression type %T", expr))
	}
	return val, ok
}
496911
func Tokenise(expr string) []string {

	spaced := unary_minus_rx.ReplaceAllString(expr, "$1 @")
	spaced = fp_rx.ReplaceAllString(spaced, " ${1} ")
	spaced = functions_rx.ReplaceAllString(spaced, " ${1} ")

	if symbols_rx != nil {
		spaced = symbols_rx.ReplaceAllString(spaced, " ${1} ")
	}

	symbols := []string{"(", ")"}
	for _, symbol := range symbols {
		spaced = strings.Replace(spaced, symbol, fmt.Sprintf(" %s ", symbol), -1)
	}

	stripped := whitespace_rx.ReplaceAllString(strings.TrimSpace(spaced), "|")
	result := strings.Split(stripped, "|")
	return result
}
842287
func (b ValExprBuilder) RegExp(val interface{}) BoolExprBuilder {
	return b.makeComparisonExpr(astRegExp, makeValExpr(val))
}
324652
func compileExpression(s string) (expr Expression, err error) {
	tokens := tokenize(s)
	if contains(tokens, "?") {
		return ternaryToken.compile(tokens)
	}
	return constToken.compile(tokens)
}
40319
func evalAstExpr(expr ast.ExprNode, ctx context.Context) (types.Datum, error) {
	if val, ok := expr.(*ast.ValueExpr); ok {
		return val.Datum, nil
	}
	b := &planBuilder{
		ctx:       ctx,
		allocator: new(idAllocator),
		colMapper: make(map[*ast.ColumnNameExpr]int),
	}
	if ctx.GetSessionVars().TxnCtx.InfoSchema != nil {
		b.is = ctx.GetSessionVars().TxnCtx.InfoSchema.(infoschema.InfoSchema)
	}
	newExpr, _, err := b.rewrite(expr, nil, nil, true)
	if err != nil {
		return types.Datum{}, errors.Trace(err)
	}
	return newExpr.Eval(nil, ctx)
}
1018252
func (nz *normalizer) convertComparison(node *ComparisonExpr) {
	if node.Operator != InStr && node.Operator != NotInStr {
		return
	}
	tupleVals, ok := node.Right.(ValTuple)
	if !ok {
		return
	}
	// The RHS is a tuple of values.
	// Make a list bindvar.
	bvals := &querypb.BindVariable{
		Type: querypb.Type_TUPLE,
	}
	for _, val := range tupleVals {
		bval := nz.sqlToBindvar(val)
		if bval == nil {
			return
		}
		bvals.Values = append(bvals.Values, &querypb.Value{
			Type:  bval.Type,
			Value: bval.Value,
		})
	}
	bvname := nz.newName()
	nz.bindVars[bvname] = bvals
	// Modify RHS to be a list bindvar.
	node.Right = ListArg(append([]byte("::"), bvname...))
}
1241386
func (p *parser) checkExpr(x ast.Expr) ast.Expr {
	switch t := unparen(x).(type) {
	case *ast.BadExpr:
	case *ast.Ident:
	case *ast.BasicLit:
	case *ast.FuncLit:
	case *ast.CompositeLit:
	case *ast.ParenExpr:
		panic("unreachable")
	case *ast.SelectorExpr:
	case *ast.IndexExpr:
	case *ast.SliceExpr:
	case *ast.TypeAssertExpr:
		if t.Type == nil {
			// the form X.(type) is only allowed in type switch expressions
			p.errorExpected(x.Pos(), "expression")
			x = &ast.BadExpr{x.Pos(), x.End()}
		}
	case *ast.CallExpr:
	case *ast.StarExpr:
	case *ast.UnaryExpr:
		if t.Op == token.RANGE {
			// the range operator is only allowed at the top of a for statement
			p.errorExpected(x.Pos(), "expression")
			x = &ast.BadExpr{x.Pos(), x.End()}
		}
	case *ast.BinaryExpr:
	default:
		// all other nodes are not proper expressions
		p.errorExpected(x.Pos(), "expression")
		x = &ast.BadExpr{x.Pos(), x.End()}
	}
	return x
}
321203
func Parse(e string) (*expr, string, error) {
	// skip whitespace
	for len(e) > 1 && e[0] == ' ' {
		e = e[1:]
	}

	if len(e) == 0 {
		return nil, "", ErrMissingExpr
	}

	if '0' <= e[0] && e[0] <= '9' || e[0] == '-' || e[0] == '+' {
		return parseConst(e)
	}

	if val, ok := strToBool(e); ok {
		// 'false' is 5 chars, 'true' is 4
		size := 5
		if val {
			size = 4
		}
		return &expr{bool: val, str: e[:size], etype: etBool}, e[size:], nil
	}

	if e[0] == '\'' || e[0] == '"' {
		val, e, err := parseString(e)
		return &expr{str: val, etype: etString}, e, err
	}

	name, e := parseName(e)

	if name == "" {
		return nil, e, ErrMissingArg
	}

	if e != "" && e[0] == '(' {
		for i := range name {
			if !isFnChar(name[i]) {
				return nil, "", ErrIllegalCharacter
			}
		}

		exp := &expr{str: name, etype: etFunc}

		ArgString, posArgs, namedArgs, e, err := parseArgList(e)
		exp.argsStr = ArgString
		exp.args = posArgs
		exp.namedArgs = namedArgs

		return exp, e, err
	}

	return &expr{str: name, etype: etName}, e, nil
}