Beispiel #1
0
func convertAndSet(to, from reflect.Value, setMethod reflect.Value) {
	var toType reflect.Type
	if setMethod.IsValid() {
		toType = setMethod.Type().In(0)
	} else {
		toType = to.Type()
	}
	fromType := from.Type()
	defer func() {
		if v := recover(); v != nil {
			panic(fmt.Sprintf("cannot use %s as a %s", fromType, toType))
		}
	}()
	if fromType == listType && toType.Kind() == reflect.Slice {
		list := from.Interface().(*List)
		from = reflect.MakeSlice(toType, len(list.data), len(list.data))
		elemType := toType.Elem()
		for i, elem := range list.data {
			from.Index(i).Set(reflect.ValueOf(elem).Convert(elemType))
		}
	} else if toType != fromType {
		from = from.Convert(toType)
	}
	if setMethod.IsValid() {
		setMethod.Call([]reflect.Value{from})
	} else {
		to.Set(from)
	}
}
Beispiel #2
0
func funcall(m reflect.Value, args []reflect.Value) (v []reflect.Value, panicked interface{}) {
	// defer func() {
	// 	panicked = recover()
	// }()
	ret := m.Call(args)
	return ret, nil
}
// Returns an endpoint that will be bound to a handler.  Internally calls the
// method endpoint
func (rm *ResourceManager) endpoint(
	res Resource, getData func(http.ResponseWriter, *http.Request) error,
	endpoint reflect.Value) http.HandlerFunc {

	callback := func(w http.ResponseWriter, r *http.Request) {

		// Call the get data function, attempting to get item and list for
		// resource if it allows
		err := getData(w, r)
		if err != nil {
			return
		}

		// Call original endpoint
		args := []reflect.Value{reflect.ValueOf(w), reflect.ValueOf(r)}
		endpoint.Call(args)
	}

	// If this resource has a wrapper around all calls to the resource
	// endpoints, then return a function that calls that wrapper.  Else,
	// just return the original call function.  Developer will have to manually
	// call the callback function in the wrapper method
	return func(w http.ResponseWriter, r *http.Request) {

		// Set the resource on the current context.
		context.Set(r, "Resource", res)

		if wrapper, ok := interface{}(res).(HandlerWrapper); ok {
			wrapper.HandlerWrapper(w, r, callback)
		} else {
			callback(w, r)
		}
	}
}
Beispiel #4
0
// callCustom calls 'custom' with sv & dv. custom must be a conversion function.
func (c *Converter) callCustom(sv, dv, custom reflect.Value, scope *scope) error {
	if !sv.CanAddr() {
		sv2 := reflect.New(sv.Type())
		sv2.Elem().Set(sv)
		sv = sv2
	} else {
		sv = sv.Addr()
	}
	if !dv.CanAddr() {
		if !dv.CanSet() {
			return scope.errorf("can't addr or set dest.")
		}
		dvOrig := dv
		dv := reflect.New(dvOrig.Type())
		defer func() { dvOrig.Set(dv) }()
	} else {
		dv = dv.Addr()
	}
	args := []reflect.Value{sv, dv, reflect.ValueOf(scope)}
	ret := custom.Call(args)[0].Interface()
	// This convolution is necessary because nil interfaces won't convert
	// to errors.
	if ret == nil {
		return nil
	}
	return ret.(error)
}
Beispiel #5
0
func eachCall(fn, v, i reflect.Value) {
	args := []reflect.Value{v}
	if in := fn.Type().NumIn(); in == 2 {
		args = append(args, i)
	}
	fn.Call(args)
}
Beispiel #6
0
Datei: exec.go Projekt: sreis/go
// evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
// it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
// as the function itself.
func (s *state) evalCall(dot, fun reflect.Value, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value {
	if args != nil {
		args = args[1:] // Zeroth arg is function name/node; not passed to function.
	}
	typ := fun.Type()
	numIn := len(args)
	if final.IsValid() {
		numIn++
	}
	numFixed := len(args)
	if typ.IsVariadic() {
		numFixed = typ.NumIn() - 1 // last arg is the variadic one.
		if numIn < numFixed {
			s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
		}
	} else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() {
		s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args))
	}
	if !goodFunc(typ) {
		// TODO: This could still be a confusing error; maybe goodFunc should provide info.
		s.errorf("can't call method/function %q with %d results", name, typ.NumOut())
	}
	// Build the arg list.
	argv := make([]reflect.Value, numIn)
	// Args must be evaluated. Fixed args first.
	i := 0
	for ; i < numFixed && i < len(args); i++ {
		argv[i] = s.evalArg(dot, typ.In(i), args[i])
	}
	// Now the ... args.
	if typ.IsVariadic() {
		argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
		for ; i < len(args); i++ {
			argv[i] = s.evalArg(dot, argType, args[i])
		}
	}
	// Add final value if necessary.
	if final.IsValid() {
		t := typ.In(typ.NumIn() - 1)
		if typ.IsVariadic() {
			if numIn-1 < numFixed {
				// The added final argument corresponds to a fixed parameter of the function.
				// Validate against the type of the actual parameter.
				t = typ.In(numIn - 1)
			} else {
				// The added final argument corresponds to the variadic part.
				// Validate against the type of the elements of the variadic slice.
				t = t.Elem()
			}
		}
		argv[i] = s.validateType(final, t)
	}
	result := fun.Call(argv)
	// If we have an error that is not nil, stop execution and return that error to the caller.
	if len(result) == 2 && !result[1].IsNil() {
		s.at(node)
		s.errorf("error calling %s: %s", name, result[1].Interface().(error))
	}
	return result[0]
}
Beispiel #7
0
func Invoke(FuncValue reflect.Value, args ...interface{}) []reflect.Value {
	in := make([]reflect.Value, len(args))
	for k, arg := range args {
		in[k] = reflect.ValueOf(arg)
	}
	return FuncValue.Call(in)
}
Beispiel #8
0
func (t TableEntry) generateIt(itBody reflect.Value) {
	if t.Pending {
		ginkgo.PIt(t.Description)
		return
	}

	values := []reflect.Value{}
	for i, param := range t.Parameters {
		var value reflect.Value

		if param == nil {
			inType := itBody.Type().In(i)
			value = reflect.Zero(inType)
		} else {
			value = reflect.ValueOf(param)
		}

		values = append(values, value)
	}

	body := func() {
		itBody.Call(values)
	}

	if t.Focused {
		ginkgo.FIt(t.Description, body)
	} else {
		ginkgo.It(t.Description, body)
	}
}
Beispiel #9
0
func funcEvaluate(L *lua.LState, fn reflect.Value) int {
	fnType := fn.Type()
	top := L.GetTop()
	expected := fnType.NumIn()
	variadic := fnType.IsVariadic()
	if !variadic && top != expected {
		L.RaiseError("invalid number of function argument (%d expected, got %d)", expected, top)
	}
	if variadic && top < expected-1 {
		L.RaiseError("invalid number of function argument (%d or more expected, got %d)", expected-1, top)
	}
	args := make([]reflect.Value, top)
	for i := 0; i < L.GetTop(); i++ {
		var hint reflect.Type
		if variadic && i >= expected-1 {
			hint = fnType.In(expected - 1).Elem()
		} else {
			hint = fnType.In(i)
		}
		args[i] = lValueToReflect(L.Get(i+1), hint)
	}
	ret := fn.Call(args)
	for _, val := range ret {
		L.Push(New(L, val.Interface()))
	}
	return len(ret)
}
Beispiel #10
0
func (t *Task) run(m reflect.Value, input Reader, output Writer) (err error) {
	collector := NewWriterCollector(output)
	colValue := reflect.ValueOf(collector)

	defer func() {
		if e := output.Close(); e != nil && err == nil {
			err = e
		}
	}()

	var k, v interface{}
	for {
		k, v, err = input.Next()
		if err != nil {
			if err == io.EOF {
				return nil
			}
			log.Printf("Read error: %s", err)
			return
		}
		m.Call([]reflect.Value{
			reflect.ValueOf(k),
			reflect.ValueOf(v),
			colValue,
		})
	}

	return
}
Beispiel #11
0
// TryCall attempts to call the task with the supplied arguments.
//
// `err` is set in the return value in two cases:
// 1. The reflected function invocation panics (e.g. due to a mismatched
//    argument list).
// 2. The task func itself returns a non-nil error.
func TryCall(f reflect.Value, args []reflect.Value, uuid reflect.Value) (results []reflect.Value, err error) {
	defer func() {
		// Recover from panic and set err.
		if e := recover(); e != nil {
			switch e := e.(type) {
			default:
				err = errors.New("Invoking task caused a panic")
			case error:
				err = e
			case string:
				err = errors.New(e)
			}
		}
	}()

	// results = f.Call(args)
	results = f.Call(append([]reflect.Value{uuid}, args...))
	// If an error was returned by the task func, propagate it
	// to the caller via err.
	if !results[1].IsNil() {
		return nil, results[1].Interface().(error)
	}

	return results, err
}
Beispiel #12
0
func shrinkOne(f reflect.Value, args []reflect.Value, ai int, shrinker Shrinker) (bool, error) {

	if shrinker == nil {
		return false, nil
	}

	for tactic := 0; tactic < MaxTactics; tactic++ {
		cur := args[ai]
		nv, err := shrinker(cur, tactic)
		if err != nil {
			switch err {
			case ErrNoMoreTactics:
				return false, nil
			case ErrDeadEnd:
				continue
			default:
				return false, err
			}
		}

		args[ai] = nv

		fret := f.Call(args)[0].Bool()
		if !fret {
			return true, nil
		}
		args[ai] = cur
	}

	return false, nil
}
Beispiel #13
0
// safelyCall invokes `function` in recover block
func (s *Server) safelyCall(function reflect.Value, args []reflect.Value) (resp []reflect.Value, e interface{}) {
	defer func() {
		if err := recover(); err != nil {
			if !s.Config.RecoverPanic {
				// go back to panic
				panic(err)
			} else {
				e = err
				resp = nil
				trace := ""
				for i := 1; ; i += 1 {
					_, file, line, ok := runtime.Caller(i)
					if !ok {
						break
					}
					if len(trace) > 1 {
						trace = trace + "\n"
					}
					trace = trace + file + ":" + strconv.Itoa(line)
				}
				s.Logger.Error("Handler crashed with error: %s\n%s", err, trace)
			}
		}
	}()
	return function.Call(args), nil
}
Beispiel #14
0
func (this *container) Exec(fv reflect.Value, args []reflect.Type) ([]reflect.Value, error) {
	if vals, err := this.getVals(args); err == nil {
		return fv.Call(vals), nil
	} else {
		return nil, err
	}
}
Beispiel #15
0
func _functionCall(fn reflect.Value, inputs ...interface{}) []reflect.Value {
	var args []reflect.Value
	for _, input := range inputs {
		args = append(args, reflect.ValueOf(input))
	}
	return fn.Call(args)
}
Beispiel #16
0
// TODO: Use gauge-go result object rather than ProtoExecutionResult
func executeFunc(fn reflect.Value, args ...interface{}) (res *m.ProtoExecutionResult) {
	rargs := make([]reflect.Value, len(args))
	for i, a := range args {
		rargs[i] = reflect.ValueOf(a)
	}
	res = &m.ProtoExecutionResult{}
	T = &testingT{}
	start := time.Now()
	defer func() {
		if r := recover(); r != nil {
			res.ScreenShot = getScreenshot()
			res.Failed = proto.Bool(true)
			res.ExecutionTime = proto.Int64(time.Since(start).Nanoseconds())
			res.StackTrace = proto.String(strings.SplitN(string(debug.Stack()), "\n", 9)[8])
			res.ErrorMessage = proto.String(fmt.Sprintf("%s", r))
		}
		T = &testingT{}
	}()
	fn.Call(rargs)
	res.Failed = proto.Bool(false)
	if len(T.errors) != 0 {
		res.ScreenShot = getScreenshot()
		res.Failed = proto.Bool(true)
		res.StackTrace = proto.String(T.getStacktraces())
		res.ErrorMessage = proto.String(T.getErrors())
	}
	res.ExecutionTime = proto.Int64(time.Since(start).Nanoseconds())
	return res
}
Beispiel #17
0
// safelyCall invokes `function` in recover block
func (a *Wrapper) SafelyCall(fn reflect.Value, args []reflect.Value) (resp []reflect.Value, err error) {
	defer func() {
		if e := recover(); e != nil {
			resp = nil
			var content string
			content = fmt.Sprintf("Handler crashed with error: %v", e)
			for i := 1; ; i += 1 {
				_, file, line, ok := runtime.Caller(i)
				if !ok {
					break
				} else {
					content += "\n"
				}
				content += fmt.Sprintf("%v %v", file, line)
			}
			a.Server.Core.Logger().Error(content)
			err = errors.New(content)
			return
		}
	}()
	if fn.Type().NumIn() > 0 {
		return fn.Call(args), err
	}
	return fn.Call(nil), err
}
Beispiel #18
0
// Invoke the given method, save headers/cookies to the response, and apply the
// result.  (e.g. render a template to the response)
func (c *Controller) Invoke(appControllerPtr reflect.Value, method reflect.Value, methodArgs []reflect.Value) {

	// Handle panics.
	defer func() {
		if err := recover(); err != nil {
			handleInvocationPanic(c, err)
		}
	}()

	// Clean up from the request.
	defer func() {
		// Delete temp files.
		if c.Request.MultipartForm != nil {
			err := c.Request.MultipartForm.RemoveAll()
			if err != nil {
				WARN.Println("Error removing temporary files:", err)
			}
		}

		for _, tmpFile := range c.Params.tmpFiles {
			err := os.Remove(tmpFile.Name())
			if err != nil {
				WARN.Println("Could not remove upload temp file:", err)
			}
		}
	}()

	// Run the plugins.
	plugins.BeforeRequest(c)

	// Calculate the Result by running the interceptors and the action.
	resultValue := func() reflect.Value {
		// Call the BEFORE interceptors
		result := c.invokeInterceptors(BEFORE, appControllerPtr)
		if result != nil {
			return reflect.ValueOf(result)
		}

		// Invoke the action.
		resultValue := method.Call(methodArgs)[0]

		// Call the AFTER interceptors
		result = c.invokeInterceptors(AFTER, appControllerPtr)
		if result != nil {
			return reflect.ValueOf(result)
		}
		return resultValue
	}()

	plugins.AfterRequest(c)

	if resultValue.IsNil() {
		return
	}
	result := resultValue.Interface().(Result)

	// Apply the result, which generally results in the ResponseWriter getting written.
	result.Apply(c.Request, c.Response)
}
Beispiel #19
0
func (this *handlerType) runRequestBusiness(target ControllerInterface, method reflect.Value, arguments []reflect.Value, basic *Basic) (result []reflect.Value) {
	defer language.Catch(func(exception language.Exception) {
		basic.Log.Error("Buiness Error Code:[%d] Message:[%s]\nStackTrace:[%s]", exception.GetCode(), exception.GetMessage(), exception.GetStackTrace())
		result = []reflect.Value{reflect.ValueOf(exception)}
	})
	result = method.Call(arguments)
	return
}
Beispiel #20
0
func _functionCallWithChanOutput(fn reflect.Value, outChan reflect.Value, inputs ...interface{}) []reflect.Value {
	var args []reflect.Value
	for _, input := range inputs {
		args = append(args, reflect.ValueOf(input))
	}
	args = append(args, outChan)
	return fn.Call(args)
}
Beispiel #21
0
// waiting for go1.1
func callableValue(fv reflect.Value) valuefun {
	if fv.Type().Kind() != reflect.Func {
		panic("not a function value")
	}
	return func(args []reflect.Value) []reflect.Value {
		return fv.Call(args)
	}
}
Beispiel #22
0
func reflectValueFromPath(root reflect.Value, path []string) (reflect.Value, error) {
	v := root

	for _, name := range path {
		var p reflect.Value
		for v.Kind() == reflect.Ptr {
			p = v
			v = v.Elem()
		}

		// Try as field first.
		var f reflect.Value
		if v.Kind() == reflect.Struct {
			f = v.FieldByName(name)
		}
		if f.IsValid() {
			v = f
		} else {
			// No field, so let's see if we got a method.
			var m reflect.Value
			if p.IsValid() {
				// Try pointer receiver first.
				m = p.MethodByName(name)
			}

			if !m.IsValid() {
				// No pointer, try directly.
				m = v.MethodByName(name)
			}
			if !m.IsValid() {
				return v, fmt.Errorf("bad member: '%s'", strings.Join(path, "."))
			}

			// We assume it takes no args and returns one mandatory value plus
			// maybe an error.
			rvs := m.Call(nil)
			switch len(rvs) {
			case 1:
				v = rvs[0]

			case 2:
				rv2 := rvs[1].Interface()
				if err, ok := rv2.(error); ok {
					return v, err
				} else if rv2 != nil {
					return v, fmt.Errorf("Second method return value must implement error.")
				}

				v = rvs[0]

			default:
				return v, fmt.Errorf("Method must return a value plus optionally an error: %s", name)
			}
		}
	}

	return v, nil
}
Beispiel #23
0
//call action
func callAction(function reflect.Value, args []reflect.Value) (result []reflect.Value, err interface{}) {
	defer func() {
		if err = recover(); err != nil {
			result = nil
		}

	}()
	return function.Call(args), nil
}
Beispiel #24
0
func callSetter(fn reflect.Value, value reflect.Value) (err error) {
	results := fn.Call([]reflect.Value{value})

	if len(results) > 0 && !results[0].IsNil() {
		err = results[0].Interface().(error)
	}

	return
}
Beispiel #25
0
func startSingleTaskInner(handler reflect.Value, handlerArgv []reflect.Value, basic *Basic) {
	defer CatchCrash(func(exception Exception) {
		basic.Log.Critical("DaemonTask Crash Code:[%d] Message:[%s]\nStackTrace:[%s]", exception.GetCode(), exception.GetMessage(), exception.GetStackTrace())
	})
	defer Catch(func(exception Exception) {
		basic.Log.Error("DaemonTask Error Code:[%d] Message:[%s]\nStackTrace:[%s]", exception.GetCode(), exception.GetMessage(), exception.GetStackTrace())
	})
	handler.Call(handlerArgv)
}
Beispiel #26
0
func RftCall(function reflect.Value, args ...reflect.Value) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = errors.New(fmt.Sprintf("RftCall panic: %+v", r))
		}
	}()
	function.Call(args)
	return
}
Beispiel #27
0
func (this *Resolver) Call(method *reflect.Value, args []reflect.Value) (response interface{}, err error) {
	output := method.Call(args)

	if (len(output) > 1) && (!output[1].IsNil()) {
		return nil, output[1].Interface().(error)
	}

	return output[0].Interface(), nil
}
Beispiel #28
0
func (b *block) call(err error, v reflect.Value) error {
	args := []reflect.Value{reflect.ValueOf(err)}
	res := v.Call(args)
	if res[0].IsNil() {
		return nil
	}

	return res[0].Interface().(error)
}
Beispiel #29
0
func callGo(L *lua.State, funv reflect.Value, args []reflect.Value) []reflect.Value {
	defer func() {
		if x := recover(); x != nil {
			RaiseError(L, sprintf("error %s", x))
		}
	}()
	resv := funv.Call(args)
	return resv
}
Beispiel #30
0
// caller converts from an actual function to a function type
// that we can construct on the fly.
func caller(f reflect.Value) func(reflect.Value) (reflect.Value, error) {
	return func(v reflect.Value) (reflect.Value, error) {
		r := f.Call([]reflect.Value{v})
		if r[1].IsNil() {
			return r[0], nil
		}
		return r[0], r[1].Interface().(error)
	}
}