// Rewrite rewrites the current request based upon partial match of the
// name in the question section of the request.
350239
func (rule *substringNameRule) Rewrite(ctx context.Context, state request.Request) Result {
	if strings.Contains(state.Name(), rule.Substring) {
		state.Req.Question[0].Name = strings.Replace(state.Name(), rule.Substring, rule.Replacement, -1)
		return RewriteDone
	}
	return RewriteIgnored
}
1161794
func Rewrite(rules map[string]string) echo.MiddlewareFunc {
	c := DefaultRewriteConfig
	c.Rules = rules
	return RewriteWithConfig(c)
}
1154732
func rewriteTypes(prog cc.Syntax) {
	// Assign overrides to groups.
	cc.Postorder(prog, func(x cc.Syntax) {
		if d, ok := x.(*cc.Decl); ok {
			key := declKey(d)
			t := override[key]
			if t == nil {
				return
			}
			if t.Kind == cc.Array {
				// Override only applies to specific decl. Skip for now.
				return
			}
			f := flowCache[d]
			if f == nil {
				return
			}
			g := f.group
			if g.goKind != 0 || g.goType != nil {
				fmt.Fprintf(os.Stderr, "multiple overrides: %v (%p) and %v (%p)\n", key, f.group, g.goKey, g.goFlow.group)
			}
			g.goKey = key
			g.goFlow = f
			if t.Kind <= cc.Enum {
				panic("bad go type override")
			}
			if (t.Kind == cc.Ptr || t.Kind == c2go.Slice) && t.Base == nil {
				g.goKind = t.Kind
			} else {
				g.goType = t
			}
		}
	})

	// Process overrides.
	cache := make(map[*cc.Type]*cc.Type)
	for _, g := range flowGroups {
		if g.goType != nil {
			continue
		}
		if c2go.Int8 <= g.goKind && g.goKind <= c2go.Float64 {
			g.goType = &cc.Type{Kind: g.goKind}
			continue
		}
		if g.goKind == cc.Ptr || g.goKind == c2go.Slice {
			t := g.decls[0].Type
			if t == nil || t.Base == nil {
				fmt.Printf("%s: expected ptr/array/slice for %s\n", g.decls[0].Span, declKey(g.decls[0]))
				continue
			}
			g.goType = &cc.Type{Kind: g.goKind, Base: toGoType(nil, nil, t.Base, cache)}
			continue
		}
		if g.goKind != 0 {
			fmt.Printf("%s: unexpected go kind %v\n", g.goKey, g.goKind)
			continue
		}
	}

	// Process defaults.
	// Each group has a 'canonical' instance of the type
	// that we can use as the initial hint.
	for _, g := range flowGroups {
		if g.goType != nil {
			continue
		}
		if g.canon == nil {
			fmt.Printf("group missing canonical\n")
			continue
		}
		if g.isBool {
			g.goType = boolType
			continue
		}
		t := g.canon.Def()
		if cc.Char <= t.Kind && t.Kind <= cc.Enum {
			// Convert to an appropriately sized number.
			// Canon is largest rank from C; convert to Go.
			g.goType = &cc.Type{Kind: c2goKind[t.Kind]}
			continue
		}

		if t.Kind == cc.Ptr || t.Kind == cc.Array {
			// Default is convert to pointer.
			// If there are any arrays or any pointer arithmetic, convert to slice instead.
			k := cc.Ptr
			for _, d := range g.decls {
				if d.Type != nil && d.Type.Kind == cc.Array {
					k = c2go.Slice
				}
			}
			for _, f := range g.syntax {
				if f.ptrAdd {
					k = c2go.Slice
				}
			}
			if t.Base.Kind == cc.Char {
				g.goType = &cc.Type{Kind: c2go.String}
				continue
			}
			g.goType = &cc.Type{Kind: k, Base: toGoType(nil, nil, t.Base, cache)}
			continue
		}
	}

	if *showGroups {
		fmt.Printf("%d groups\n", len(flowGroups))
		for _, g := range flowGroups {
			suffix := ""
			if g.isBool {
				suffix = " [bool]"
			}
			fmt.Printf("group(%d): %v (canon %v)%s\n", len(g.decls), c2go.GoString(g.goType), c2go.GoString(g.canon), suffix)
			for i := 0; i < 2; i++ {
				for _, f := range g.syntax {
					if d, ok := f.syntax.(*cc.Decl); ok == (i == 0) {
						suffix := ""
						if ok {
							suffix = ": " + declKey(d) + " " + c2go.GoString(d.Type)
						}
						if f.ptrAdd {
							suffix += " (ptradd)"
						}
						if f.usedAsBool {
							suffix += " (bool)"
						}
						fmt.Printf("\t%s %v%s\n", f.syntax.GetSpan(), f.syntax, suffix)
					}
				}
			}
		}
	}

	// Apply grouped decisions to individual declarations.
	cc.Postorder(prog, func(x cc.Syntax) {
		switch x := x.(type) {
		case *cc.Decl:
			d := x
			if d.Name == "..." || d.Type == nil {
				return
			}
			if d.Name == "" && d.Type.Is(cc.Enum) && len(d.Type.Decls) > 0 {
				for _, dd := range d.Type.Decls {
					dd.Type = idealType
				}
				return
			}
			t := override[declKey(d)]
			if t != nil && t.Kind == cc.Array {
				d.Type = t
				return
			}
			f := flowCache[d]
			if f == nil {
				d.Type = toGoType(nil, d, d.Type, cache)
				if declKey(d) != "tmp" {
					fprintf(d.Span, "missing flow group for %s", d.Span, declKey(d))
				}
				return
			}
			g := f.group
			if d.Init != nil && len(d.Init.Braced) > 0 && d.Type != nil && d.Type.Kind == cc.Array {
				// Initialization of array - do not override type.
				// But if size is not given explicitly, change to slice.
				d.Type.Base = toGoType(nil, nil, d.Type.Base, cache)
				if d.Type.Width == nil {
					d.Type.Kind = c2go.Slice
				}
				return
			}
			d.Type = toGoType(g, d, d.Type, cache)
			if d.Type != nil && d.Type.Kind == cc.Func && d.Type.Base.Kind != cc.Void {
				if f != nil && f.returnValue != nil && f.returnValue.group != nil && f.returnValue.group.goType != nil {
					d.Type.Base = f.returnValue.group.goType
				}
			}

		case *cc.Expr:
			if x.Type != nil {
				t := toGoType(nil, nil, x.Type, cache)
				if t == nil {
					fprintf(x.Span, "cannot convert %v to go type\n", c2go.GoString(x.Type))
				}
				x.Type = t
			}
		}
	})
}
1328725
func (r *Router) Redirect(w http.ResponseWriter, req *http.Request, path string, code int) {
	http.Redirect(w, req, r.prefix+path, code)
}
327607
func (rule *suffixTtlRule) Rewrite(ctx context.Context, state request.Request) Result {
	if strings.HasSuffix(state.Name(), rule.Suffix) {
		return RewriteDone
	}
	return RewriteIgnored
}
565432
func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
	if r.regexpType != regexpTypeHost {
		if r.regexpType == regexpTypeQuery {
			return r.matchQueryString(req)
		}
		path := req.URL.Path
		if r.options.useEncodedPath {
			path = req.URL.EscapedPath()
		}
		return r.regexp.MatchString(path)
	}

	return r.regexp.MatchString(getHost(req))
}
1335617
func (router *router) match(req *Request) (*Route, error) {
	// todo: consider using goroutines for searching for route

	method := req.Method
	path := req.URL.Path

	for _, route := range router.routes[method] {
		params, err := route.regex.Match(path)

		if err == nil {
			req.Params = params
			return &route, nil
		}
	}

	return nil, errors.New("[" + req.Method + "] handler for route " + path + " not found")
}
1339004
func RedirectHTTP(w http.ResponseWriter, r *http.Request) {
	if r.TLS != nil || r.Host == "" {
		http.Error(w, "not found", 404)
	}

	u := r.URL
	u.Host = r.Host
	u.Scheme = "https"
	http.Redirect(w, r, u.String(), 302)
}
8389
func (rule *edns0SubnetRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result {
	result := RewriteIgnored
	o := setupEdns0Opt(r)
	found := false
	for _, s := range o.Option {
		switch e := s.(type) {
		case *dns.EDNS0_SUBNET:
			if rule.action == Replace || rule.action == Set {
				if rule.fillEcsData(w, r, e) == nil {
					result = RewriteDone
				}
			}
			found = true
			break
		}
	}

	// add option if not found
	if !found && (rule.action == Append || rule.action == Set) {
		o.SetDo()
		opt := dns.EDNS0_SUBNET{Code: dns.EDNS0SUBNET}
		if rule.fillEcsData(w, r, &opt) == nil {
			o.Option = append(o.Option, &opt)
			result = RewriteDone
		}
	}

	return result
}
63748
func (rule *typeRule) Rewrite(ctx context.Context, state request.Request) Result {
	if rule.fromType > 0 && rule.toType > 0 {
		if state.QType() == rule.fromType {
			state.Req.Question[0].Qtype = rule.toType
			return RewriteDone
		}
	}
	return RewriteIgnored
}
1267072
func RewriteExpr(expr Expr, fn func(Expr) Expr) Expr {
	switch e := expr.(type) {
	case *BinaryExpr:
		e.LHS = RewriteExpr(e.LHS, fn)
		e.RHS = RewriteExpr(e.RHS, fn)
		if e.LHS != nil && e.RHS == nil {
			expr = e.LHS
		} else if e.RHS != nil && e.LHS == nil {
			expr = e.RHS
		} else if e.LHS == nil && e.RHS == nil {
			return nil
		}

	case *ParenExpr:
		e.Expr = RewriteExpr(e.Expr, fn)
		if e.Expr == nil {
			return nil
		}

	case *Call:
		for i, expr := range e.Args {
			e.Args[i] = RewriteExpr(expr, fn)
		}
	}

	return fn(expr)
}
337414
func (rule *regexNameRule) Rewrite(ctx context.Context, state request.Request) Result {
	regexGroups := rule.Pattern.FindStringSubmatch(state.Name())
	if len(regexGroups) == 0 {
		return RewriteIgnored
	}
	s := rule.Replacement
	for groupIndex, groupValue := range regexGroups {
		groupIndexStr := "{" + strconv.Itoa(groupIndex) + "}"
		if strings.Contains(s, groupIndexStr) {
			s = strings.Replace(s, groupIndexStr, groupValue, -1)
		}
	}
	state.Req.Question[0].Name = s
	return RewriteDone
}
242379
func (r ComplexRule) Rewrite(fs http.FileSystem, req *http.Request) (re Result) {
	replacer := newReplacer(req)

	// validate regexp if present
	if r.Regexp != nil {
		matches := regexpMatches(r.Regexp, r.Base, req.URL.Path)
		switch len(matches) {
		case 0:
			// no match
			return
		default:
			// set regexp match variables {1}, {2} ...

			// url escaped values of ? and #.
			q, f := url.QueryEscape("?"), url.QueryEscape("#")

			for i := 1; i < len(matches); i++ {
				// Special case of unescaped # and ? by stdlib regexp.
				// Reverse the unescape.
				if strings.ContainsAny(matches[i], "?#") {
					matches[i] = strings.NewReplacer("?", q, "#", f).Replace(matches[i])
				}

				replacer.Set(fmt.Sprint(i), matches[i])
			}
		}
	}

	// attempt rewrite
	return To(fs, req, r.To, replacer)
}
480763
func (rule PushDownRangeRule) Rewrite(node plan.Node) (plan.Node, bool, error) {
	fromNode := node.Predecessors()[0]
	fromSpec := fromNode.ProcedureSpec().(*FromProcedureSpec)

	rangeSpec := node.ProcedureSpec().(*universe.RangeProcedureSpec)
	return plan.CreatePhysicalNode("ReadRange", &ReadRangePhysSpec{
		Bucket:   fromSpec.Bucket,
		BucketID: fromSpec.BucketID,
		Bounds:   rangeSpec.Bounds,
	}), true, nil
}
242665
func (m *rewrite) rewrite() (string, error) {

	var err error

	if m.sel.Where != nil {
		m.result.Where = m.sel.Where
		m.result.Where.Expr, err = m.walkNode(m.sel.Where.Expr)
		if err != nil {
			return "", err
		}
	}

	// Evaluate the Select columns make sure we can pass them down or polyfill
	err = m.walkSelectList()
	if err != nil {
		u.Warnf("Could Not evaluate Columns/Aggs %s %v", m.sel.Columns.String(), err)
		return "", err
	}
	m.result.From = m.sel.From

	if len(m.sel.GroupBy) > 0 {
		err = m.walkGroupBy()
		if err != nil {
			u.Warnf("Could Not evaluate GroupBys %s %v", m.sel.GroupBy.String(), err)
			return "", err
		}
	}

	if len(m.sel.OrderBy) > 0 {
		// this should be same right?
		m.result.OrderBy = m.sel.OrderBy
	}

	return m.result.String(), nil
}
502544
func (r *Request) URL(uri string) *Request {
	r.URLStruct, r.Error = url.Parse(uri)
	return r
}
77382
func RewritePaths(next http.Handler, rewrites ...RewritePair) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		for _, rewrite := range rewrites {
			req.URL.Path = rewrite.Expr.ReplaceAllString(req.URL.Path, rewrite.Replacement)
		}
		next.ServeHTTP(w, req)
	})
}