/// <summary>
        /// Scores the given constructor based on the number of dependencies we can fill.
        /// </summary>
        static int Rate(MethodBase constructor, TypeTracker typeTracker)
        {
            // Preserve the default behaviour of preferring explicitly marked constructors.
            if (constructor.IsDefined(typeof(InjectionConstructorAttribute), false))
                return int.MaxValue;

            var score = 0;

            foreach (var parameter in constructor.GetParameters())
            {
                if(parameter.IsOut || parameter.IsRetval)
                    return -1;

                if (typeTracker.HasDependency(parameter.ParameterType))
                {
                    score++;
                }
                else
                {
                    // We don't know how to fill this parameter so try a different constructor
                    return -1;
                }
            }

            return score;
        }
		public static bool IsOneWay(MethodBase method)
		{
			return method.IsDefined (typeof (OneWayAttribute), false);
		}
Exemple #3
0
		//
		// Imports SRE parameters
		//
		public static AParametersCollection Create (ParameterInfo [] pi, MethodBase method)
		{
			if (pi.Length == 0) {
				if (method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0)
					return new ParametersCollection (new IParameterData [0], Type.EmptyTypes, method, false);

				return Parameters.EmptyReadOnlyParameters;
			}

			Type [] types = new Type [pi.Length];
			IParameterData [] par = new IParameterData [pi.Length];
			bool is_params = false;
			for (int i = 0; i < types.Length; i++) {
				types [i] = TypeManager.TypeToCoreType (pi [i].ParameterType);

				ParameterInfo p = pi [i];
				Parameter.Modifier mod = 0;
				if (types [i].IsByRef) {
					if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
						mod = Parameter.Modifier.OUT;
					else
						mod = Parameter.Modifier.REF;

					//
					// Strip reference wrapping
					//
					types [i] = TypeManager.GetElementType (types [i]);
				} else if (i == 0 && TypeManager.extension_attribute_type != null && method != null && method.IsStatic &&
			        (method.DeclaringType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute &&
			        method.IsDefined (TypeManager.extension_attribute_type, false)) {
					mod = Parameter.Modifier.This;
				} else if (i >= pi.Length - 2 && types [i].IsArray) {
					if (p.IsDefined (TypeManager.param_array_type, false)) {
						mod = Parameter.Modifier.PARAMS;
						is_params = true;
					}
				}

				par [i] = new ParameterData (p.Name, mod);
			}

			return method != null ?
				new ParametersCollection (par, types, method, is_params) :
				new ParametersCollection (par, types);
		}
        // TODO: better filtering in DLR
        private static bool IsVisibleFrame(MethodBase/*!*/ method) {
            // filter out the _stub_ methods
            if (method.Name.StartsWith("_stub_")) {
                return false;
            }
                
            Type type = method.DeclaringType;

            if (type != null) {
                string typeName = type.FullName;
                if (typeName.StartsWith("System.Reflection.") ||
                    typeName.StartsWith("System.Runtime") ||
                    typeName.StartsWith("System.Dynamic") ||
                    typeName.StartsWith("Microsoft.Scripting")) {
                    return false;
                }

                // TODO: check loaded assemblies
                if (type.Assembly == typeof(RubyOps).Assembly) {
                    return false;
                }

                if (method.IsDefined(typeof(RubyStackTraceHiddenAttribute), false)) {
                    return false;
                }
                 
                if (type.Assembly.IsDefined(typeof(RubyLibraryAttribute), false)) {
                    return method.IsDefined(typeof(RubyMethodAttribute), false);
                }
            }
                
            return true;
        }
 public static bool IsPrerequisiteTestMethod(MethodBase method)
 {
     return method.IsDefined(typeof(PrerequisiteAttribute), false);
 }
 public static bool IsTestMethod(MethodBase method)
 {
     return method.IsDefined(typeof(TestAttribute), false);
 }
 public static bool IsExceptionResilientTestMethod(MethodBase method)
 {
     return method.IsDefined(typeof(ExceptionResilientAttribute), false);
 }
        public static string GetSignature(this MethodBase method,
                                          bool includeAccessModifiers = false,
                                          bool includeReturn          = false,
                                          bool includeDeclaringType   = true,
                                          bool useFullNames           = false,
                                          bool includeParameters      = true,
                                          bool includeParametersNames = false,
                                          Func <bool, bool, MethodBase, object, string> parametersFunction = null,
                                          object parametersFunctionArguments = null
                                          )
        {
            var res = new StringBuilder();

            // Access modifiers
            if (includeAccessModifiers)
            {
                if (method.IsPublic)
                {
                    res.Append("public ");
                }
                else if (method.IsPrivate)
                {
                    res.Append("private ");
                }
                else if (method.IsAssembly)
                {
                    res.Append("internal ");
                }
                if (method.IsFamily)
                {
                    res.Append("protected ");
                }
                if (method.IsStatic)
                {
                    res.Append("static ");
                }
                if (method.IsVirtual)
                {
                    res.Append("virtual ");
                }
                if (method.IsAbstract)
                {
                    res.Append("abstract ");
                }
            }
            // Return type
            if (includeReturn)
            {
                res.Append(((MethodInfo)method).ReturnType.GetSignature(useFullNames) + " ");
            }
            // Method name
            if (includeDeclaringType)
            {
                res.Append(method.DeclaringType.GetSignature(useFullNames) + ".");
            }
            res.Append(method.Name);
            // Generics arguments
            if (method.IsGenericMethod)
            {
                res.Append("<");
                var genericArgs = method.GetGenericArguments();
                for (var i = 0; i < genericArgs.Length; i++)
                {
                    res.Append((i > 0 ? ", " : "") + genericArgs[i].GetSignature(useFullNames));
                }
                res.Append(">");
            }
            // Parameters
            if (includeParameters)
            {
                res.Append("(");
                if (parametersFunction != null)
                {
                    res.Append(parametersFunction(useFullNames, includeParametersNames, method, parametersFunctionArguments));
                }
                else
                {
                    var pars = method.GetParameters();
                    for (var i = 0; i < pars.Length; i++)
                    {
                        var par = pars[i];
                        if (i == 0 && method.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute), false))
                        {
                            res.Append("this ");
                        }
                        if (par.ParameterType.IsByRef)
                        {
                            res.Append("ref ");
                        }
                        else if (par.IsOut)
                        {
                            res.Append("out ");
                        }
                        res.Append(par.ParameterType.GetSignature(useFullNames));
                        if (includeParametersNames)
                        {
                            res.Append(" " + par.Name);
                        }
                        if (i < pars.Length - 1)
                        {
                            res.Append(", ");
                        }
                    }
                }
                res.Append(")");
            }
            return(res.ToString());
        }
