Пример #1
0
        public ParameterWrapper(ActionBinder binder, ParameterInfo info)
            : this(binder, info.ParameterType) {
            _name = SymbolTable.StringToId(info.Name ?? "<unknown>");

#if FULL
            _prohibitNull = info.IsDefined(typeof(NotNullAttribute), false); 
#endif

            _isParams = info.IsDefined(typeof(ParamArrayAttribute), false);

#if FULL
            _isParamsDict = info.IsDefined(typeof(ParamDictionaryAttribute), false); 
#endif

            }
Пример #2
0
        public ParameterWrapper(ActionBinder binder, ParameterInfo info)
            : this(binder, info.ParameterType)
        {
            _name = SymbolTable.StringToId(info.Name ?? "<unknown>");

            _isParams = info.IsDefined(typeof(ParamArrayAttribute), false);
        }
Пример #3
0
        public override Expression/*!*/ ConvertExpression(Expression/*!*/ expr, ParameterInfo info, Type/*!*/ toType) {
            Type fromType = expr.Type;

            // block:
            if (fromType == typeof(MissingBlockParam)) {
                Debug.Assert(toType == typeof(BlockParam) || toType == typeof(MissingBlockParam));
                return AstUtils.Constant(null);
            }

            if (fromType == typeof(BlockParam) && toType == typeof(MissingBlockParam)) {
                return AstUtils.Constant(null);
            }

            // protocol conversions:
            if (info != null && info.IsDefined(typeof(DefaultProtocolAttribute), false)) {
                var action = RubyConversionAction.TryGetDefaultConversionAction(toType);
                if (action != null) {
                    // TODO: once we work with MetaObjects, we could inline these dynamic sites:
                    return Ast.Dynamic(action, toType, ContextExpression, expr);
                }

                throw new InvalidOperationException(String.Format("No default protocol conversion for type {0}.", toType));
            }

            return Binder.ConvertExpression(expr, toType, ConversionResultKind.ExplicitCast, ScopeExpression);
        }
Пример #4
0
		public static Parameter FromParameterInfo(ParameterInfo parameterInfo) {
			Parameter parameter = new Parameter();
			parameter._name = parameterInfo.Name;
			parameter._position = parameterInfo.Position;
			parameter._parameterType = parameterInfo.ParameterType;
			parameter._isParamArray = parameterInfo.IsDefined(typeof(ParamArrayAttribute), true);
			return parameter;
		}
        private static void BuildParameter(ParameterBuilder builder, ParameterInfo parameter)
        {
            Debug.Assert(parameter != null);
            Debug.Assert(builder != null);

            builder.Name = parameter.Name;
            builder.ParameterType = parameter.ParameterType;
            builder.Position = parameter.Position;
            builder.IsParamArray = parameter.IsDefined(typeof(ParamArrayAttribute), true);

            //
            // Build via attributes.
            //

            object[] attributes = parameter.GetCustomAttributes(typeof(IParameterReflector), true);
            foreach (IParameterReflector reflector in attributes)
                reflector.Build(builder, parameter);
        }
 public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit)
 {
     if (element == null)
     {
         throw new ArgumentNullException("element");
     }
     if (attributeType == null)
     {
         throw new ArgumentNullException("attributeType");
     }
     if (!attributeType.IsSubclassOf(typeof(Attribute)) && (attributeType != typeof(Attribute)))
     {
         throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
     }
     MemberTypes memberType = element.Member.MemberType;
     if (memberType == MemberTypes.Constructor)
     {
         return element.IsDefined(attributeType, false);
     }
     if (memberType != MemberTypes.Method)
     {
         if (memberType != MemberTypes.Property)
         {
             throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo"));
         }
         return element.IsDefined(attributeType, false);
     }
     return InternalParamIsDefined(element, attributeType, inherit);
 }
