// Compile converts all key value pairs into a binary clauses.
// Since map iteration is non-deterministic, we'll sort the keys to
// produce repeatable SQL statements (especially for testing)
198601
func (v Values) Compile(d Dialect, params *Parameters) (string, error) {
	clauses := make([]Clause, len(v))
	for i, key := range v.Keys() {
		clauses[i] = BinaryClause{
			Pre:  ColumnClause{name: key},
			Post: &Parameter{v[key]},
			Sep:  " = ",
		}
	}
	return ArrayClause{Clauses: clauses, Sep: ", "}.Compile(d, params)
}
205775
func CompileAndExecute(path string, tree *toml.Tree) (*Result, error) {
	query, err := Compile(path)
	if err != nil {
		return nil, err
	}
	return query.Execute(tree), nil
}
28885
func (a *exprCompiler) compile(x ast.Expr, callCtx bool) *expr {
	ei := &exprInfo{a.compiler, x.Pos()}

	switch x := x.(type) {
	// Literals
	case *ast.BasicLit:
		switch x.Kind {
		case token.INT:
			return ei.compileIntLit(string(x.Value))
		case token.FLOAT:
			return ei.compileFloatLit(string(x.Value))
		case token.CHAR:
			return ei.compileCharLit(string(x.Value))
		case token.STRING:
			return ei.compileStringLit(string(x.Value))
		default:
			log.Panicf("unexpected basic literal type %v", x.Kind)
		}

	case *ast.CompositeLit:
		var ty *expr
		if x.Type != nil {
			// special case for array literal: [...]T{x,y,z}
			// we only know the number of elements here, so create the array type
			// just now.
			switch xt := x.Type.(type) {
			case *ast.ArrayType:
				if _, ok := xt.Len.(*ast.Ellipsis); ok {
					elmt_ty := a.compileType(a.block, xt.Elt)
					ty = ei.exprFromType(NewArrayType(int64(len(x.Elts)), elmt_ty))
				} else {
					ty = a.compile(x.Type, true)
				}
			default:
				ty = a.compile(x.Type, true)
			}
		}
		keys := make([]interface{}, 0, len(x.Elts))
		vals := make([]*expr, len(x.Elts))
		for i := range x.Elts {
			switch x.Elts[i].(type) {
			case *ast.KeyValueExpr:
				kv := x.Elts[i].(*ast.KeyValueExpr)
				switch kk := kv.Key.(type) {
				case *ast.Ident:
					switch x.Type.(type) {
					case *ast.Ident:
						keys = append(keys, kk.Name)
					default:
						keys = append(keys, a.compile(kv.Key, callCtx))
					}
				default:
					ekey := a.compile(kv.Key, callCtx)
					keys = append(keys, ekey)
				}
				vals[i] = a.compile(kv.Value, callCtx)
			default:
				vals[i] = a.compile(x.Elts[i], callCtx)
			}
		}
		return ei.compileCompositeLit(ty, keys, vals)

	case *ast.FuncLit:
		decl := ei.compileFuncType(a.block, x.Type)
		if decl == nil {
			// TODO(austin) Try compiling the body,
			// perhaps with dummy argument definitions
			return nil
		}
		fn := ei.compileFunc(a.block, decl, x.Body)
		if fn == nil {
			return nil
		}
		if a.constant {
			a.diagAt(x.Pos(), "function literal used in constant expression")
			return nil
		}
		return ei.compileFuncLit(decl, fn)

	// Types
	case *ast.ArrayType:
		switch x.Len.(type) {
		case *ast.Ellipsis:
			a.diagAt(x.Pos(), "array literal with ellipsis is not implemented")
			return nil
		default:
			// TODO(austin) Use a multi-type case
			goto typeexpr
		}
	case *ast.ChanType:
		goto typeexpr

	case *ast.Ellipsis:
		goto typeexpr

	case *ast.FuncType:
		goto typeexpr

	case *ast.InterfaceType:
		goto typeexpr

	case *ast.MapType:
		goto typeexpr

	// Remaining expressions
	case *ast.BadExpr:
		// Error already reported by parser
		a.silentErrors++
		return nil

	case *ast.BinaryExpr:
		l, r := a.compile(x.X, false), a.compile(x.Y, false)
		if l == nil || r == nil {
			return nil
		}
		return ei.compileBinaryExpr(x.Op, l, r)

	case *ast.CallExpr:
		l := a.compile(x.Fun, true)
		args := make([]*expr, len(x.Args))
		bad := false
		for i, arg := range x.Args {
			if i == 0 && l != nil && (l.t == Type(makeType) || l.t == Type(newType)) {
				argei := &exprInfo{a.compiler, arg.Pos()}
				args[i] = argei.exprFromType(a.compileType(a.block, arg))
			} else {
				args[i] = a.compile(arg, false)
			}
			if args[i] == nil {
				bad = true
			}
		}
		if bad || l == nil {
			return nil
		}
		if a.constant {
			a.diagAt(x.Pos(), "function call in constant context")
			return nil
		}

		if l.valType != nil {
			a.diagAt(x.Pos(), "type conversions not implemented")
			return nil
		} else if ft, ok := l.t.(*FuncType); ok && ft.builtin != "" {
			return ei.compileBuiltinCallExpr(a.block, ft, args)
		} else {
			return ei.compileCallExpr(a.block, l, args)
		}

	case *ast.Ident:
		return ei.compileIdent(a.block, a.constant, callCtx, x.Name)

	case *ast.IndexExpr:
		l, r := a.compile(x.X, false), a.compile(x.Index, false)
		if l == nil || r == nil {
			return nil
		}
		return ei.compileIndexExpr(l, r)

	case *ast.SliceExpr:
		var lo, hi *expr
		arr := a.compile(x.X, false)
		if x.Low == nil {
			// beginning was omitted, so we need to provide it
			ei := &exprInfo{a.compiler, x.Pos()}
			lo = ei.compileIntLit("0")
		} else {
			lo = a.compile(x.Low, false)
		}
		if x.High == nil {
			// End was omitted, so we need to compute len(x.X)
			ei := &exprInfo{a.compiler, x.Pos()}
			hi = ei.compileBuiltinCallExpr(a.block, lenType, []*expr{arr})
		} else {
			hi = a.compile(x.High, false)
		}
		if arr == nil || lo == nil || hi == nil {
			return nil
		}
		return ei.compileSliceExpr(arr, lo, hi)

	case *ast.KeyValueExpr:
		var key, val *expr
		key = a.compile(x.Key, true)
		val = a.compile(x.Value, true)
		if key == nil {
			a.diagAt(x.Key.Pos(), "could not compile 'key' expression")
			return nil
		}
		if val == nil {
			a.diagAt(x.Value.Pos(), "could not compile 'value' expression")
			return nil
		}
		e := ei.compileKeyValueExpr(key, val)
		return e

	case *ast.ParenExpr:
		return a.compile(x.X, callCtx)

	case *ast.SelectorExpr:
		v := a.compile(x.X, false)
		if v == nil {
			return nil
		}
		return ei.compileSelectorExpr(v, x.Sel.Name)

	case *ast.StarExpr:
		// We pass down our call context because this could be
		// a pointer type (and thus a type conversion)
		v := a.compile(x.X, callCtx)
		if v == nil {
			return nil
		}
		if v.valType != nil {
			// Turns out this was a pointer type, not a dereference
			return ei.exprFromType(NewPtrType(v.valType))
		}
		return ei.compileStarExpr(v)

	case *ast.StructType:
		goto notimpl

	case *ast.TypeAssertExpr:
		goto notimpl

	case *ast.UnaryExpr:
		v := a.compile(x.X, false)
		if v == nil {
			return nil
		}
		return ei.compileUnaryExpr(x.Op, v)
	}
	log.Panicf("unexpected ast node type %T", x)
	panic("unreachable")

typeexpr:
	if !callCtx {
		a.diagAt(x.Pos(), "type used as expression")
		return nil
	}
	return ei.exprFromType(a.compileType(a.block, x))

notimpl:
	a.diagAt(x.Pos(), "%T expression node not implemented", x)
	return nil
}
112115
func (stmt RetInsertStmt) Compile(d aspect.Dialect, params *aspect.Parameters) (string, error) {
	compiled, err := stmt.InsertStmt.Compile(d, params)
	if err != nil {
		return "", err
	}
	if len(stmt.returning) > 0 {
		compiled += fmt.Sprintf(
			" RETURNING %s",
			strings.Join(
				stmt.CompileColumns(d, params, stmt.returning),
				", ",
			),
		)
	}
	return compiled, nil
}
1054243
func (r *Render) compile() {
	for _, ts := range r.templates {
		fileList := make([]string, len(ts.fileList))
		for i, f := range ts.fileList {
			fileList[i] = path.Join(r.opt.Directory, f)
		}
		ts.template = template.New(ts.entry)
		ts.template.Delims(r.opt.Delims.Left, r.opt.Delims.Right)
		for _, funcs := range r.opt.Funcs {
			ts.template.Funcs(funcs)
		}
		ts.template = template.Must(ts.template.ParseFiles(fileList...))
	}
	log.Debugf("Templates have been compiled, count=%d", len(r.templates))
}
70210
func (self *Otto) Compile(filename string, src interface{}) (*Script, error) {
	return self.CompileWithSourceMap(filename, src, nil)
}
1256467
func Compile(pattern string, options *Options) (Glob, error) {
	pattern = strings.TrimSpace(pattern)
	reader := strings.NewReader(pattern)

	if options == nil {
		options = DefaultOptions
	} else {
		// Check that the separator is not an expander
		for _, expander := range expanders {
			if options.Separator == expander {
				return nil, fmt.Errorf("'%s' is not allowed as a separator", string(options.Separator))
			}
		}
	}

	state := &parserState{
		options:          options,
		escapedSeparator: escapeRegexComponent(string(options.Separator)),
		processedTokens:  make([]processedToken, 0, 10),
	}
	glob := &globImpl{
		Regexp:      nil,
		globPattern: pattern,
		negated:     false,
		parserState: state,
	}

	regexBuf := new(bytes.Buffer)
	if options.MatchAtStart {
		regexBuf.WriteRune('^')
	}

	var err error
	// Transform into a regular expression pattern
	// 1. Parse negation prefixes
	err = parseNegation(reader, glob)
	if err != nil {
		return nil, err
	}

	// 2. Tokenise and convert!
	tokeniser := newGlobTokeniser(reader, options)
	lastProcessedToken := &processedToken{}
	for tokeniser.Scan() {
		if err = tokeniser.Err(); err != nil {
			return nil, err
		}

		token, tokenType := tokeniser.Token()
		t := processedToken{
			contents:  nil,
			tokenType: tokenType,
		}

		// Special cases
		if tokenType == tcGlobStar && tokeniser.Peek() {
			// If this is a globstar and the next token is a separator, consume it (the globstar pattern itself includes
			// a separator)
			if err = tokeniser.PeekErr(); err != nil {
				return nil, err
			}
			_, peekedType := tokeniser.PeekToken()
			if peekedType == tcSeparator {
				tokeniser.Scan()
			}
		}
		if tokenType == tcGlobStar && lastProcessedToken.tokenType == tcGlobStar {
			// If the last token was a globstar and this is too, remove the last. We don't remove this globstar because
			// it may now be the last in the pattern, which is special
			lastProcessedToken = popLastToken(state)
		}
		if tokenType == tcGlobStar && lastProcessedToken.tokenType == tcSeparator && !tokeniser.Peek() {
			// If this is the last token, and it's a globstar, remove a preceeding separator
			lastProcessedToken = popLastToken(state)
		}

		t.contents, err = processToken(token, tokenType, glob, tokeniser)
		if err != nil {
			return nil, err
		}

		lastProcessedToken = &t
		state.processedTokens = append(state.processedTokens, t)
	}

	for _, t := range state.processedTokens {
		t.contents.WriteTo(regexBuf)
	}

	if options.MatchAtEnd {
		regexBuf.WriteRune('$')
	}

	regexString := regexBuf.String()
	Logger.Tracef("[ohmyglob:Glob] Compiled \"%s\" to regex `%s` (negated: %v)", pattern, regexString, glob.negated)
	re, err := regexp.Compile(regexString)
	if err != nil {
		return nil, err
	}

	glob.parserState = nil
	glob.Regexp = re

	return glob, nil
}
977632
func (c *Compiler) Compile() (*template.Template, error) {
	return c.CompileWithName(filepath.Base(c.filename))
}
653122
func CompileModules(modules map[string]string) (*Compiler, error) {

	parsed := make(map[string]*Module, len(modules))

	for f, module := range modules {
		if pm, err := ParseModule(f, module); err != nil {
			return nil, err
		} else if pm != nil {
			parsed[f] = pm
		}
	}

	compiler := NewCompiler()
	compiler.Compile(parsed)

	if compiler.Failed() {
		return nil, compiler.Errors
	}

	return compiler, nil
}
324652
func compileExpression(s string) (expr Expression, err error) {
	tokens := tokenize(s)
	if contains(tokens, "?") {
		return ternaryToken.compile(tokens)
	}
	return constToken.compile(tokens)
}
359987
func Compiler(c *ast.Compiler) func(r *Rego) {
	return func(r *Rego) {
		r.compiler = c
	}
}
1098351
func CompileGlob(pat string) (glob Glob, err error) {
	pat = toSlash(pat)
	s, err := translateGlob(pat)
	if err != nil {
		return
	}
	r, err := regexp.Compile(s)
	if err != nil {
		return
	}
	glob = Glob{pat, r}
	return
}
524323
func Compile(expr string) (*Expr, error) {
	if expr == "" {
		return nil, errors.New("expr expression is nil")
	}
	qy, err := build(expr)
	if err != nil {
		return nil, err
	}
	return &Expr{s: expr, q: qy}, nil
}
1123305
func (p *Parameter) Compile(d Dialect, params *Parameters) (string, error) {
	i := params.Add(p.Value)
	return d.Parameterize(i), nil
}
657302
func (stmt SelectStmt) Compile(d Dialect, params *Parameters) (string, error) {
	if err := stmt.Error(); err != nil {
		return "", err
	}

	compiled := "SELECT"

	// DISTINCT
	if stmt.isDistinct {
		compiled += " DISTINCT"
		if len(stmt.distincts) > 0 {
			distincts := make([]string, len(stmt.distincts))
			for i, column := range stmt.distincts {
				// TODO Errors!
				distincts[i], _ = column.Compile(d, params)
			}
			compiled += fmt.Sprintf(
				" ON (%s)", strings.Join(distincts, ", "),
			)
		}
	}

	compiled += fmt.Sprintf(
		" %s FROM %s",
		strings.Join(stmt.CompileColumns(d, params), ", "),
		strings.Join(stmt.CompileTables(d, params), ", "),
	)

	// JOIN ... ON ...
	if len(stmt.join) > 0 {
		for _, j := range stmt.join {
			jc, err := j.Compile(d, params)
			if err != nil {
				return "", err
			}
			compiled += jc
		}
	}

	// WHERE ...
	if stmt.cond != nil {
		cc, err := stmt.cond.Compile(d, params)
		if err != nil {
			return "", err
		}
		compiled += fmt.Sprintf(" WHERE %s", cc)
	}

	// GROUP BY ...
	if len(stmt.groupBy) > 0 {
		groupBy := make([]string, len(stmt.groupBy))
		for i, column := range stmt.groupBy {
			// TODO Errors!
			groupBy[i], _ = column.Compile(d, params)
		}
		compiled += fmt.Sprintf(" GROUP BY %s", strings.Join(groupBy, ", "))
	}

	// ORDER BY ...
	if len(stmt.order) > 0 {
		order := make([]string, len(stmt.order))
		for i, column := range stmt.order {
			// TODO Errors!
			order[i], _ = column.Compile(d, params)
		}
		compiled += fmt.Sprintf(" ORDER BY %s", strings.Join(order, ", "))
	}

	// LIMIT ...
	if stmt.limit != 0 {
		compiled += fmt.Sprintf(" LIMIT %d", stmt.limit)
	}

	// OFFSET ...
	if stmt.offset != 0 {
		compiled += fmt.Sprintf(" OFFSET %d", stmt.offset)
	}
	return compiled, nil
}
660396
func CompileGlobSet(patterns []string, options *Options) (GlobSet, error) {
	globs := make(globSetImpl, len(patterns))
	for i, pattern := range patterns {
		glob, err := Compile(pattern, options)
		if err != nil {
			return nil, err
		}
		globs[i] = glob
	}

	return globs, nil
}
987404
func compileV2Metadata(tables []TableMetadata) {
	for i := range tables {
		table := &tables[i]

		clusteringColumnCount := componentColumnCountOfType(table.Columns, ColumnClusteringKey)
		table.ClusteringColumns = make([]*ColumnMetadata, clusteringColumnCount)

		if table.KeyValidator != "" {
			keyValidatorParsed := parseType(table.KeyValidator)
			table.PartitionKey = make([]*ColumnMetadata, len(keyValidatorParsed.types))
		} else { // Cassandra 3.x+
			partitionKeyCount := componentColumnCountOfType(table.Columns, ColumnPartitionKey)
			table.PartitionKey = make([]*ColumnMetadata, partitionKeyCount)
		}

		for _, columnName := range table.OrderedColumns {
			column := table.Columns[columnName]
			if column.Kind == ColumnPartitionKey {
				table.PartitionKey[column.ComponentIndex] = column
			} else if column.Kind == ColumnClusteringKey {
				table.ClusteringColumns[column.ComponentIndex] = column
			}
		}
	}
}