// CallInternal prepends `ctx` argument and validates the return value.
//
// Note that we intentionally do not start a new stack frame to declutter stack
// traces: lucicfg.rule(...) wrapping is "transparent" from Starlark's point of
// view.
770088
func (r *ruleImpl) CallInternal(th *starlark.Thread, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
	newArgs := make(starlark.Tuple, 0, len(args)+1)
	newArgs = append(newArgs, starlarkstruct.FromStringDict(
		starlark.String("lucicfg.rule_ctx"),
		starlark.StringDict{
			"defaults": r.defaults,
		},
	))
	newArgs = append(newArgs, args...)
	switch res, err := r.Callable.CallInternal(th, newArgs, kwargs); {
	case err != nil:
		return nil, err
	case !isNamedStruct(res, "graph.keyset"):
		return nil, fmt.Errorf("bad rule implementation %s: must return graph.keyset, got %s", r.Callable, res.Type())
	default:
		return res, nil
	}
}
668778
func newRuleImpl(impl starlark.Callable, defaults *starlark.Dict) (*ruleImpl, error) {
	pairs := defaults.Items()
	for _, pair := range pairs {
		k, v := pair[0], pair[1]
		if _, ok := k.(starlark.String); !ok {
			return nil, fmt.Errorf("lucicfg.rule: keys in \"defaults\" must be strings")
		}
		if !isNamedStruct(v, "lucicfg.var") {
			return nil, fmt.Errorf("lucicfg.rule: values in \"defaults\" must be lucicfg.var")
		}
	}
	return &ruleImpl{
		Callable: impl,
		defaults: starlarkstruct.FromKeywords(starlark.String("lucicfg.rule.defaults"), pairs),
	}, nil
}
867249
func (s *InternalLBService) GetInternalLoadBalancerVMID(name string, opts ...OptionFunc) (string, int, error) {
	p := &ListInternalLoadBalancerVMsParams{}
	p.p = make(map[string]interface{})

	p.p["name"] = name

	for _, fn := range append(s.cs.options, opts...) {
		if err := fn(s.cs, p); err != nil {
			return "", -1, err
		}
	}

	l, err := s.ListInternalLoadBalancerVMs(p)
	if err != nil {
		return "", -1, err
	}

	if l.Count == 0 {
		return "", l.Count, fmt.Errorf("No match found for %s: %+v", name, l)
	}

	if l.Count == 1 {
		return l.InternalLoadBalancerVMs[0].Id, l.Count, nil
	}

	if l.Count > 1 {
		for _, v := range l.InternalLoadBalancerVMs {
			if v.Name == name {
				return v.Id, l.Count, nil
			}
		}
	}
	return "", l.Count, fmt.Errorf("Could not find an exact match for %s: %+v", name, l)
}
2233
func ErrorInternal(responseWriter http.ResponseWriter, err error) bool {
	return Error(responseWriter, http.StatusInternalServerError, err)
}
215549
func (p *parser) readInternal() *token {
	for t := range p.tokens {
		return &t
	}
	return &token{tokenEOF, "", -1}
}
542456
func (v *validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) {

BEGIN:
	switch current.Kind() {
	case reflect.Ptr:

		nullable = true

		if current.IsNil() {
			return current, reflect.Ptr, nullable
		}

		current = current.Elem()
		goto BEGIN

	case reflect.Interface:

		nullable = true

		if current.IsNil() {
			return current, reflect.Interface, nullable
		}

		current = current.Elem()
		goto BEGIN

	case reflect.Invalid:
		return current, reflect.Invalid, nullable

	default:

		if v.v.hasCustomFuncs {

			if fn, ok := v.v.customFuncs[current.Type()]; ok {
				current = reflect.ValueOf(fn(current))
				goto BEGIN
			}
		}

		return current, current.Kind(), nullable
	}
}
1182505
func (m *MonitorValues) FlattenInternetInValue() ([]FlatMonitorValue, error) {
	return m.flattenValue(func(v *MonitorValue) *float64 { return v.In })
}
1220513
func Caller(skip int) Call {
	// As of Go 1.9 we need room for up to three PC entries.
	//
	// 0. An entry for the stack frame prior to the target to check for
	//    special handling needed if that prior entry is runtime.sigpanic.
	// 1. A possible second entry to hold metadata about skipped inlined
	//    functions. If inline functions were not skipped the target frame
	//    PC will be here.
	// 2. A third entry for the target frame PC when the second entry
	//    is used for skipped inline functions.
	var pcs [3]uintptr
	n := runtime.Callers(skip+1, pcs[:])
	frames := runtime.CallersFrames(pcs[:n])
	frame, _ := frames.Next()
	frame, _ = frames.Next()

	return Call{
		frame: frame,
	}
}
908123
func NewInternalError(err error) *StatusError {
	return &StatusError{metav1.Status{
		Status: metav1.StatusFailure,
		Code:   http.StatusInternalServerError,
		Reason: metav1.StatusReasonInternalError,
		Details: &metav1.StatusDetails{
			Causes: []metav1.StatusCause{{Message: err.Error()}},
		},
		Message: fmt.Sprintf("Internal error occurred: %v", err),
	}}
}
1104601
func (s *Statement) CallFunc(f func(*Group)) *Statement {
	g := &Group{
		close:     ")",
		multi:     false,
		name:      "call",
		open:      "(",
		separator: ",",
	}
	f(g)
	*s = append(*s, g)
	return s
}
1101082
func NewInternalError(err error) error {
	return &StatusError{unversioned.Status{
		Status: unversioned.StatusFailure,
		Code:   http.StatusInternalServerError,
		Reason: unversioned.StatusReasonInternalError,
		Details: &unversioned.StatusDetails{
			Causes: []unversioned.StatusCause{{Message: err.Error()}},
		},
		Message: fmt.Sprintf("Internal error occurred: %v", err),
	}}
}
439815
func matchSimpleCall(expr syntax.Expr) (fn []string, args []syntax.Expr) {
	call, ok := expr.(*syntax.CallExpr)
	if !ok {
		return nil, nil
	}
	if fn = matchRefPath(call.Fn); len(fn) == 0 {
		return nil, nil
	}
	return fn, call.Args
}
269864
func goFunctionCall(cCtx *C.duk_context) C.duk_ret_t {
	d := contextFromPointer(cCtx)

	funPtr, ctx := d.getFunctionPtrs()
	d.transmute(unsafe.Pointer(ctx))

	result := d.fnIndex.get(funPtr)(d)

	return C.duk_ret_t(result)
}
728413
func (g *BuildGenerator) InstantiateInternal(ctx context.Context, request *buildapi.BuildRequest) (*buildapi.Build, error) {
	versionedRequest := &buildv1.BuildRequest{}
	if err := legacyscheme.Scheme.Convert(request, versionedRequest, nil); err != nil {
		return nil, fmt.Errorf("failed to convert internal BuildRequest to external: %v", err)
	}
	build, err := g.Instantiate(ctx, versionedRequest)
	if err != nil {
		return nil, err
	}
	internalBuild := &buildapi.Build{}
	if err := legacyscheme.Scheme.Convert(build, internalBuild, nil); err != nil {
		return nil, fmt.Errorf("failed to convert external Build to internal: %v", err)
	}
	return internalBuild, nil
}
303724
func (d *IGD) getInternalIP() (string, error) {
	host, _, _ := net.SplitHostPort(d.client.GetServiceClient().RootDevice.URLBase.Host)
	devIP := net.ParseIP(host)
	if devIP == nil {
		return "", errors.New("could not determine router's internal IP")
	}

	ifaces, err := net.Interfaces()
	if err != nil {
		return "", err
	}

	for _, iface := range ifaces {
		addrs, err := iface.Addrs()
		if err != nil {
			return "", err
		}

		for _, addr := range addrs {
			if x, ok := addr.(*net.IPNet); ok && x.Contains(devIP) {
				return x.IP.String(), nil
			}
		}
	}

	return "", errors.New("could not determine internal IP")
}
290548
func (inst *AsmInstruction) IsCall() bool {
	if inst.Inst == nil {
		return false
	}
	return inst.Inst.Op == x86asm.CALL || inst.Inst.Op == x86asm.LCALL
}
201671
func (v *evalVisitor) callFunc(name string, funcVal reflect.Value, options *Options) reflect.Value {
	params := options.Params()

	funcType := funcVal.Type()

	// @todo Is there a better way to do that ?
	strType := reflect.TypeOf("")
	boolType := reflect.TypeOf(true)

	// check parameters number
	addOptions := false
	numIn := funcType.NumIn()

	if numIn == len(params)+1 {
		lastArgType := funcType.In(numIn - 1)
		if reflect.TypeOf(options).AssignableTo(lastArgType) {
			addOptions = true
		}
	}

	if !addOptions && (len(params) != numIn) {
		v.errorf("Helper '%s' called with wrong number of arguments, needed %d but got %d", name, numIn, len(params))
	}

	// check and collect arguments
	args := make([]reflect.Value, numIn)
	for i, param := range params {
		arg := reflect.ValueOf(param)
		argType := funcType.In(i)

		if !arg.IsValid() {
			if canBeNil(argType) {
				arg = reflect.Zero(argType)
			} else if argType.Kind() == reflect.String {
				arg = reflect.ValueOf("")
			} else {
				// @todo Maybe we can panic on that
				return reflect.Zero(strType)
			}
		}

		if !arg.Type().AssignableTo(argType) {
			if strType.AssignableTo(argType) {
				// convert parameter to string
				arg = reflect.ValueOf(strValue(arg))
			} else if boolType.AssignableTo(argType) {
				// convert parameter to bool
				val, _ := isTrueValue(arg)
				arg = reflect.ValueOf(val)
			} else {
				v.errorf("Helper %s called with argument %d with type %s but it should be %s", name, i, arg.Type(), argType)
			}
		}

		args[i] = arg
	}

	if addOptions {
		args[numIn-1] = reflect.ValueOf(options)
	}

	result := funcVal.Call(args)

	return result[0]
}