Пример #7
0
 internal ServiceDependency InstantiateDependency(ParameterInfo formalParameter, ContainerService.Builder builder)
 {
     ValueWithType actualArgument;
     if (builder.Arguments != null && builder.Arguments.TryGet(formalParameter.Name, out actualArgument))
         return containerContext.Constant(formalParameter, actualArgument.value);
     var parameters = builder.Configuration.ParametersSource;
     object actualParameter;
     if (parameters != null && parameters.TryGet(formalParameter.Name, formalParameter.ParameterType, out actualParameter))
         return containerContext.Constant(formalParameter, actualParameter);
     var dependencyConfiguration = builder.Configuration.GetOrNull(formalParameter);
     Type implementationType = null;
     if (dependencyConfiguration != null)
     {
         if (dependencyConfiguration.ValueAssigned)
             return containerContext.Constant(formalParameter, dependencyConfiguration.Value);
         if (dependencyConfiguration.Factory != null)
         {
             var dependencyBuilder = new ContainerService.Builder(new ServiceName(formalParameter.ParameterType))
             {
                 Context = builder.Context,
                 DependencyName = formalParameter.Name
             };
             builder.Context.Stack.Add(dependencyBuilder);
             dependencyBuilder.CreateInstanceBy(CallTarget.F(dependencyConfiguration.Factory), true);
             builder.Context.Stack.RemoveLast();
             return dependencyBuilder.GetService().AsDependency(containerContext, formalParameter.Name, false);
         }
         implementationType = dependencyConfiguration.ImplementationType;
     }
     implementationType = implementationType ?? formalParameter.ParameterType;
     FromResourceAttribute resourceAttribute;
     if (implementationType == typeof (Stream) && formalParameter.TryGetCustomAttribute(out resourceAttribute))
     {
         var resourceStream = builder.Type.Assembly.GetManifestResourceStream(builder.Type, resourceAttribute.Name);
         if (resourceStream == null)
             return containerContext.Error(null, formalParameter.Name,
                 "can't find resource [{0}] in namespace of [{1}], assembly [{2}]",
                 resourceAttribute.Name, builder.Type, builder.Type.Assembly.GetName().Name);
         return containerContext.Resource(formalParameter, resourceAttribute.Name, resourceStream);
     }
     var dependencyName = ServiceName.Parse(implementationType.UnwrapEnumerable(),
         InternalHelpers.ParseContracts(formalParameter));
     if (dependencyName.Type.IsSimpleType())
     {
         if (!formalParameter.HasDefaultValue)
             return containerContext.Error(null, formalParameter.Name,
                 "parameter [{0}] of service [{1}] is not configured",
                 formalParameter.Name, builder.Type.FormatName());
         return containerContext.Constant(formalParameter, formalParameter.DefaultValue);
     }
     var resultService = ResolveCore(dependencyName, false, null, builder.Context);
     if (resultService.Status.IsBad())
         return containerContext.ServiceError(resultService);
     var isEnumerable = dependencyName.Type != implementationType;
     if (isEnumerable)
         return containerContext.Service(resultService, resultService.GetAllValues());
     if (resultService.Status == ServiceStatus.NotResolved)
     {
         if (formalParameter.HasDefaultValue)
             return containerContext.Service(resultService, formalParameter.DefaultValue);
         if (formalParameter.IsDefined<OptionalAttribute>() || formalParameter.IsDefined("CanBeNullAttribute"))
             return containerContext.Service(resultService, null);
         return containerContext.NotResolved(resultService);
     }
     return resultService.AsDependency(containerContext, null, false);
 }
Пример #8
0
 /// <summary>
 /// 如果给定的参数信息是 params 参数,则返回对应的数组元素类型;否则为 <c>null</c>。
 /// </summary>
 /// <param name="parameter">参数信息。</param>
 /// <returns>params 参数的元素类型。</returns>
 internal static Type GetParamArrayType(ParameterInfo parameter)
 {
     if (parameter.ParameterType.IsArray && parameter.IsDefined(typeof(ParamArrayAttribute), true))
     {
         return parameter.ParameterType.GetElementType();
     }
     return null;
 }
 private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit)
 {
     if (param.IsDefined(type, false))
     {
         return true;
     }
     if ((param.Member.DeclaringType != null) && inherit)
     {
         for (ParameterInfo info = GetParentDefinition(param); info != null; info = GetParentDefinition(info))
         {
             object[] customAttributes = info.GetCustomAttributes(type, false);
             for (int i = 0; i < customAttributes.Length; i++)
             {
                 AttributeUsageAttribute attributeUsage = InternalGetAttributeUsage(customAttributes[i].GetType());
                 if ((customAttributes[i] is Attribute) && attributeUsage.Inherited)
                 {
                     return true;
                 }
             }
         }
     }
     return false;
 }
Пример #10
0
        public static void CopyParameterAttributes(ParameterInfo from, ParameterBuilder to) {
            if (from.IsDefined(typeof(ParamArrayAttribute), false)) {
                to.SetCustomAttribute(new CustomAttributeBuilder(
                    typeof(ParamArrayAttribute).GetConstructor(Type.EmptyTypes), ArrayUtils.EmptyObjects)
                );
            } else if (from.IsDefined(typeof(ParamDictionaryAttribute), false)) {
                to.SetCustomAttribute(new CustomAttributeBuilder(
                    typeof(ParamDictionaryAttribute).GetConstructor(Type.EmptyTypes), ArrayUtils.EmptyObjects)
                );
            }

            if ((from.Attributes & ParameterAttributes.HasDefault) != 0) {
                to.SetConstant(from.DefaultValue);
            }
        }
