Esempio n. 1
0
        public static bool ShouldWarn(PythonBinder/*!*/ binder, MethodBase/*!*/ method, out WarningInfo info) {
            Assert.NotNull(method);

            ObsoleteAttribute[] os = (ObsoleteAttribute[])method.GetCustomAttributes(typeof(ObsoleteAttribute), true);
            if (os.Length > 0) {
                info = new WarningInfo(
                    PythonExceptions.DeprecationWarning,
                    String.Format("{0}.{1} has been obsoleted.  {2}",
                        NameConverter.GetTypeName(method.DeclaringType),
                        method.Name,
                        os[0].Message
                    )
                );

                return true;
            }

            if (binder.WarnOnPython3000) {
                Python3WarningAttribute[] py3kwarnings = (Python3WarningAttribute[])method.GetCustomAttributes(typeof(Python3WarningAttribute), true);
                if (py3kwarnings.Length > 0) {
                    info = new WarningInfo(
                        PythonExceptions.DeprecationWarning,
                        py3kwarnings[0].Message
                    );

                    return true;
                }
            }

#if !SILVERLIGHT
            // no apartment states on Silverlight
            if (method.DeclaringType == typeof(Thread)) {
                if (method.Name == "Sleep") {
                    info = new WarningInfo(
                        PythonExceptions.RuntimeWarning,
                        "Calling Thread.Sleep on an STA thread doesn't pump messages.  Use Thread.CurrentThread.Join instead.",
                        Expression.Equal(
                            Expression.Call(
                                Expression.Property(
                                    null,
                                    typeof(Thread).GetProperty("CurrentThread")
                                ),
                                typeof(Thread).GetMethod("GetApartmentState")
                            ),
                            AstUtils.Constant(ApartmentState.STA)
                        ),
                        () => Thread.CurrentThread.GetApartmentState() == ApartmentState.STA
                    );

                    return true;
                }
            }
#endif

            info = null;
            return false;
        }
Esempio n. 2
0
 public string GetBaseName(MethodBase method, Func<DisplayAsAttribute, string> selectName)
 {
     var nameAttribute = method.GetCustomAttributes(typeof(DisplayAsAttribute), true);
     if(nameAttribute.Length != 0)
         return selectName(((DisplayAsAttribute)nameAttribute[0]));
     return NormalizeNamePattern.Replace(method.Name, " ");
 }
        public bool MethodShouldBeProxied(MethodBase method, IList aspects, Type baseType)
        {
            foreach (IAspect aspect in aspects)
            {
                IGenericAspect tmpAspect;
                if (aspect is IGenericAspect)
                    tmpAspect = (IGenericAspect) aspect;
                else
                    tmpAspect = TypedToGenericConverter.Convert((ITypedAspect) aspect);

                foreach (IPointcut pointcut in tmpAspect.Pointcuts)
                {
                    if (pointcut.IsMatch(method, baseType))
                        return true;
                }
            }
            foreach (FixedInterceptorAttribute fixedInterceptorAttribute in method.GetCustomAttributes(typeof(FixedInterceptorAttribute), true))
                return true;

            if (baseType != null)
            {
                foreach (FixedInterceptorAttribute fixedInterceptorAttribute in baseType.GetCustomAttributes(typeof(FixedInterceptorAttribute), true))
                    return true;
            }

            return false;
        }
Esempio n. 4
0
 private static string GetMethodName(MethodBase mb)
 {
     object[] attr = mb.GetCustomAttributes(typeof(NameSigAttribute), false);
     if (attr.Length == 1)
     {
         return(((NameSigAttribute)attr[0]).Name);
     }
     else if (mb.Name == ".ctor")
     {
         return("<init>");
     }
     else if (mb.Name == ".cctor")
     {
         return("<clinit>");
     }
     else if (mb.Name.StartsWith(NamePrefix.DefaultMethod, StringComparison.Ordinal))
     {
         return(mb.Name.Substring(NamePrefix.DefaultMethod.Length));
     }
     else if (mb.Name.StartsWith(NamePrefix.Bridge, StringComparison.Ordinal))
     {
         return(mb.Name.Substring(NamePrefix.Bridge.Length));
     }
     else if (mb.IsSpecialName)
     {
         return(UnicodeUtil.UnescapeInvalidSurrogates(mb.Name));
     }
     else
     {
         return(mb.Name);
     }
 }