Exemple #9
0
        public void Resolve(IDictionary<Identifier, IReferencable> referencables)
        {
            if (referencables.ContainsKey(identifier))
            {
                IsResolved = true;
                IReferencable referencable = referencables[identifier];
                var method = referencable as Method;

                if (method == null)
                {
                    throw new InvalidOperationException("Cannot resolve to '" + referencable.GetType().FullName + "'");
                }

                ReturnType = method.ReturnType;

                if (ReturnType != null && !ReturnType.IsResolved)
                {
                    ReturnType.Resolve(referencables);
                }

                declaration = method.declaration;
                if (declaration != null && declaration.IsDefined(typeof (ObsoleteAttribute)))
                {
                    ObsoleteReason = declaration.GetCustomAttribute<ObsoleteAttribute>().Message;
                }

                if (!Summary.IsResolved)
                {
                    Summary.Resolve(referencables);
                }

                if (!Remarks.IsResolved)
                {
                    Remarks.Resolve(referencables);
                }

                foreach (MethodParameter para in Parameters)
                {
                    if ((para.Reference != null) && (!para.Reference.IsResolved))
                    {
                        para.Reference.Resolve(referencables);
                    }
                }
            }
            else
            {
                ConvertToExternalReference();
            }
        }
Exemple #10
0
        public static bool IsSupportedExtensionMethod(MethodBase method,Type extendedType)
        {
            if (!method.IsDefined(typeof(ExtensionAttribute), false))
                return false;
            var methodParameters = method.GetParameters();
            if (methodParameters.Length < 1)
                return false;

            var hasValidGenericParameter = false;
            for (var i = 0; i < methodParameters.Length; i++)
            {
                var parameterType = methodParameters[i].ParameterType;
                if (i == 0)
                {
                    if (parameterType.IsGenericParameter)
                    {
                        var parameterConstraints = parameterType.GetGenericParameterConstraints();
                        if (parameterConstraints.Length == 0 || !parameterConstraints[0].IsAssignableFrom(extendedType))
                            return false;
                        hasValidGenericParameter = true;
                    }
                    else if (!parameterType.IsAssignableFrom(extendedType))
                        return false;
                }
                else if (parameterType.IsGenericParameter)
                {
                    var parameterConstraints = parameterType.GetGenericParameterConstraints();
                    if (parameterConstraints.Length == 0 || !parameterConstraints[0].IsClass)
                        return false;
                    hasValidGenericParameter = true;
                }
            }
            return hasValidGenericParameter || !method.ContainsGenericParameters;
        }
        /// <summary>
        ///   Method executed when entering a test method.
        /// </summary>
        /// <param name="instance"> The instance of the context specification. </param>
        /// <param name="methodInfo"> The test method. </param>
        /// <param name="becauseAction"> The because method. </param>
        private void OnTestMethodEntry(
            IContextSpecification instance, 
            MethodBase methodInfo, 
            Action becauseAction)
        {
            var isRunningInTheContextOfAnotherTest = instance.ArePrerequisiteTestsRunning;

            if (isRunningInTheContextOfAnotherTest)
            {
                return;
            }

            var isRunningPrerequisite = methodInfo.IsDefined(typeof(PrerequisiteAttribute), true);

            becauseAction();

            if (!isRunningPrerequisite)
            {
                this.RunPrerequisiteTestsMethod();
            }
        }