Пример #11
0
        private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit)
        {
            Contract.Requires(param != null);
            Contract.Requires(type != null);

            // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain.
            // We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes 
            // that are marked inherited from the remainder of the ParameterInfo's in the inheritance chain.
            // For MethodInfo's on an interface we do not do an inheritance walk. For ParameterInfo's on a
            // Class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the class inherits from.

            if (param.IsDefined(type, false))
                return true;
            
            if (param.Member.DeclaringType == null || !inherit) // This is an interface so we are done.
                return false;

            ParameterInfo baseParam = GetParentDefinition(param);

            while (baseParam != null)
            {
                Object[] objAttr = baseParam.GetCustomAttributes(type, false); 
                                
                for (int i =0; i < objAttr.Length; i++)
                {
                    Type objType = objAttr[i].GetType();
                    AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);

                    if ((objAttr[i] is Attribute) && (attribUsage.Inherited))
                        return true;
                }

                baseParam = GetParentDefinition(baseParam);
            } 

            return false;
        }
 /// <summary>
 /// Determine whether any data is available for a parameter.
 /// </summary>
 /// <param name="parameter">A ParameterInfo representing one
 /// argument to a parameterized test</param>
 /// <returns>
 /// True if any data is available, otherwise false.
 /// </returns>
 public bool HasDataFor(ParameterInfo parameter)
 {
     return parameter.IsDefined(typeof(DataAttribute), false);
 }
 internal static bool IsDefined(ParameterInfo target, Type caType, bool inherit) {
   // JScript implements subclasses of ParameterInfo which throw an exception when Module is
   // accessed. We know that none of these are from a ReflectionOnly assembly.
   Type t = target.GetType();
   if (t.Assembly == typeof(CustomAttribute).Assembly || !target.Member.Module.Assembly.ReflectionOnly)
     return target.IsDefined(caType, inherit);
   return CustomAttribute.CheckForCustomAttribute(CustomAttributeData.GetCustomAttributes(target), caType);
 }
Пример #14
0
        internal static void BuildParameter(ParameterBuilder builder, ParameterInfo parameter)
        {
            Debug.Assert(parameter != null);
            Debug.Assert(builder != null);

            //
            // Build...
            //

            builder.Name = parameter.Name;
            builder.ParameterType = parameter.ParameterType;
            builder.IsParamArray = parameter.IsDefined(typeof(ParamArrayAttribute), true);

            //
            // Modify...
            //

            object[] modifiers = GetCustomAttributes(parameter, typeof(IParameterModifier), true);
            foreach (IParameterModifier modifier in modifiers)
                modifier.Modify(builder);
        }
Пример #15
0
 public static bool IsParamDictionary(ParameterInfo parameter) {
     return parameter.IsDefined(typeof(ParamDictionaryAttribute), false);
 }