Esempio n. 5
0
        private MongoSessionAttribute GetMongoSessionAttribute(MethodBase methodBase)
        {
            // �޼��忡 Ư���� �����Ǿ� �ִ��� Ȯ���Ѵ�.
            object[] attrs
                      = methodBase.GetCustomAttributes(typeof(MongoSessionAttribute), true);

            MongoSessionAttribute sessionAttribute = null;

            if (attrs != null && attrs.Length > 0)
            {
                sessionAttribute = (MongoSessionAttribute)attrs[0];
            }
            else
            {
                // Ŭ������ Ư���� �����Ǿ� �ִ��� Ȯ���Ѵ�.
                attrs = methodBase.ReflectedType.GetCustomAttributes(
                            typeof(MongoSessionAttribute), true);

                if (attrs != null && attrs.Length > 0)
                {
                    sessionAttribute = (MongoSessionAttribute)attrs[0];
                }
            }

            return sessionAttribute;
        }
		static bool WebAttributesOCEExtender (MethodBase method, object[] customAttributes, ref OperationContractAttribute oca)
		{
			int caLength = customAttributes == null ? 0 : customAttributes.Length;
			if (method == null && caLength == 0)
				return false;

			if (caLength == 0) {
				customAttributes = method.GetCustomAttributes (false);

				if (customAttributes.Length == 0)
					return false;
			}

			bool foundWebAttribute = false;
			foreach (object o in customAttributes) {
				if (o is WebInvokeAttribute || o is WebGetAttribute) {
					foundWebAttribute = true;
					break;
				}
			}

			if (!foundWebAttribute)
				return false;

			// LAMESPEC: .NET allows for contract methods decorated only with
			// Web{Get,Invoke}Attribute and _without_ the OperationContractAttribute.
			if (oca == null)
				oca = new OperationContractAttribute ();
			
			return true;
		}
        private static bool IsUnitTestMethod(MethodBase method)
        {
            // Look for NUnit [Test] attribute on method
            var testAttributes = method.GetCustomAttributes(typeof(TestAttribute), true);

            return testAttributes.Any();
        }
			GetOperationContractAttribute (MethodBase method)
		{
			object [] matts = method.GetCustomAttributes (
				typeof (OperationContractAttribute), false);
			if (matts.Length == 0)
				return null;
			return (OperationContractAttribute) matts [0];
		}
 public override bool CompileTimeValidate(MethodBase method)
 {
     return
         (method.GetCustomAttributes(typeof(CompilerGeneratedAttribute), true).Length == 0 &&
         !method.Name.StartsWith("get_") &&
         !method.Name.StartsWith("set_") &&
         !method.IsConstructor);
 }
Esempio n. 10
0
        public bool Matches(MethodBase member)
        {
            Guard.ArgumentNotNull(member, "member");

            object[] attribues = member.GetCustomAttributes(attributeType, inherited);

            return (attribues != null && attribues.Length > 0);
        }