Exemple #12
0
        public MethodProxy(MethodBase methodBase, object hardTarget)
        {
            this.methodBase = methodBase;
            this.hardTarget = hardTarget;

            parameters = methodBase.GetParameters();

            if (_length == null)
                _length = new Number(0) { attributes = JSObjectAttributesInternal.ReadOnly | JSObjectAttributesInternal.DoNotDelete | JSObjectAttributesInternal.DoNotEnum | JSObjectAttributesInternal.SystemObject };
            var pc = methodBase.GetCustomAttributes(typeof(Modules.ArgumentsLengthAttribute), false).ToArray();
            if (pc.Length != 0)
                _length.iValue = (pc[0] as Modules.ArgumentsLengthAttribute).Count;
            else
                _length.iValue = parameters.Length;

            for (int i = 0; i < parameters.Length; i++)
            {
                var t = parameters[i].GetCustomAttribute(typeof(Modules.ConvertValueAttribute)) as Modules.ConvertValueAttribute;
                if (t != null)
                {
                    if (paramsConverters == null)
                        paramsConverters = new Modules.ConvertValueAttribute[parameters.Length];
                    paramsConverters[i] = t;
                }
            }

            if (methodBase is MethodInfo)
            {
                var methodInfo = methodBase as MethodInfo;
                returnConverter = methodInfo.ReturnParameter.GetCustomAttribute(typeof(Modules.ConvertValueAttribute), false) as Modules.ConvertValueAttribute;

                forceInstance = methodBase.IsDefined(typeof(InstanceMemberAttribute), false);

                if (forceInstance)
                {
                    if (!methodInfo.IsStatic
                        || (parameters.Length == 0)
                        || (parameters.Length > 2)
                        || (parameters[0].ParameterType != typeof(JSObject))
                        || (parameters.Length > 1 && parameters[1].ParameterType != typeof(Arguments)))
                        throw new ArgumentException("Force-instance method \"" + methodBase + "\" have invalid signature");
                    raw = true;
                }

                if (!PartiallyTrusted
                    && !methodInfo.IsStatic
                    && (parameters.Length == 0 || (parameters.Length == 1 && parameters[0].ParameterType == typeof(Arguments)))
#if PORTABLE
 && !methodInfo.ReturnType.GetTypeInfo().IsValueType
 && !methodInfo.DeclaringType.GetTypeInfo().IsValueType)
#else
 && !methodInfo.ReturnType.IsValueType
 && !methodInfo.DeclaringType.IsValueType)
#endif
                {
                    var t = methodBase.GetCustomAttributes(typeof(AllowUnsafeCallAttribute), false).ToArray();
                    alternedTypes = new AllowUnsafeCallAttribute[t.Length];
                    for (var i = 0; i < t.Length; i++)
                        alternedTypes[i] = (AllowUnsafeCallAttribute)t[i];
                }

                #region Magic
                if (alternedTypes != null)
                {
                    if (methodInfo.ReturnType == typeof(void))
                    {
                        if (parameters.Length == 0)
                        {
#if PORTABLE
                            var methodDelegate = methodInfo.CreateDelegate(typeof(Action<>).MakeGenericType(methodBase.DeclaringType));
                            var handle = handleInfo.GetValue(methodDelegate);
                            var forceConverterConstructor = typeof(Action<object>).GetTypeInfo().DeclaredConstructors.First();
#else
                            var forceConverterConstructor = typeof(Action<object>).GetConstructors().First();
                            var handle = methodInfo.MethodHandle.GetFunctionPointer();
#endif
                            action1 = (Action<object>)forceConverterConstructor.Invoke(new object[] { null, (IntPtr)handle });
                            mode = _Mode.A1;
                        }
                        else // 1
                        {
#if PORTABLE
                            var methodDelegate = methodInfo.CreateDelegate(typeof(Action<,>).MakeGenericType(methodBase.DeclaringType, typeof(Arguments)));
                            var handle = handleInfo.GetValue(methodDelegate);
                            var forceConverterConstructor = typeof(Action<object, object>).GetTypeInfo().DeclaredConstructors.First();
#else
                            var forceConverterConstructor = typeof(Action<object, object>).GetConstructors().First();
                            var handle = methodInfo.MethodHandle.GetFunctionPointer();
#endif
                            action2 = (Action<object, object>)forceConverterConstructor.Invoke(new object[] { null, (IntPtr)handle });
                            mode = _Mode.A2;
                        }
                    }
                    else
                    {
                        if (parameters.Length == 0)
                        {
#if PORTABLE
                            var methodDelegate = methodInfo.CreateDelegate(typeof(Func<,>).MakeGenericType(methodBase.DeclaringType, methodInfo.ReturnType));
                            var handle = handleInfo.GetValue(methodDelegate);
                            var forceConverterConstructor = typeof(Func<object, object>).GetTypeInfo().DeclaredConstructors.First();
#else
                            var forceConverterConstructor = typeof(Func<object, object>).GetConstructors().First();
                            var handle = methodInfo.MethodHandle.GetFunctionPointer();
#endif
                            func1 = (Func<object, object>)forceConverterConstructor.Invoke(new object[] { getDummy(), (IntPtr)handle });
                            mode = _Mode.F1;

                        }
                        else // 1
                        {
#if PORTABLE
                            var methodDelegate = methodInfo.CreateDelegate(typeof(Func<,,>).MakeGenericType(methodBase.DeclaringType, typeof(Arguments), methodInfo.ReturnType));
                            var handle = handleInfo.GetValue(methodDelegate);
                            var forceConverterConstructor = typeof(Func<object, object, object>).GetTypeInfo().DeclaredConstructors.First();
#else
                            var forceConverterConstructor = typeof(Func<object, object, object>).GetConstructors().First();
                            var handle = methodInfo.MethodHandle.GetFunctionPointer();
#endif
                            func2 = (Func<object, object, object>)forceConverterConstructor.Invoke(new object[] { getDummy(), (IntPtr)handle });
                            mode = _Mode.F2;
                        }
                    }
                    raw = true;
                    return; // больше ничего не требуется, будет вызывать через этот путь
                }
                #endregion
#if PORTABLE
                makeMethodOverExpression(methodInfo);
#else
                makeMethodOverEmit(methodInfo);
#endif
            }
            else if (methodBase is ConstructorInfo)
            {
                makeConstructorOverExpression(methodBase as ConstructorInfo);
            }
            else
                throw new NotImplementedException();
        }
		//
		// Imports SRE parameters
		//
		public static AParametersCollection Create (ParameterInfo [] pi, MethodBase method)
		{
			int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;

			if (pi.Length == 0 && varargs == 0)
				return ParametersCompiled.EmptyReadOnlyParameters;

			Type [] types = new Type [pi.Length + varargs];
			IParameterData [] par = new IParameterData [pi.Length + varargs];
			bool is_params = false;
			PredefinedAttribute extension_attr = PredefinedAttributes.Get.Extension;
			PredefinedAttribute param_attr = PredefinedAttributes.Get.ParamArray;
			for (int i = 0; i < pi.Length; i++) {
				types [i] = TypeManager.TypeToCoreType (pi [i].ParameterType);

				ParameterInfo p = pi [i];
				Parameter.Modifier mod = 0;
				Expression default_value = null;
				if (types [i].IsByRef) {
					if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
						mod = Parameter.Modifier.OUT;
					else
						mod = Parameter.Modifier.REF;

					//
					// Strip reference wrapping
					//
					types [i] = TypeManager.GetElementType (types [i]);
				} else if (i == 0 && extension_attr.IsDefined && method != null && method.IsStatic &&
			        (method.DeclaringType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute &&
					method.IsDefined (extension_attr.Type, false)) {
					mod = Parameter.Modifier.This;
				} else {
					if (i >= pi.Length - 2 && types[i].IsArray) {
						if (p.IsDefined (param_attr.Type, false)) {
							mod = Parameter.Modifier.PARAMS;
							is_params = true;
						}
					}

					if (!is_params && p.IsOptional) {
						object value = p.DefaultValue;
						if (value == Missing.Value) {
							default_value = EmptyExpression.Null;
						} else if (value == null) {
							default_value = new NullLiteral (Location.Null);
						} else {
							default_value = Constant.CreateConstant (value.GetType (), value, Location.Null);
						}
					}
				}

				par [i] = new ParameterData (p.Name, mod, default_value);
			}

			if (varargs != 0) {
				par [par.Length - 1] = new ArglistParameter (Location.Null);
				types [types.Length - 1] = InternalType.Arglist;
			}

			return method != null ?
				new ParametersImported (par, types, varargs != 0, is_params) :
				new ParametersImported (par, types);
		}
 private static bool HasHiddenOrNonUserCodeOrInternalAttribute(MethodBase method)
 {
     return method.IsDefined(typeof(DebuggerHiddenAttribute), true)
         || method.IsDefined(typeof(DebuggerNonUserCodeAttribute), true)
         || method.IsDefined(typeof(SystemInternalAttribute), true);
 }
 public static bool IsExpectedExceptionTestMethod(MethodBase method)
 {
     return method.IsDefined(typeof(ExpectedExceptionAttribute), false);
 }
 private static bool HasTestEntryPointAttribute(MethodBase method)
 {
     return method.IsDefined(typeof(UserCodeEntryPointAttribute), true);
 }
Exemple #17
0
        //
        // Imports SRE parameters
        //
        public static AParametersCollection Create(TypeSpec parent, ParameterInfo [] pi, MethodBase method)
        {
            int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;

            if (pi.Length == 0 && varargs == 0)
                return ParametersCompiled.EmptyReadOnlyParameters;

            TypeSpec [] types = new TypeSpec [pi.Length + varargs];
            IParameterData [] par = new IParameterData [pi.Length + varargs];
            bool is_params = false;
            PredefinedAttribute extension_attr = PredefinedAttributes.Get.Extension;
            for (int i = 0; i < pi.Length; i++) {
                ParameterInfo p = pi [i];
                Parameter.Modifier mod = 0;
                Expression default_value = null;
                if (p.ParameterType.IsByRef) {
                    if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
                        mod = Parameter.Modifier.OUT;
                    else
                        mod = Parameter.Modifier.REF;

                    //
                    // Strip reference wrapping
                    //
                    types [i] = Import.ImportType (p.ParameterType.GetElementType ());
                } else if (i == 0 && method.IsStatic && parent.IsStatic &&
                    extension_attr.IsDefined && extension_attr.IsDefined && method.IsDefined (extension_attr.Type.GetMetaInfo (), false)) {
                    mod = Parameter.Modifier.This;
                    types[i] = Import.ImportType (p.ParameterType);
                } else {
                    types[i] = Import.ImportType (p.ParameterType);

                    if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
                        var cattrs = CustomAttributeData.GetCustomAttributes (p);
                        if (cattrs != null && cattrs.Any (l => l.Constructor.DeclaringType == typeof (ParamArrayAttribute))) {
                            mod = Parameter.Modifier.PARAMS;
                            is_params = true;
                        }
                    }

                    if (!is_params && p.IsOptional) {
                        object value = p.DefaultValue;
                        if (value == Missing.Value) {
                            default_value = EmptyExpression.Null;
                        } else if (value == null) {
                            default_value = new NullLiteral (Location.Null);
                        } else {
                            default_value = Constant.CreateConstant (null, Import.ImportType (value.GetType ()), value, Location.Null);
                        }
                    }
                }

                par [i] = new ParameterData (p.Name, mod, default_value);
            }

            if (varargs != 0) {
                par [par.Length - 1] = new ArglistParameter (Location.Null);
                types [types.Length - 1] = InternalType.Arglist;
            }

            return method != null ?
                new ParametersImported (par, types, varargs != 0, is_params) :
                new ParametersImported (par, types);
        }