Пример #16
0
		/// <summary>
		/// Emits code converting argument on the evaluation stack to a specified type using PHP.NET library conversions. 
		/// Used for conversion of elements of params array optional arguments,
		/// for conversion of a content of mandatory by-ref holder, and
		/// for conversion of mandatory in argument.
		/// </summary>
		/// <param name="dstType">
		/// The type of the formal argument. Shouldn't be <see cref="Type.IsByRef"/>.
		/// </param>
		/// <param name="srcTypeOrValue">
		/// The type of the formal argument or its value if it is a literal.
		/// </param>
		/// <param name="allowImplicitCast">Whether to allow implicit cast of types PhpArray, PhpObject, PhpResource.</param>
		/// <param name="param">The formal argument description.</param>
        /// <param name="additionalValuesOnStackCount">Amount of values pushed on stackl, that have to be cleaned up in case of failed conversion.</param>
		internal void EmitArgumentConversion(Type dstType, object srcTypeOrValue, bool allowImplicitCast, ParameterInfo param, int additionalValuesOnStackCount = 0)
		{
			Debug.Assert(!dstType.IsByRef);

			Type src_type = srcTypeOrValue as Type;

			// passing void parameter is the same as passing null reference:
			if (src_type == Types.Void)
			{
				srcTypeOrValue = null;
				src_type = null;
			}

			// unites treatment of enums and ints:
			if (src_type != null && src_type.IsEnum) src_type = typeof(int);
			if (dstType.IsEnum) dstType = typeof(int);

			// no conversions needed:
			if (dstType == src_type)
			{
				// deep copy if needed (doesn't produce unnecessary copying):
				if (param.IsDefined(typeof(PhpDeepCopyAttribute), false))
				{
					// CALL (<dstType>)PhpVariable.Copy(STACK,CopyReason.PassedByCopy);
					il.LdcI4((int)CopyReason.PassedByCopy);
					il.Emit(OpCodes.Call, Methods.PhpVariable.Copy);

					if (dstType != typeof(object))
						il.Emit(OpCodes.Castclass, dstType);
				}
				return;
			}

			// if dst type is reference then src type should be also a reference 
			// (reference - reference combination was eliminated in previous statement):
			Debug.Assert(dstType != typeof(PhpReference), "Formal type cannot be reference if actual is not.");

			// dereferences a reference:
			if (src_type == typeof(PhpReference))
			{
				il.Emit(OpCodes.Ldfld, Fields.PhpReference_Value);
				src_type = typeof(object);
			}

			#region dst is integer, long integer, bool, double, string, PhpBytes, char

			// to integer (can be loaded from literal):
			if (dstType == typeof(int))
			{
				if (src_type == null)
				{
					il.LdcI4(Convert.ObjectToInteger(srcTypeOrValue));
				}
				else
				{
					// boxing and conversion:
					if (src_type.IsValueType) il.Emit(OpCodes.Box, src_type);
					il.Emit(OpCodes.Call, Methods.Convert.ObjectToInteger);
				}
				return;
			}

			// to long integer (can be loaded from literal):
			if (dstType == typeof(long))
			{
				if (src_type == null)
				{
					il.LdcI8(Convert.ObjectToLongInteger(srcTypeOrValue));
				}
				else
				{
					// boxing and conversion:
					if (src_type.IsValueType) il.Emit(OpCodes.Box, src_type);
					il.Emit(OpCodes.Call, Methods.Convert.ObjectToLongInteger);
				}
				return;
			}

			// to boolean (can be loaded from literal):
			if (dstType == typeof(bool))
			{
				if (src_type == null)
				{
					il.LdcI4(Convert.ObjectToBoolean(srcTypeOrValue) ? 1 : 0);
				}
				else
				{
					// boxing and conversion:
					if (src_type.IsValueType) il.Emit(OpCodes.Box, src_type);
					il.Emit(OpCodes.Call, Methods.Convert.ObjectToBoolean);
				}
				return;
			}

			// to double (can be loaded from literal):
			if (dstType == typeof(double))
			{
				if (src_type == null)
				{
					il.Emit(OpCodes.Ldc_R8, Convert.ObjectToDouble(srcTypeOrValue));
				}
				else
				{
					// boxing and conversion:
					if (src_type.IsValueType) il.Emit(OpCodes.Box, src_type);
					il.Emit(OpCodes.Call, Methods.Convert.ObjectToDouble);
				}
				return;
			}

			// to string (can be loaded from literal):
			if (dstType == typeof(string))
			{
				if (src_type == null)
				{
					il.Emit(OpCodes.Ldstr, Convert.ObjectToString(srcTypeOrValue));
				}
				else
				{
					// boxing and conversion:
					if (src_type.IsValueType) il.Emit(OpCodes.Box, src_type);
					il.Emit(OpCodes.Call, Methods.Convert.ObjectToString);
				}
				return;
			}

            // to bytes:
            if (dstType == typeof(PhpBytes))
            {
                if (src_type == null)
                {
                    il.EmitLoadPhpBytes(Convert.ObjectToPhpBytes(srcTypeOrValue));
                }
                else
                {
                    // boxing and conversion:
                    if (src_type.IsValueType) il.Emit(OpCodes.Box, src_type);
                    il.Emit(OpCodes.Call, Methods.Convert.ObjectToPhpBytes);
                }
                return;
            }

            // to char:
			if (dstType == typeof(char))
			{
				if (src_type == null)
				{
					il.LdcI4((int)Convert.ObjectToChar(srcTypeOrValue));
				}
				else
				{
					// boxing and conversion:
					if (src_type.IsValueType) il.Emit(OpCodes.Box, src_type);
					il.Emit(OpCodes.Call, Methods.Convert.ObjectToChar);
				}
				return;
			}

			#endregion

			// further conversions doesn't work with empty stack => loads literal on eval stack:
			if (src_type == null)
				src_type = il.LoadLiteral(srcTypeOrValue);

			if (src_type.IsValueType)
				il.Emit(OpCodes.Box, src_type);

			// to callback:
			if (dstType == typeof(PhpCallback))
			{
				il.Emit(OpCodes.Call, Methods.Convert.ObjectToCallback);
				return;
			}

			Debug.Assert(!dstType.IsValueType);

			if (param.IsDefined(typeof(PhpDeepCopyAttribute), false))
			{
				// do not copy literals:
				if (!src_type.IsValueType && src_type != typeof(string))
				{
					// CALL (<src_type>)PhpVariable.Copy(STACK,CopyReason.PassedByCopy);
					il.LdcI4((int)CopyReason.PassedByCopy);
					il.Emit(OpCodes.Call, Methods.PhpVariable.Copy);

					// src_type was on the eval. stack before copy was called:
					if (src_type != typeof(object))
						il.Emit(OpCodes.Castclass, src_type);
				}
			}

			// to object:
			if (dstType == typeof(object)) return;

            //
            // cast the value to the target type
            //
            if (allowImplicitCast)
            {
                // cast the value, without the checking of the success
                il.Emit(OpCodes.Isinst, dstType);
            }
            else
            {
                // if implicit cast is not allowed => a condition checking the result of the cast
                // is emitted (conditional call to InvalidImplicitCast)

                // conversion of array, object, and resource:
                string type_name = PhpVariable.GetAssignableTypeName(dstType);

                Label endif_label = il.DefineLabel();
                Label endblock_label = il.DefineLabel();

                //LocalBuilder loc_typed = null;
                bool needsCast;
                LocalBuilder loc_obj = il.DeclareLocal(typeof(object));
                il.Emit(OpCodes.Dup);
                il.Stloc(loc_obj);
                
                // IF (obj == null) goto ENDIF;
                il.Emit(OpCodes.Dup);
                il.Emit(OpCodes.Ldnull);
                il.Emit(OpCodes.Beq_S, endblock_label);

                // (obj) on top of eval stack, eat it:

                if (dstType.IsSealed)
                {
                    needsCast = true;
                    // if (<obj>.GetType() == typeof(<dstType>)) goto ENDIF;    // little JIT hack
                    il.Emit(OpCodes.Dup);                
                    il.Emit(OpCodes.Callvirt, Methods.Object_GetType);
                    il.Emit(OpCodes.Ldtoken, dstType);
                    il.Emit(OpCodes.Call, Methods.GetTypeFromHandle);
                    il.Emit(OpCodes.Call, Methods.Equality_Type_Type);
                    il.Emit(OpCodes.Brtrue, endif_label);
                    
                    // (object)<obj> on stack
                }
                else
                {
                    needsCast = false;

                    //loc_typed = il.DeclareLocal(dstType);

                    // <loc_typed> = <obj> as <dstType>:
                    il.Emit(OpCodes.Isinst, dstType);
                    //il.Stloc(loc_typed);

                    // (obj as dstType) is on top of the evaluation stack

                    // IF (obj!=null) goto ENDIF;
                    il.Emit(OpCodes.Dup);
                    il.Emit(OpCodes.Brtrue_S, endif_label);

                    // (<obj> as <dstType>) on stack
                }

                if (true)
                {
                    il.Emit(OpCodes.Pop);   // pops <obj> from stack

                    // CALL PhpException.InvalidImplicitCast(obj,<PhpTypeName>,<functionName>);
                    il.Ldloc(loc_obj);      // pushes original <obj>
                    il.Emit(OpCodes.Ldstr, type_name);
                    il.Emit(OpCodes.Ldstr, this.functionName.ToString());
                    il.Emit(OpCodes.Call, Methods.PhpException.InvalidImplicitCast);
                    
                    if (debug)
                        il.Emit(OpCodes.Nop);

                    // pops all arguments already pushed:
                    int popsCount = pushedArgsCount + additionalValuesOnStackCount;
                    for (int i = 0; i < popsCount; ++i)
                        il.Emit(OpCodes.Pop);
                    
                    Debug.Assert(overloadCallSkipEmitter != null);

                    // GOTO <end of call>;
                    //il.Emit(OpCodes.Br, overloadCallEndLabel);
                    overloadCallSkipEmitter(il);
                }

                // ENDIF;
                il.MarkLabel(endif_label);

                // load <obj>
                if (needsCast)
                {
                    // cast <obj> from top of the stack
                    il.Emit(OpCodes.Castclass, dstType);
                }

                // ENDBLOCK:
                il.MarkLabel(endblock_label);
            }
		}
