// SubstituteRHS locates any SexpSelector(s) (Selector implementers, really)
// and substitutes
// the value of x.RHS() for each x in args.
499805
func (env *Zlisp) SubstituteRHS(args []Sexp) ([]Sexp, error) {
	for i := range args {
		obj, hasRhs := args[i].(Selector)
		if hasRhs {
			sx, err := obj.RHS(env)
			if err != nil {
				return args, err
			}
			args[i] = sx
		}
	}
	return args, nil
}
556718
func CompareHRS(h1 int64, r1 int, s1 cstypes.RoundStepType, h2 int64, r2 int, s2 cstypes.RoundStepType) int {
	if h1 < h2 {
		return -1
	} else if h1 > h2 {
		return 1
	}
	if r1 < r2 {
		return -1
	} else if r1 > r2 {
		return 1
	}
	if s1 < s2 {
		return -1
	} else if s1 > s2 {
		return 1
	}
	return 0
}
1049690
func substitute(src, sub, repl string) string {
	idx := strings.Index(src, sub)
	for idx >= 0 {
		src = src[:idx] + repl + src[idx+len(sub):]
		idx = strings.Index(src, sub)
	}
	return src
}
369253
func (s *VoiceMessage) SetSubstitutions(v map[string][]*string) *VoiceMessage {
	s.Substitutions = v
	return s
}
1176834
func fillHashHelper(r interface{}, depth int, env *Zlisp, preferSym bool) (Sexp, error) {
	Q("fillHashHelper() at depth %d, decoded type is %T\n", depth, r)

	// check for one of our registered structs

	// go through the type registry upfront
	for hashName, factory := range GoStructRegistry.Registry {
		//P("fillHashHelper is trying hashName='%s'", hashName)
		st, err := factory.Factory(env, nil)
		if err != nil {
			return SexpNull, err
		}
		if reflect.ValueOf(st).Type() == reflect.ValueOf(r).Type() {
			Q("we have a registered struct match for st=%T and r=%T", st, r)
			retHash, err := MakeHash([]Sexp{}, hashName, env)
			if err != nil {
				return SexpNull, fmt.Errorf("MakeHash '%s' problem: %s",
					hashName, err)
			}

			err = retHash.FillHashFromShadow(env, r)
			if err != nil {
				return SexpNull, err
			}
			Q("retHash = %#v\n", retHash)
			return retHash, nil // or return sx?
		} else {
			Q("fillHashHelper: no match for st=%T and r=%T", st, r)
		}
	}

	Q("fillHashHelper: trying basic non-struct types for r=%T", r)

	// now handle basic non struct types:
	switch val := r.(type) {
	case string:
		Q("depth %d found string case: val = %#v\n", depth, val)
		if preferSym {
			return env.MakeSymbol(val), nil
		}
		return &SexpStr{S: val}, nil

	case int:
		Q("depth %d found int case: val = %#v\n", depth, val)
		return &SexpInt{Val: int64(val)}, nil

	case int32:
		Q("depth %d found int32 case: val = %#v\n", depth, val)
		return &SexpInt{Val: int64(val)}, nil

	case int64:
		Q("depth %d found int64 case: val = %#v\n", depth, val)
		return &SexpInt{Val: int64(val)}, nil

	case float64:
		Q("depth %d found float64 case: val = %#v\n", depth, val)
		return &SexpFloat{Val: val}, nil

	case []interface{}:
		Q("depth %d found []interface{} case: val = %#v\n", depth, val)

		slice := []Sexp{}
		for i := range val {
			sx2, err := fillHashHelper(val[i], depth+1, env, preferSym)
			if err != nil {
				return SexpNull, fmt.Errorf("error in fillHashHelper() call: '%s'", err)
			}
			slice = append(slice, sx2)
		}
		return &SexpArray{Val: slice, Env: env}, nil

	case map[string]interface{}:

		Q("depth %d found map[string]interface case: val = %#v\n", depth, val)
		sortedMapKey, sortedMapVal := makeSortedSlicesFromMap(val)

		pairs := make([]Sexp, 0)

		typeName := "hash"
		var keyOrd Sexp
		foundzKeyOrder := false
		for i := range sortedMapKey {
			// special field storing the name of our record (defmap) type.
			Q("\n i=%d sortedMapVal type %T, value=%v\n", i, sortedMapVal[i], sortedMapVal[i])
			Q("\n i=%d sortedMapKey type %T, value=%v\n", i, sortedMapKey[i], sortedMapKey[i])
			if sortedMapKey[i] == "zKeyOrder" {
				keyOrd = decodeGoToSexpHelper(sortedMapVal[i], depth+1, env, true)
				foundzKeyOrder = true
			} else if sortedMapKey[i] == "Atype" {
				tn, isString := sortedMapVal[i].(string)
				if isString {
					typeName = string(tn)
				}
			} else {
				sym := env.MakeSymbol(sortedMapKey[i])
				pairs = append(pairs, sym)
				ele := decodeGoToSexpHelper(sortedMapVal[i], depth+1, env, preferSym)
				pairs = append(pairs, ele)
			}
		}
		hash, err := MakeHash(pairs, typeName, env)
		if foundzKeyOrder {
			err = SetHashKeyOrder(hash, keyOrd)
			panicOn(err)
		}
		panicOn(err)
		return hash, nil

	case []byte:
		Q("depth %d found []byte case: val = %#v\n", depth, val)

		return &SexpRaw{Val: val}, nil

	case nil:
		return SexpNull, nil

	case bool:
		return &SexpBool{Val: val}, nil

	default:
		Q("unknown type in type switch, val = %#v.  type = %T.\n", val, val)
	}

	return SexpNull, nil
}
1094661
func (t *BTree) ReplaceOrInsert(item Item) Item {
	if item == nil {
		panic("nil item being added to BTree")
	}
	if t.root == nil {
		t.root = t.cow.newNode()
		t.root.items = append(t.root.items, item)
		t.length++
		return nil
	} else {
		t.root = t.root.mutableFor(t.cow)
		if len(t.root.items) >= t.maxItems() {
			item2, second := t.root.split(t.maxItems() / 2)
			oldroot := t.root
			t.root = t.cow.newNode()
			t.root.items = append(t.root.items, item2)
			t.root.children = append(t.root.children, oldroot, second)
		}
	}
	out := t.root.insert(item, t.maxItems())
	if out == nil {
		t.length++
	}
	return out
}
1012054
func (s *EmailMessage) SetSubstitutions(v map[string][]*string) *EmailMessage {
	s.Substitutions = v
	return s
}
1253625
func SubstituteWith(template string, mapping Mapping, pattern *regexp.Regexp, subsFuncs ...SubstituteFunc) (string, error) {
	var err error
	result := pattern.ReplaceAllStringFunc(template, func(substring string) string {
		matches := pattern.FindStringSubmatch(substring)
		groups := matchGroups(matches, pattern)
		if escaped := groups["escaped"]; escaped != "" {
			return escaped
		}

		substitution := groups["named"]
		if substitution == "" {
			substitution = groups["braced"]
		}

		if substitution == "" {
			err = &InvalidTemplateError{Template: template}
			return ""
		}

		for _, f := range subsFuncs {
			var (
				value   string
				applied bool
			)
			value, applied, err = f(substitution, mapping)
			if err != nil {
				return ""
			}
			if !applied {
				continue
			}
			return value
		}

		value, _ := mapping(substitution)
		return value
	})

	return result, err
}
1145443
func Substitute(template string, mapping Mapping) (string, error) {
	return SubstituteWith(template, mapping, defaultPattern, DefaultSubstituteFuncs...)
}
9504
func SliceShrinkerOne(elementShrinker gopter.Shrinker) gopter.Shrinker {
	return func(v interface{}) gopter.Shrink {
		rv := reflect.ValueOf(v)
		if rv.Kind() != reflect.Slice {
			panic(fmt.Sprintf("%#v is not a slice", v))
		}

		shrinks := make([]gopter.Shrink, 0, rv.Len())
		for i := 0; i < rv.Len(); i++ {
			sliceShrinkOne := &sliceShrinkOne{
				original:      rv,
				index:         i,
				elementShrink: elementShrinker(rv.Index(i).Interface()),
			}
			shrinks = append(shrinks, sliceShrinkOne.Next)
		}
		return gopter.ConcatShrinks(shrinks...)
	}
}
1318189
func (r Returns) AsArgs() string {
	if len(r) == 0 {
		return ""
	}

	rets := []string{}
	for i := range r {
		rets = append(rets, r[i].Type)
	}
	return strings.Join(rets, ", ")
}
1246222
func (g *Generator) generateHrefs() (err error) {
	var (
		hrefFile string
		resWr    *ResourcesWriter
	)
	{
		hrefFile = filepath.Join(g.OutDir, "hrefs.go")
		resWr, err = NewResourcesWriter(hrefFile)
		if err != nil {
			return
		}
	}
	defer func() {
		resWr.Close()
		if err == nil {
			err = resWr.FormatCode()
		}
	}()
	title := fmt.Sprintf("%s: Application Resource Href Factories", g.API.Context())
	imports := []*codegen.ImportSpec{
		codegen.SimpleImport("fmt"),
		codegen.SimpleImport("strings"),
	}
	if err = resWr.WriteHeader(title, g.Target, imports); err != nil {
		return err
	}
	g.genfiles = append(g.genfiles, hrefFile)
	err = g.API.IterateResources(func(r *design.ResourceDefinition) error {
		m := g.API.MediaTypeWithIdentifier(r.MediaType)
		var identifier string
		if m != nil {
			identifier = m.Identifier
		} else {
			identifier = "text/plain"
		}
		data := ResourceData{
			Name:              codegen.Goify(r.Name, true),
			Identifier:        identifier,
			Description:       r.Description,
			Type:              m,
			CanonicalTemplate: codegen.CanonicalTemplate(r),
			CanonicalParams:   codegen.CanonicalParams(r),
		}
		return resWr.Execute(&data)
	})
	return
}
492723
func SubstituteCorCol2Constant(expr Expression) (Expression, error) {
	switch x := expr.(type) {
	case *ScalarFunction:
		allConstant := true
		newArgs := make([]Expression, 0, len(x.GetArgs()))
		for _, arg := range x.GetArgs() {
			newArg, err := SubstituteCorCol2Constant(arg)
			if err != nil {
				return nil, err
			}
			_, ok := newArg.(*Constant)
			newArgs = append(newArgs, newArg)
			allConstant = allConstant && ok
		}
		if allConstant {
			val, err := x.Eval(chunk.Row{})
			if err != nil {
				return nil, err
			}
			return &Constant{Value: val, RetType: x.GetType()}, nil
		}
		var newSf Expression
		if x.FuncName.L == ast.Cast {
			newSf = BuildCastFunction(x.GetCtx(), newArgs[0], x.RetType)
		} else {
			newSf = NewFunctionInternal(x.GetCtx(), x.FuncName.L, x.GetType(), newArgs...)
		}
		return newSf, nil
	case *CorrelatedColumn:
		return &Constant{Value: *x.Data, RetType: x.GetType()}, nil
	case *Constant:
		if x.DeferredExpr != nil {
			newExpr := FoldConstant(x)
			return &Constant{Value: newExpr.(*Constant).Value, RetType: x.GetType()}, nil
		}
	}
	return expr, nil
}
605317
func (j *Job) Replaces() []string {
	replaces := make([]string, 0)
	replaces = append(replaces, j.requirements()[fleetReplaces]...)
	return replaces
}
931168
func lookupFunc(name string, args int) substituteFunc {
	switch name {
	case ",":
		return toLowerFirst
	case ",,":
		return toLower
	case "^":
		return toUpperFirst
	case "^^":
		return toUpper
	case "#":
		if args == 0 {
			return toLen
		}
		return trimShortestPrefix
	case "##":
		return trimLongestPrefix
	case "%":
		return trimShortestSuffix
	case "%%":
		return trimLongestSuffix
	case ":":
		return toSubstr
	case "/#":
		return replacePrefix
	case "/%":
		return replaceSuffix
	case "/":
		return replaceFirst
	case "//":
		return replaceAll
	case "=", ":=", ":-":
		return toDefault
	case ":?", ":+", "-", "+":
		return toDefault
	default:
		return toDefault
	}
}
184646
func (bp *Bypass) Matchers() []Matcher {
	bp.mux.RLock()
	defer bp.mux.RUnlock()

	return bp.matchers
}
947405
func replacePlaceholders(str string, kv ...string) string {
	for ph, value := range toMap(kv...) {
		str = strings.Replace(str, "!!!"+ph+"!!!", value, -1)
	}
	return str
}