Esempio n. 11
0
        protected void AddSnippet(ServiceOutput output, MethodBase methodBase)
        {
            if (output == null)
            {
                throw new ArgumentNullException("output");
            }

            if (methodBase == null)
            {
                throw new ArgumentNullException("methodBase");
            }

            // get the action associated with the call
            SnippetAction action = SnippetManager.Instance.Parse(HttpContext.Current.Request.Params);
            if (action.IsEnabled)
            {

                bool snippetMatch = false;

                //get the name of the snippet that needs to be loaded
                string snippetName = action.Name;

                // make sure the method can support this snippet.
                object[] attributes = methodBase.GetCustomAttributes(typeof(SupportedSnippetAttribute), false);
                foreach (object a in attributes)
                {
                    SupportedSnippetAttribute attribute = a as SupportedSnippetAttribute;
                    if (attribute != null &&
                        attribute.Name.Equals(attribute.Name, StringComparison.OrdinalIgnoreCase) )
                    {
                        snippetMatch = true;
                        break;
                    }
                }

                logger.Log(LogLevel.Debug, "SnippetName - [{0}] , Match - {1}", snippetName, snippetMatch);

                // asked snippet can be supported by the service.
                if (snippetMatch &&
                    SnippetManager.Instance.IsRegistered(snippetName))
                {
                    // load the snippet control from the location
                    Control control = FormlessPage.GetControl(SnippetManager.Instance.GetControlPath(snippetName));
                    SnippetControl snippet = control as SnippetControl;

                    if (snippet != null)
                    {
                        logger.Log(LogLevel.Debug, "Got snippet [{0}], invoking to get output.", snippetName);

                        //set the control values
                        snippet.SetProperties(action.Properties);
                        output.AddOutput(Constants.Json.Html, snippet.GetJsonHtml());
                    }
                }
            }
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="MethodMemberDescriptor"/> class.
		/// </summary>
		/// <param name="methodBase">The MethodBase (MethodInfo or ConstructorInfo) got through reflection.</param>
		/// <param name="accessMode">The interop access mode.</param>
		/// <exception cref="System.ArgumentException">Invalid accessMode</exception>
		public MethodMemberDescriptor(MethodBase methodBase, InteropAccessMode accessMode = InteropAccessMode.Default)
		{
			CheckMethodIsCompatible(methodBase, true);

			IsConstructor = (methodBase is ConstructorInfo);
			this.MethodInfo = methodBase;

			bool isStatic = methodBase.IsStatic || IsConstructor;

			if (IsConstructor)
				m_IsAction = false;
			else
				m_IsAction = ((MethodInfo)methodBase).ReturnType == typeof(void);

			ParameterInfo[] reflectionParams = methodBase.GetParameters();
			ParameterDescriptor[] parameters;
			
			if (this.MethodInfo.DeclaringType.IsArray)
			{
				m_IsArrayCtor = true;

				int rank = this.MethodInfo.DeclaringType.GetArrayRank();

				parameters = new ParameterDescriptor[rank];

				for (int i = 0; i < rank; i++)
					parameters[i] = new ParameterDescriptor("idx" + i.ToString(), typeof(int));
			}
			else
			{
				parameters = reflectionParams.Select(pi => new ParameterDescriptor(pi)).ToArray();
			}
		
			
			bool isExtensionMethod = (methodBase.IsStatic && parameters.Length > 0 && methodBase.GetCustomAttributes(typeof(ExtensionAttribute), false).Any());

			base.Initialize(methodBase.Name, isStatic, parameters, isExtensionMethod);

			// adjust access mode
			if (Script.GlobalOptions.Platform.IsRunningOnAOT())
				accessMode = InteropAccessMode.Reflection;

			if (accessMode == InteropAccessMode.Default)
				accessMode = UserData.DefaultAccessMode;

			if (accessMode == InteropAccessMode.HideMembers)
				throw new ArgumentException("Invalid accessMode");

			if (parameters.Any(p => p.Type.IsByRef))
				accessMode = InteropAccessMode.Reflection;

			this.AccessMode = accessMode;

			if (AccessMode == InteropAccessMode.Preoptimized)
				((IOptimizableDescriptor)this).Optimize();
		}
Esempio n. 13
0
 private static bool IsNative(MethodBase m)
 {
     object[] methodFlagAttribs = m.GetCustomAttributes(typeof(ModifiersAttribute), false);
     if (methodFlagAttribs.Length == 1)
     {
         ModifiersAttribute modifiersAttrib = (ModifiersAttribute)methodFlagAttribs[0];
         return((modifiersAttrib.Modifiers & Modifiers.Native) != 0);
     }
     return(false);
 }
Esempio n. 14
0
        public bool Matches(MethodBase member)
        {
            Guard.ArgumentNotNull(member, "member");

            bool hasNoPoliciesAttribute =
                (member.GetCustomAttributes(typeof(ApplyNoPoliciesAttribute), false).Length != 0);

            hasNoPoliciesAttribute |=
                (member.DeclaringType.GetCustomAttributes(typeof(ApplyNoPoliciesAttribute), false).
                    Length != 0);
            return !hasNoPoliciesAttribute;
        }
Esempio n. 15
0
        public static bool IsBoxedMath(MethodBase m)
        {
            Type t = m.DeclaringType;
            if ( t == typeof(Numbers))
            {
                object[] boxedMaths = m.GetCustomAttributes(typeof(WarnBoxedMathAttribute), true);
                if (boxedMaths.Length > 0)
                    return ((WarnBoxedMathAttribute)boxedMaths[0]).Value;

                ParameterInfo[] pis = ((MethodBase)m).GetParameters();
                foreach (ParameterInfo param in pis)
                    if (param.ParameterType.Equals(typeof(object)) )
                        return true;
            }

            return false;
        }
Esempio n. 16
0
		public static OperationContractAttribute GetOperationContractAttribute (MethodBase method)
		{
			object [] matts = method.GetCustomAttributes (typeof (OperationContractAttribute), false);
			OperationContractAttribute oca;
			
			if (matts.Length == 0)
				oca = null;
			else
				oca = matts [0] as OperationContractAttribute;

			if (getOperationContractAttributeExtenders != null && getOperationContractAttributeExtenders.Count > 0) {
				foreach (var extender in getOperationContractAttributeExtenders)
					if (extender (method, matts, ref oca))
						break;
			}

			return oca;
		}
Esempio n. 17
0
 private static string GetMethodName(MethodBase mb)
 {
     object[] attr = mb.GetCustomAttributes(typeof(NameSigAttribute), false);
     if (attr.Length == 1)
     {
         return(((NameSigAttribute)attr[0]).Name);
     }
     else if (mb.Name == ".ctor")
     {
         return("<init>");
     }
     else if (mb.Name == ".cctor")
     {
         return("<clinit>");
     }
     else
     {
         return(mb.Name);
     }
 }
Esempio n. 18
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="MethodMemberDescriptor" /> class.
        /// </summary>
        /// <param name="methodBase">The MethodBase (MethodInfo or ConstructorInfo) got through reflection.</param>
        /// <param name="accessMode">The interop access mode.</param>
        /// <exception cref="System.ArgumentException">Invalid accessMode</exception>
        public MethodMemberDescriptor(MethodBase methodBase, InteropAccessMode accessMode = InteropAccessMode.Default)
        {
            CheckMethodIsCompatible(methodBase, true);

            IsConstructor = (methodBase is ConstructorInfo);
            MethodInfo = methodBase;

            var isStatic = methodBase.IsStatic || IsConstructor;

            if (IsConstructor)
                m_IsAction = false;
            else
                m_IsAction = ((MethodInfo) methodBase).ReturnType == typeof (void);

            var reflectionParams = methodBase.GetParameters();
            var parameters = reflectionParams.Select(pi => new ParameterDescriptor(pi)).ToArray();

            var isExtensionMethod = (methodBase.IsStatic && parameters.Length > 0 &&
                                     methodBase.GetCustomAttributes(typeof (ExtensionAttribute), false).Any());

            Initialize(methodBase.Name, isStatic, parameters, isExtensionMethod);

            // adjust access mode
            if (Script.GlobalOptions.Platform.IsRunningOnAOT())
                accessMode = InteropAccessMode.Reflection;

            if (accessMode == InteropAccessMode.Default)
                accessMode = UserData.DefaultAccessMode;

            if (accessMode == InteropAccessMode.HideMembers)
                throw new ArgumentException("Invalid accessMode");

            if (parameters.Any(p => p.Type.IsByRef))
                accessMode = InteropAccessMode.Reflection;

            AccessMode = accessMode;

            if (AccessMode == InteropAccessMode.Preoptimized)
                ((IOptimizableDescriptor) this).Optimize();
        }
Esempio n. 19
0
        static string GetTestCaseName(bool fullName)
        {
            System.Diagnostics.StackTrace trace = StackTraceHelper.Create();
            var frames = trace.GetFrames();

            for (int i = 0; i < frames.Length; i++)
            {
                System.Reflection.MethodBase method = frames[i].GetMethod();
                object[] testAttrs = method.GetCustomAttributes(typeof(NUnit.Framework.TestAttribute), false).ToArray();
                if (testAttrs != null && testAttrs.Length > 0)
                {
                    if (fullName)
                    {
                        return(method.DeclaringType.FullName + "." + method.Name);
                    }
                    else
                    {
                        return(method.Name);
                    }
                }
            }
            return("GetTestCaseName[UnknownTestMethod]");
        }
Esempio n. 20
0
        /// <summary>
        /// TODO: Resolve IsPublic, IsNotPublic semantics of reflection
        /// </summary>
        /// <param name="ci"></param>
        /// <returns></returns>
        private bool OkToUseBase(MethodBase ci, out string message)
        {
            if (ci.IsAbstract)
            {
                message = "Will not use: method or constructor is abstract: " + ci.ToString();
                return false;
            }

            foreach (ParameterInfo pi in ci.GetParameters())
            {
                if (pi.ParameterType.Name.EndsWith("&"))
                {
                    message = "Will not use: method or constructor has a parameter containing \"&\": " + ci.ToString();
                    return false;
                }
                if (pi.IsOut)
                {
                    message = "Will not use: method or constructor has an out parameter: " + ci.ToString();
                    return false;
                }
                if (pi.ParameterType.IsGenericParameter)
                {
                    message = "Will not use: method or constructor has a generic parameter: " + ci.ToString();
                    return false;
                }
            }

            if (!this.useInternal && !ci.IsPublic)
            {
                message = "Will not use: method or constructor is not public: " + ci.ToString();
                return false;
            }

            if (ci.IsPrivate)
            {
                message = "Will not use: method or constructor is private: " + ci.ToString();
                return false;
            }

            if (ci.IsStatic)
            {
                if (!useStaticMethods)
                {
                    message = "Will not use: method or constructor is static: " + ci.ToString();
                    return false;
                }
            }

            if (ci.DeclaringType.Equals(typeof(object)))
            {
                message = "Will not use: method is System.Object's: " + ci.ToString();
                return false;
            }


            foreach (Attribute attr in ci.GetCustomAttributes(true))
            {

                if (attr is ObsoleteAttribute)
                {
                    //WriteLine("Obsolete Method " + ci.DeclaringType + "::" + ci.Name + "()" + "detected\n");
                    message = "Will not use: has attribute System.ObsoleteAttribute: " + ci.ToString();
                    return false;
                }
                //TODO: there are still cases where an obsolete method is not caught. e.g. System.Xml.XmlSchema::ElementType

            }

            message = "@@@OK8" + ci.ToString();
            return true;
        }
Esempio n. 21
0
        public static CheckDescription AnalyzeSignature(MethodBase method)
        {
            var result = new CheckDescription { Check = method };

            if (method.IsStatic)
            {
#if !CORE
                // check if this is an extension method
                if (method.GetCustomAttributes(typeof(ExtensionAttribute), false).Length > 0)
                {
                    var parameters = method.GetParameters();
                    var param = parameters[0];
                    var paramType = param.ParameterType;
                    if (!paramType.IsGenericType)
                    {
                        // this is not an check implementation
                        return null;
                    }

                    // if it is specific to chains
                    if (paramType.Name == "ICheckLink`1")
                    {
                        paramType = paramType.GetGenericArguments()[0];
                    }

                    if (paramType.Name == "IExtendableCheckLink`1"
                        || paramType.Name == "IExtendableCheckLink`2"
                        || paramType.Name == "ICheck`1"
                        || paramType.GetInterface("ICheck`1") != null
                        || paramType.Name == "IStructCheck`1"
                        || paramType.Name == "ICodeCheck`1")
                    {
                        result.entryPoint = paramType.Name == "IStructCheck`1" ? "ThatEnum" : "That";

                        var testedtype = paramType.GetGenericArguments()[0];
                        if (testedtype.IsGenericParameter)
                        {
                            testedtype = testedtype.BaseType;
                        }

                        result.CheckedType = testedtype;

                        // get other parameters
                        result.CheckParameters = new List<Type>(parameters.Length - 1);
                        for (var i = 1; i < parameters.Length; i++)
                        {
                            result.CheckParameters.Add(parameters[i].ParameterType);
                        }
                    }
                    else
                    {
                        // this is not an check implementation
                        return null;
                    }

                    // identify type subjected to test
                }
                else
                {
                    // unexpected case: check is a static method which is not an extension method
                    return null;
                }
            }
            else
            {
                result.entryPoint = "That";
                if (method.DeclaringType == null)
                {
                    return null;
                }

                // this is an instance method, tested type is part of type defintion
                Type scanning = method.DeclaringType.GetInterface("ICheck`1");
                if (scanning != null && scanning.IsGenericType)
                {
                    // the type implements ICheck<T>
                    result.CheckedType = scanning.IsGenericType ? scanning.GetGenericArguments()[0] : null;

                    if (result != null && result.CheckedType.IsGenericType)
                    {
                        result.CheckedType = result.CheckedType.BaseType;
                    }

                    // get other parameters
                    result.CheckParameters = new List<Type>();
                    foreach (var t in method.GetParameters())
                    {
                        result.CheckParameters.Add(t.ParameterType);
                    }
                }
                else
                {
                    // type does not implement ICheck<T>, we try to find a 'Value' property
                    var prop = method.DeclaringType.GetProperty("Value", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                    if (prop != null)
                    {
                        result.CheckedType = prop.PropertyType;

                        // get other parameters
                        result.CheckParameters = new List<Type>();
                        foreach (var t in method.GetParameters())
                        {
                            result.CheckParameters.Add(t.ParameterType);
                        }
                    }
                    else
                    {
                        // not a check method
                        Debug.WriteLine(string.Format("Type {0} needs to implement a Value property (method {1})", method.DeclaringType.Name, method.Name));
                    }
                }
#endif
            }

            return result;
        }
Esempio n. 22
0
        protected void ScanMethod(MethodBase aMethod, bool aIsPlug, string sourceItem)
        {
            var xParams = aMethod.GetParameters();
            var xParamTypes = new Type[xParams.Length];
            // Dont use foreach, enum generaly keeps order but
            // isn't guaranteed.
            //string xMethodFullName = LabelName.GenerateFullName(aMethod);


            for (int i = 0; i < xParams.Length; i++)
            {
                xParamTypes[i] = xParams[i].ParameterType;
                Queue(xParamTypes[i], aMethod, "Parameter");
            }
            var xIsDynamicMethod = aMethod.DeclaringType == null;
            // Queue Types directly related to method
            if (!aIsPlug)
            {
                // Don't queue declaring types of plugs
                if (!xIsDynamicMethod)
                {
                    // dont queue declaring types of dynamic methods either, those dont have a declaring type
                    Queue(aMethod.DeclaringType, aMethod, "Declaring Type");
                }
            }
            if (aMethod is SysReflection.MethodInfo)
            {
                Queue(((SysReflection.MethodInfo)aMethod).ReturnType, aMethod, "Return Type");
            }

            // Scan virtuals
            #region Virtuals scan
            if (!xIsDynamicMethod && aMethod.IsVirtual)
            {
                // For virtuals we need to climb up the type tree
                // and find the top base method. We then add that top
                // node to the mVirtuals list. We don't need to add the
                // types becuase adding DeclaringType will already cause
                // all ancestor types to be added.

                var xVirtMethod = aMethod;
                var xVirtType = aMethod.DeclaringType;
                MethodBase xNewVirtMethod;
                while (true)
                {
                    xVirtType = xVirtType.BaseType;
                    if (xVirtType == null)
                    {
                        // We've reached object, can't go farther
                        xNewVirtMethod = null;
                    }
                    else
                    {
                        xNewVirtMethod = xVirtType.GetMethod(aMethod.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, xParamTypes, null);
                        if (xNewVirtMethod != null)
                        {
                            if (!xNewVirtMethod.IsVirtual)
                            {
                                // This can happen if a virtual "replaces" a non virtual
                                // above it that is not virtual.
                                xNewVirtMethod = null;
                            }
                        }
                    }
                    // We dont bother to add these to Queue, because we have to do a
                    // full downlevel scan if its a new base virtual anyways.
                    if (xNewVirtMethod == null)
                    {
                        // If its already in the list, we mark it null
                        // so we dont do a full downlevel scan.
                        if (mVirtuals.Contains(xVirtMethod))
                        {
                            xVirtMethod = null;
                        }
                        break;
                    }
                    xVirtMethod = xNewVirtMethod;
                }

                // New virtual base found, we need to downscan it
                // If it was already in mVirtuals, then ScanType will take
                // care of new additions.
                if (xVirtMethod != null)
                {
                    Queue(xVirtMethod, aMethod, "Virtual Base");
                    mVirtuals.Add(xVirtMethod);

                    // List changes as we go, cant be foreach
                    for (int i = 0; i < mItemsList.Count; i++)
                    {
                        if (mItemsList[i] is Type)
                        {
                            var xType = (Type)mItemsList[i];
                            if (xType.IsSubclassOf(xVirtMethod.DeclaringType))
                            {
                                var xNewMethod = xType.GetMethod(aMethod.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, xParamTypes, null);
                                if (xNewMethod != null)
                                {
                                    // We need to check IsVirtual, a non virtual could
                                    // "replace" a virtual above it?
                                    if (xNewMethod.IsVirtual)
                                    {
                                        Queue(xNewMethod, aMethod, "Virtual Downscan");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            MethodBase xPlug = null;
            // Plugs may use plugs, but plugs won't be plugged over themself
            if (!aIsPlug && !xIsDynamicMethod)
            {
                // Check to see if method is plugged, if it is we don't scan body
                xPlug = mPlugManager.ResolvePlug(aMethod, xParamTypes);
            }

            if (xPlug == null)
            {
                bool xNeedsPlug = false;
                if ((aMethod.Attributes & MethodAttributes.PinvokeImpl) != 0)
                {
                    // pinvoke methods dont have an embedded implementation
                    xNeedsPlug = true;
                }
                else
                {
                    var xImplFlags = aMethod.GetMethodImplementationFlags();
                    // todo: prob even more
                    if ((xImplFlags & MethodImplAttributes.Native) != 0 ||
                        (xImplFlags & MethodImplAttributes.InternalCall) != 0)
                    {
                        // native implementations cannot be compiled
                        xNeedsPlug = true;
                    }
                }
                if (xNeedsPlug)
                {
                    throw new Exception("Native code encountered, plug required. Please see https://github.com/CosmosOS/Cosmos/wiki/Plugs). " + LabelName.GenerateFullName(aMethod) + "." + Environment.NewLine + " Called from :" + Environment.NewLine + sourceItem);
                }

                //TODO: As we scan each method, we could update or put in a new list
                // that has the resolved plug so we don't have to reresolve it again
                // later for compilation.

                // Scan the method body for more type and method refs
                //TODO: Dont queue new items if they are plugged
                // or do we need to queue them with a resolved ref in a new list?

                InlineAttribute inl = null;
                foreach (InlineAttribute inli in aMethod.GetCustomAttributes(typeof(InlineAttribute), false))
                {
                    inl = inli;
                }
                if (inl != null)
                    return;	// cancel inline

                List<ILOpCode> xOpCodes;
                xOpCodes = mReader.ProcessMethod(aMethod);
                if (xOpCodes != null)
                {
                    ProcessInstructions(xOpCodes);
                    foreach (var xOpCode in xOpCodes)
                    {
                        if (xOpCode is ILOpCodes.OpMethod)
                        {
                            Queue(((ILOpCodes.OpMethod)xOpCode).Value, aMethod, "Call", sourceItem);
                        }
                        else if (xOpCode is ILOpCodes.OpType)
                        {
                            Queue(((ILOpCodes.OpType)xOpCode).Value, aMethod, "OpCode Value");
                        }
                        else if (xOpCode is ILOpCodes.OpField)
                        {
                            var xOpField = (ILOpCodes.OpField)xOpCode;
                            //TODO: Need to do this? Will we get a ILOpCodes.OpType as well?
                            Queue(xOpField.Value.DeclaringType, aMethod, "OpCode Value");
                            if (xOpField.Value.IsStatic)
                            {
                                //TODO: Why do we add static fields, but not instance?
                                // AW: instance fields are "added" always, as part of a type, but for static fields, we need to emit a datamember
                                Queue(xOpField.Value, aMethod, "OpCode Value");
                            }
                        }
                        else if (xOpCode is ILOpCodes.OpToken)
                        {
                            var xTokenOp = (ILOpCodes.OpToken)xOpCode;
                            if (xTokenOp.ValueIsType)
                            {
                                Queue(xTokenOp.ValueType, aMethod, "OpCode Value");
                            }
                            if (xTokenOp.ValueIsField)
                            {
                                Queue(xTokenOp.ValueField.DeclaringType, aMethod, "OpCode Value");
                                if (xTokenOp.ValueField.IsStatic)
                                {
                                    //TODO: Why do we add static fields, but not instance?
                                    // AW: instance fields are "added" always, as part of a type, but for static fields, we need to emit a datamember
                                    Queue(xTokenOp.ValueField, aMethod, "OpCode Value");
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Gets the instance of the attribute with given type, which decorates given method on given type.
        /// </summary>
        /// <param name="targetType">Type of the target type.</param>
        /// <param name="method">The target method.</param>
        /// <param name="attributeType">Type of the attribute, which applies interceptor to a method.</param>
        /// <returns></returns>
        private static Attribute GetAttribute(Type targetType, MethodBase method, Type attributeType)
        {
            var key = GetMethodSignature(method, attributeType);
            if (SignatureCache.ContainsKey(key))
            {
                return SignatureCache[key];
            }

            var classAttributes = (from attr in targetType.GetCustomAttributes(!targetType.IsInterface)
                                   where attr.GetType() == attributeType
                                   select attr).ToList();

            if (classAttributes.Any())
            {
                var attribute = (ClassInterceptAttribute)classAttributes.First();

                if (MatchesClassAttribute(attribute, method))
                {
                    AddToSignatureCache(key, attribute);
                    return attribute;
                }
            }

            var attributes = (from attr in method.GetCustomAttributes(!targetType.IsInterface)
                             where attr.GetType() == attributeType
                             select attr).ToList();

            if (attributes.Any())
            {
                var attribute = (Attribute)attributes.First();
                AddToSignatureCache(key, attribute);
                return attribute;
            }

            AddToSignatureCache(key, null);

            return null;
        }
Esempio n. 24
0
 //Tests whether the method is marked with the given attribute.
 private bool MethodMarkedWith(MethodBase methodInfo, Type markingAttribute)
 {
     return methodInfo.GetCustomAttributes(markingAttribute,false).Length > 0;
 }
 public static bool Contains(MethodBase method)
 {
     return method.GetCustomAttributes(true).OfType<ScriptOnlyAttribute>().Any();
 }
 public CustomHandlerMethod(MethodBase aMethod, Operation anOper) : base(aMethod.GetCustomAttributes(false), aMethod.DeclaringType + "." + aMethod.Name, anOper)
 {
     base.ProcessAttrs();
 }
        /// <summary>
        /// Returns a method signature display string. Used to display stack frames.
        /// </summary>
        /// <returns>Null if the method is a compiler generated method that shouldn't be displayed to the user.</returns>
        internal virtual string FormatMethodSignature(MethodBase method)
        {
            // TODO: https://github.com/dotnet/roslyn/issues/5250

            if (method.Name.IndexOfAny(s_generatedNameChars) >= 0 ||
                method.DeclaringType.Name.IndexOfAny(s_generatedNameChars) >= 0 ||
                method.GetCustomAttributes<DebuggerHiddenAttribute>().Any() ||
                method.DeclaringType.GetTypeInfo().GetCustomAttributes<DebuggerHiddenAttribute>().Any())
            {
                return null;
            }

            return $"{method.DeclaringType.ToString()}.{method.Name}({string.Join(", ", method.GetParameters().Select(p => p.ToString()))})";
        }
        /// <summary>
        /// Matches a method with the pointuct
        /// </summary>
        /// <param name="method">The method to match</param>
        /// <param name="type"></param>
        /// <returns>True if the pointcut matched the method, otherwise false</returns>
        public bool IsAttributeMatch(MethodBase method, Type type)
        {
            Type signatureType = GetSignatureType();
            if (signatureType == null)
                return false;

            if (method.GetCustomAttributes(signatureType, true).Length > 0)
                return true;
            else
                return false;
        }
Esempio n. 29
0
		public static bool IsConditionalMethodExcluded (MethodBase mb, Location loc)
		{
			object excluded = analyzed_method_excluded [mb];
			if (excluded != null)
				return excluded == TRUE ? true : false;

			if (TypeManager.conditional_attribute_type == null)
				return false;

			ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true)
				as ConditionalAttribute[];
			if (attrs.Length == 0) {
				analyzed_method_excluded.Add (mb, FALSE);
				return false;
			}

			foreach (ConditionalAttribute a in attrs) {
				if (loc.CompilationUnit.IsConditionalDefined (a.ConditionString)) {
					analyzed_method_excluded.Add (mb, FALSE);
					return false;
				}
			}

			analyzed_method_excluded.Add (mb, TRUE);
			return true;
		}
Esempio n. 30
0
        private static void RunMethod(MethodBase specificTest, object test, FullRunDescription report, bool log)
        {
            try
            {
                specificTest.Invoke(test, new object[] { });
            }
            catch (Exception e)
            {
                if (specificTest.GetCustomAttributes(typeof(ExpectedExceptionAttribute), false).Length == 0)
                {
                    if (CheckContext.DefaulNegated == false)
                    {
                        return;
                    }

                    throw;
                }

                Type expectedType =
                    ((ExpectedExceptionAttribute)
                     specificTest.GetCustomAttributes(typeof(ExpectedExceptionAttribute), false)[0]).ExpectedException;
                if (e.InnerException != null)
                {
                    if (e.InnerException is FluentCheckException)
                    {
                        var fluExc = e.InnerException as FluentCheckException;
                        var desc = GetCheckAndType(fluExc);
                        if (desc != null)
                        {
                            var method = desc.Check;
                            var testedtype = desc.CheckedType;
                            desc.ErrorSampleMessage = fluExc.Message;

                            // are we building a report
                            if (log)
                            {
                                Log(
                                    string.Format(
                                        "Check.That({1} sut).{0} failure message\n****\n{2}\n****",
                                        method.Name,
                                        testedtype.Name,
                                        fluExc.Message));
                            }

                            if (report != null)
                            {
                                report.AddEntry(desc);
                            }

                            if (CheckContext.DefaulNegated == false)
                            {
                                Log(string.Format("(Forced) Negated test '{0}' should have succeeded, but it failed (method {1}).", specificTest.Name, desc.Signature));
                            }
                        }
                        else
                        {
                            Log(string.Format("Failed to parse the method signature {0}", specificTest.Name));
                        }

                        return;
                    }

                    if (report != null)
                    {
                        Log(
                            string.Format(
                                "{0} did not generate a fluent check:\n{1}",
                                specificTest.Name,
                                e.InnerException.Message));
                    }

                    if (e.InnerException.GetType() != expectedType && expectedType != null)
                    {
                        throw;
                    }
                }
                else
                {
                    if (report != null)
                    {
                        Log(string.Format("{0} failed to run:\n{1}", specificTest.Name, e));
                    }

                    throw;
                }
            }
        }
Esempio n. 31
0
        public static string DocOneInfo(MethodBase info, string name, bool includeSelf) {
            // Look for methods tagged with [Documentation("doc string for foo")]
            object[] attrs = info.GetCustomAttributes(typeof(DocumentationAttribute), false);
            if (attrs.Length > 0) {
                Debug.Assert(attrs.Length == 1);
                DocumentationAttribute doc = attrs[0] as DocumentationAttribute;
                return doc.Documentation;
            }

            string defaultDoc = GetDefaultDocumentation(name);
            if (defaultDoc != null) {
                return defaultDoc;
            }

            return CreateAutoDoc(info, name, 0, includeSelf);
        }
Esempio n. 32
0
		private bool IsPassContext (MethodBase method) {
				object[] method_attrs = method.GetCustomAttributes (typeof (PassContextAttribute), true);
				return (method_attrs != null && method_attrs.Length > 0);
		}
Esempio n. 33
0
        /// <summary>
        /// Gets a methods attribute.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <returns></returns>
        private Attribute GetAttribute(MethodBase method)
        {
            var key = GetMethodSignature(method);

            if(SignatureCache.ContainsKey(key)) {
                return SignatureCache[key];
            }

            var attributes = from attr in method.GetCustomAttributes(false)
                             where attr.GetType().Equals(TargetAttribute)
                             select attr;

            if(attributes.Any()) {
                var attribute = (Attribute)attributes.First();
                SignatureCache.Add(key, attribute);
                return attribute;
            }

            return null;
        }
        private static MethodMapping CreateMethodMapping(TypeMapping type, MethodBase method, int index)
        {
            var display = method.GetCustomAttributes(false).OfType<DisplayAttribute>().SingleOrDefault();

            return new MethodMapping
                       {
                           ID = Guid.NewGuid().ToString("N"),
                           Name = display == null ? method.IsConstructor ? "New" : method.Name : display.GetName(),
                           MethodName = method.Name,
                           Parameters = method.GetParameters(),
                           Index = index,
                           Type = type,
                           ReturnType = method is ConstructorInfo ? typeof(void) : ((MethodInfo)method).ReturnType,
                           UnderlineAction = method.IsConstructor ? RunningObjectsAction.Create : RunningObjectsAction.Execute,
                           Visible = !ScriptOnlyAttribute.Contains(method),
                           Method = method
                       };
        }