Пример #17
0
        static bool InternalParamIsDefined (ParameterInfo parameter, Type attributeType, bool inherit)
        {
            if (parameter.IsDefined (attributeType, inherit))
                return true;

            if (!inherit)
                return false;

            var member = parameter.Member;
            if (member.MemberType != MemberTypes.Method)
                return false;

            var method = ((MethodInfo) member).GetBaseMethod ();

            while (true) {
                var param = method.GetParametersInternal () [parameter.Position];
                if (param.IsDefined (attributeType, false))
                    return true;

                var base_method = method.GetBaseMethod ();
                if (base_method == method)
                    break;

                method = base_method;
            }

            return false;
        }
Пример #18
0
        internal static ParameterResult GetParameterResultFromParameterInfo(ParameterInfo param)
        {
            // TODO: Get parameter documentation
            var pyType = ClrModule.GetPythonType(param.ParameterType);

            string name = param.Name;
            string typeName = PythonType.Get__name__(pyType);
            if (param.IsDefined(typeof(ParamArrayAttribute), false)) {
                name = "*" + name;
                if (param.ParameterType.IsArray) {
                    var elemType = param.ParameterType.GetElementType();
                    if (elemType == typeof(object)) {
                        typeName = "sequence";
                    } else {
                        typeName = PythonType.Get__name__(DynamicHelpers.GetPythonTypeFromType(elemType)) + " sequence";
                    }
                }
            } else if (param.IsDefined(typeof(ParamDictionaryAttribute), false)) {
                name = "**" + name;
                typeName = "object";
            }

            bool isOptional = false;
            if (param.DefaultValue != DBNull.Value && !(param.DefaultValue is Missing)) {
                name = name + " = " + PythonOps.Repr(DefaultContext.Default, param.DefaultValue);
            } else if (param.IsOptional) {
                object missing = CompilerHelpers.GetMissingValue(param.ParameterType);
                if (missing != Missing.Value) {
                    name = name + " = " + PythonOps.Repr(DefaultContext.Default, missing);
                } else {
                    isOptional = true;
                }
            }

            return new ParameterResult(name, "", typeName, isOptional);
        }
Пример #19
0
 private string GetParameterModifiers(ParameterInfo x, bool includeParams)
 {
     if (x.ParameterType.IsByRef)
         if (x.IsOut) return "out ";
         else return "ref ";
     else if (x.IsDefined(typeof(ParamArrayAttribute), false) && includeParams)
         return "params ";
     else
         return string.Empty;
 }
Пример #20
0
        //SetSpecified(Parameter|Field) has to be here, because .NET generates proxy objects with special parameters when value type is present.
        //The reason is value types are not Nullable so this special parameter indicates if value is present or not
        //http://stackoverflow.com/questions/3362574/how-to-get-rid-of-xmlignoreattribute-when-creating-proxy-dynamically-from-wsdl
                
        private bool SetSpecifiedParameter(List<object> resultParams, ParameterInfo pi)
        {
            //check XmlIgnoreAttribute
            //There is case when field always has to be specified so *Specified field isn't present
            if (lastPrimitive && pi.IsDefined(typeof(System.Xml.Serialization.XmlIgnoreAttribute), false))
            {
                resultParams.Add(true);
                lastPrimitive = false;
                return true;
            }

            lastPrimitive = false;
            return false;
        }
Пример #21
0
        public override Expression/*!*/ Convert(DynamicMetaObject/*!*/ metaObject, Type restrictedType, ParameterInfo info, Type/*!*/ toType) {
            Expression expr = metaObject.Expression;
            Type fromType = restrictedType ?? expr.Type;

            // block:
            if (fromType == typeof(MissingBlockParam)) {
                Debug.Assert(toType == typeof(BlockParam) || toType == typeof(MissingBlockParam));
                return AstUtils.Constant(null);
            }

            if (fromType == typeof(BlockParam) && toType == typeof(MissingBlockParam)) {
                return AstUtils.Constant(null);
            }

            // protocol conversions:
            if (info != null && info.IsDefined(typeof(DefaultProtocolAttribute), false)) {
                var action = RubyConversionAction.TryGetDefaultConversionAction(Context, toType);
                if (action != null) {
                    // TODO: inline implicit conversions:
                    return Ast.Dynamic(action, toType, expr);
                }

                // Do not throw an exception here to allow generic type parameters to be used with D.P. attribute.
                // The semantics should be to use DP if available for the current instantiation and ignore it otherwise.
            }

            if (restrictedType != null) {
                if (restrictedType == typeof(DynamicNull)) {
                    if (!toType.IsValueType || toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(Nullable<>)) {
                        return AstUtils.Constant(null, toType);
                    } else if (toType == typeof(bool)) {
                        return AstUtils.Constant(false);
                    }
                }

                if (toType.IsAssignableFrom(restrictedType)) {
                    // expr can be converted to restrictedType, which can be converted toType => we can convert expr to toType:
                    return AstUtils.Convert(expr, CompilerHelpers.GetVisibleType(toType));
                }

                // if there is a simple conversion from restricted type, convert the expression to the restricted type and use that conversion:
                Type visibleRestrictedType = CompilerHelpers.GetVisibleType(restrictedType);
                if (Converter.CanConvertFrom(metaObject, visibleRestrictedType, toType, false, NarrowingLevel.None, false, false)) {
                    expr = AstUtils.Convert(expr, visibleRestrictedType);
                }
            }

            return Converter.ConvertExpression(expr, toType, _args.RubyContext, _args.MetaContext.Expression, _implicitProtocolConversions);
        }
Пример #22
0
		/// <summary>
		/// Determines whether a type represented by a class object is
		/// convertible to another type represented by a class object using a
		/// method invocation conversion, treating object types of primitive
		/// types as if they were primitive types (that is, a Boolean actual
		/// parameter type matches boolean primitive formal type). This behavior
		/// is because this method is used to determine applicable methods for
		/// an actual parameter list, and primitive types are represented by
		/// their object duals in reflective method calls.
		/// </summary>
		/// <param name="formal">the formal parameter type to which the actual parameter type should be convertible</param>
		/// <param name="actual">the actual parameter type.</param>
		/// <returns>
		/// true if either formal type is assignable from actual type,
		/// or formal is a primitive type and actual is its corresponding object
		/// type or an object type of a primitive type that can be converted to
		/// the formal type.
		/// </returns>
		private static bool IsMethodInvocationConvertible(ParameterInfo formal, Type actual)
		{
			Type underlyingType = formal.ParameterType;

			if (formal.IsDefined(typeof(ParamArrayAttribute), false))
			{
				underlyingType = formal.ParameterType.GetElementType();
			}

			// if it's a null, it means the arg was null
			if (actual == null && !underlyingType.IsPrimitive)
			{
				return true;
			}

			// Check for identity or widening reference conversion
			if (actual != null && underlyingType.IsAssignableFrom(actual))
			{
				return true;
			}

			// Check for boxing with widening primitive conversion.
			if (underlyingType.IsPrimitive)
			{
				if (underlyingType == typeof(Boolean) && actual == typeof(Boolean))
					return true;
				if (underlyingType == typeof(Char) && actual == typeof(Char))
					return true;
				if (underlyingType == typeof(Byte) && actual == typeof(Byte))
					return true;
				if (underlyingType == typeof(Int16) && (actual == typeof(Int16) || actual == typeof(Byte)))
					return true;
				if (underlyingType == typeof(Int32) &&
				    (actual == typeof(Int32) || actual == typeof(Int16) || actual == typeof(Byte)))
					return true;
				if (underlyingType == typeof(Int64) &&
				    (actual == typeof(Int64) || actual == typeof(Int32) || actual == typeof(Int16) || actual == typeof(Byte)))
					return true;
				if (underlyingType == typeof(Single) &&
				    (actual == typeof(Single) || actual == typeof(Int64) || actual == typeof(Int32) || actual == typeof(Int16) ||
				     actual == typeof(Byte)))
					return true;
				if (underlyingType == typeof(Double) &&
				    (actual == typeof(Double) || actual == typeof(Single) || actual == typeof(Int64) || actual == typeof(Int32) ||
				     actual == typeof(Int16) || actual == typeof(Byte)))
					return true;
			}

			return false;
		}
Пример #23
0
		bool IsParamsArg (ParameterInfo pi)
		{
			return pi.ParameterType.IsArray && pi.IsDefined (typeof (ParamArrayAttribute));
		}
Пример #24
0
		private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit)
		{
			if (param.IsDefined(type, false))
			{
				return true;
			}
			if (param.Member.DeclaringType == null || !inherit)
			{
				return false;
			}
			for (ParameterInfo parentDefinition = Attribute.GetParentDefinition(param); parentDefinition != null; parentDefinition = Attribute.GetParentDefinition(parentDefinition))
			{
				object[] customAttributes = parentDefinition.GetCustomAttributes(type, false);
				for (int i = 0; i < customAttributes.Length; i++)
				{
					Type type2 = customAttributes[i].GetType();
					AttributeUsageAttribute attributeUsageAttribute = Attribute.InternalGetAttributeUsage(type2);
					if (customAttributes[i] is Attribute && attributeUsageAttribute.Inherited)
					{
						return true;
					}
				}
			}
			return false;
		}
Пример #25
0
        public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit)
        {
            // Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            if (attributeType == null)
                throw new ArgumentNullException(nameof(attributeType));
            
            if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
                throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
            Contract.EndContractBlock();

            MemberInfo member = element.Member;

            switch(member.MemberType)
            {
                case MemberTypes.Method: // We need to climb up the member hierarchy            
                    return InternalParamIsDefined(element, attributeType, inherit);

                case MemberTypes.Constructor:
                    return element.IsDefined(attributeType, false);

                case MemberTypes.Property:
                    return element.IsDefined(attributeType, false);

                default: 
                    Contract.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
                    throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo"));
            }
        }
Пример #26
0
 internal static bool IsDefined(ParameterInfo/*!*/ param)
 {
     return param != null && param.IsDefined(typeof(PhpRwAttribute), false);
 }
Пример #27
0
		public static bool IsDefined (ParameterInfo element, Type attributeType, bool inherit)
		{
			CheckParameters (element, attributeType);

			if (element.IsDefined (attributeType, inherit))
				return true;

			if (inherit)
				return IsDefinedOnParameter (element, attributeType);

			return false;
		}
        private void CheckParameter(ParameterInfo parameterInfo, object parameterValue,
            IMethodCallMessage mcall, IDictionary<string, object> symbolStore)
        {
            Type type = parameterValue.GetType();

            if (!type.IsPrimitive)
            {
                RpcAdapterValidate(parameterValue, parameterInfo, symbolStore);
                return;
            }

            bool checkSuccess = false;
            if ((parameterInfo.IsDefined(typeof(PossibleValueAttribute), false)
                    || parameterInfo.IsDefined(typeof(PossibleValueRangeAttribute), false)))
            {
                Attribute[] attributes =
                    (Attribute[])parameterInfo.GetCustomAttributes(typeof(Attribute), false);
                foreach (Attribute attribute in attributes)
                {
                    if (attribute is PossibleValueRangeAttribute && !checkSuccess)
                    {
                        checkSuccess =
                            MessageUtils.CheckValueByRange(parameterValue, (PossibleValueRangeAttribute)attribute);
                    }

                    if (attribute is PossibleValueAttribute && !checkSuccess)
                    {
                        checkSuccess =
                            messageUtils.CheckValueByEnum(parameterValue, ((PossibleValueAttribute)attribute).EnumType);
                    }
                }
            }
            else
            {
                checkSuccess = true;
            }

            if (!checkSuccess)
            {
                throw new InvalidOperationException(
                           String.Format("Value of parameter '{0}' in method '{1}' is not one of its specified values",
                                        parameterInfo.Name, mcall.MethodBase));
            }
        }
Пример #29
0
		private static object GetDefaultValueFor(ParameterInfo parameter)
		{
			var type = parameter.ParameterType;
			if (type == typeof(bool))
			{
				return false;
			}
			if (type.IsEnum)
			{
				return Enum.ToObject(type, 0);
			}
			if (type == typeof(char))
			{
				return Char.MinValue;
			}
			if (type.IsPrimitive)
			{
				return 0;
			}
			if(type.IsArray && parameter.IsDefined(typeof(ParamArrayAttribute), true))
			{
				return Array.CreateInstance(type.GetElementType(), 0);
			}

			return null;
		}
Пример #30
0
        public override Expression/*!*/ Convert(DynamicMetaObject/*!*/ metaObject, Type restrictedType, ParameterInfo info, Type/*!*/ toType) {
            Expression expr = metaObject.Expression;
            Type fromType = restrictedType ?? expr.Type;

            // block:
            if (fromType == typeof(MissingBlockParam)) {
                Debug.Assert(toType == typeof(BlockParam) || toType == typeof(MissingBlockParam));
                return AstUtils.Constant(null);
            }

            if (fromType == typeof(BlockParam) && toType == typeof(MissingBlockParam)) {
                return AstUtils.Constant(null);
            }

            // protocol conversions:
            if (info != null && info.IsDefined(typeof(DefaultProtocolAttribute), false)) {
                var action = RubyConversionAction.TryGetDefaultConversionAction(Context, toType);
                if (action != null) {
                    // TODO: inline implicit conversions:
                    return Ast.Dynamic(action, toType, expr);
                }

                throw new InvalidOperationException(String.Format("No default protocol conversion for type {0}.", toType));
            }

            if (restrictedType != null) {
                if (restrictedType == typeof(DynamicNull)) {
                    if (!toType.IsValueType || toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(Nullable<>)) {
                        return AstUtils.Constant(null, toType);
                    } else if (toType == typeof(bool)) {
                        return AstUtils.Constant(false);
                    }
                }

                if (toType.IsAssignableFrom(restrictedType)) {
                    // expr can be converted to restrictedType, which can be converted toType => we can convert expr to toType:
                    return AstUtils.Convert(expr, CompilerHelpers.GetVisibleType(toType));
                }

                // if there is a simple conversion from restricted type, convert the expression to the restricted type and use that conversion:
                Type visibleRestrictedType = CompilerHelpers.GetVisibleType(restrictedType);
                if (Converter.CanConvertFrom(visibleRestrictedType, toType, NarrowingLevel.One, false)) {
                    expr = AstUtils.Convert(expr, visibleRestrictedType);
                }
            }

            return Converter.ConvertExpression(expr, toType, _args.RubyContext, _args.MetaContext.Expression, _implicitProtocolConversions);
        }