CSharpName() static public méthode

static public CSharpName ( IList types ) : string
types IList
Résultat string
Exemple #1
0
 public override void Error_ValueCannotBeConverted(EmitContext ec, Location loc, Type t, bool expl)
 {
     if (TypeManager.IsGenericParameter(t))
     {
         Report.Error(403, loc,
                      "Cannot convert null to the type parameter `{0}' because it could be a value " +
                      "type. Consider using `default ({0})' instead", t.Name);
     }
     else
     {
         Report.Error(37, loc, "Cannot convert null to `{0}' because it is a value type",
                      TypeManager.CSharpName(t));
     }
 }
        // <summary>
        //   Resolve is used in method definitions
        // </summary>
        public virtual Type Resolve(IResolveContext ec)
        {
            // HACK: to resolve attributes correctly
            this.resolve_context = ec;

            if (parameter_type != null)
            {
                return(parameter_type);
            }

            TypeExpr texpr = TypeName.ResolveAsTypeTerminal(ec, false);

            if (texpr == null)
            {
                return(null);
            }

            parameter_type = texpr.Type;

            if ((modFlags & Parameter.Modifier.ISBYREF) != 0 &&
                TypeManager.IsSpecialType(parameter_type))
            {
                Report.Error(1601, Location, "Method or delegate parameter cannot be of type `{0}'",
                             GetSignatureForError());
                return(null);
            }

#if GMCS_SOURCE
            TypeParameterExpr tparam = texpr as TypeParameterExpr;
            if (tparam != null)
            {
                return(parameter_type);
            }
#endif

            if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute)
            {
                Report.Error(721, Location, "`{0}': static types cannot be used as parameters",
                             texpr.GetSignatureForError());
                return(parameter_type);
            }

            if ((modFlags & Modifier.This) != 0 && parameter_type.IsPointer)
            {
                Report.Error(1103, Location, "The type of extension method cannot be `{0}'",
                             TypeManager.CSharpName(parameter_type));
            }

            return(parameter_type);
        }
Exemple #3
0
        // <summary>
        //   Resolve is used in method definitions
        // </summary>
        public virtual TypeSpec Resolve(IMemberContext rc, int index)
        {
            if (parameter_type != null)
            {
                return(parameter_type);
            }

            if (attributes != null)
            {
                attributes.AttachTo(this, rc);
            }

            var expr = texpr.ResolveAsType(rc);

            if (expr == null)
            {
                return(null);
            }

            this.idx       = index;
            texpr          = expr;
            parameter_type = texpr.Type;

            if ((modFlags & Parameter.Modifier.ISBYREF) != 0 && parameter_type.IsSpecialRuntimeType)
            {
                rc.Module.Compiler.Report.Error(1601, Location, "Method or delegate parameter cannot be of type `{0}'",
                                                GetSignatureForError());
                return(null);
            }

            TypeManager.CheckTypeVariance(parameter_type,
                                          (modFlags & Parameter.Modifier.ISBYREF) != 0 ? Variance.None : Variance.Contravariant,
                                          rc);

            if (parameter_type.IsStatic)
            {
                rc.Module.Compiler.Report.Error(721, Location, "`{0}': static types cannot be used as parameters",
                                                texpr.GetSignatureForError());
                return(parameter_type);
            }

            if ((modFlags & Modifier.This) != 0 && (parameter_type.IsPointer || parameter_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic))
            {
                rc.Module.Compiler.Report.Error(1103, Location, "The extension method cannot be of type `{0}'",
                                                TypeManager.CSharpName(parameter_type));
            }

            return(parameter_type);
        }
Exemple #4
0
        // <summary>
        //  Verifies whether the invocation arguments are compatible with the
        //  delegate's target method
        // </summary>
        public static bool VerifyApplicability(EmitContext ec, Type delegate_type,
                                               ArrayList args, Location loc)
        {
            int arg_count;

            if (args == null)
            {
                arg_count = 0;
            }
            else
            {
                arg_count = args.Count;
            }

            Expression ml = Expression.MemberLookup(
                ec.ContainerType, delegate_type, "Invoke", loc);

            MethodGroupExpr me = ml as MethodGroupExpr;

            if (me == null)
            {
                Report.Error(-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
                return(false);
            }

            MethodBase            mb = GetInvokeMethod(ec.ContainerType, delegate_type);
            AParametersCollection pd = TypeManager.GetParameterData(mb);

            int pd_count = pd.Count;

            bool params_method        = pd.HasParams;
            bool is_params_applicable = false;
            bool is_applicable        = me.IsApplicable(ec, args, arg_count, ref mb, ref is_params_applicable) == 0;

            if (!is_applicable && !params_method && arg_count != pd_count)
            {
                Report.Error(1593, loc, "Delegate `{0}' does not take `{1}' arguments",
                             TypeManager.CSharpName(delegate_type), arg_count.ToString());
                return(false);
            }

            return(me.VerifyArgumentsCompat(
                       ec, ref args, arg_count, mb,
                       is_params_applicable || (!is_applicable && params_method),
                       false, loc));
        }
Exemple #5
0
        public override void ApplyAttributeBuilder(Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
        {
            if (a.Type == pa.In && ModFlags == Modifier.OUT)
            {
                a.Report.Error(36, a.Location, "An out parameter cannot have the `In' attribute");
                return;
            }

            if (a.Type == pa.ParamArray)
            {
                a.Report.Error(674, a.Location, "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead");
                return;
            }

            if (a.Type == pa.Out && (ModFlags & Modifier.REF) == Modifier.REF &&
                !OptAttributes.Contains(pa.In))
            {
                a.Report.Error(662, a.Location,
                               "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and `Out' attributes or neither");
                return;
            }

            if (a.Type == pa.CLSCompliant)
            {
                a.Report.Warning(3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead");
            }

            if (a.Type == pa.DefaultParameterValue || a.Type == pa.OptionalParameter)
            {
                if (HasOptionalExpression)
                {
                    a.Report.Error(1745, a.Location,
                                   "Cannot specify `{0}' attribute on optional parameter `{1}'",
                                   TypeManager.CSharpName(a.Type).Replace("Attribute", ""), Name);
                }

                if (a.Type == pa.DefaultParameterValue)
                {
                    return;
                }
            }

            base.ApplyAttributeBuilder(a, ctor, cdata, pa);
        }
Exemple #6
0
		protected override void DoMemberTypeDependentChecks ()
		{
			if ((ModFlags & Modifiers.BACKING_FIELD) != 0)
				return;

			base.DoMemberTypeDependentChecks ();

			if ((ModFlags & Modifiers.VOLATILE) != 0) {
				if (!CanBeVolatile ()) {
					Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
						GetSignatureForError (), TypeManager.CSharpName (MemberType));
				}

				if ((ModFlags & Modifiers.READONLY) != 0) {
					Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
						GetSignatureForError ());
				}
			}
		}
Exemple #7
0
        public override void Error_ValueCannotBeConverted(ResolveContext ec, Location loc, TypeSpec t, bool expl)
        {
            if (t.IsGenericParameter)
            {
                ec.Report.Error(403, loc,
                                "Cannot convert null to the type parameter `{0}' because it could be a value " +
                                "type. Consider using `default ({0})' instead", t.Name);
                return;
            }

            if (TypeSpec.IsValueType(t))
            {
                ec.Report.Error(37, loc, "Cannot convert null to `{0}' because it is a value type",
                                TypeManager.CSharpName(t));
                return;
            }

            base.Error_ValueCannotBeConverted(ec, loc, t, expl);
        }
Exemple #8
0
        protected override bool VerifyClsCompliance()
        {
            if (!base.VerifyClsCompliance())
            {
                return(false);
            }

            switch (UnderlyingType.BuiltinType)
            {
            case BuiltinTypeSpec.Type.UInt:
            case BuiltinTypeSpec.Type.ULong:
            case BuiltinTypeSpec.Type.UShort:
                Report.Warning(3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
                               GetSignatureForError(), TypeManager.CSharpName(UnderlyingType));
                break;
            }

            return(true);
        }
Exemple #9
0
        static string FriendlyStackTrace(StackTrace t)
        {
            StringBuilder sb = new StringBuilder();

            bool foundUserCode = false;

            for (int i = 0; i < t.FrameCount; i++)
            {
                StackFrame f  = t.GetFrame(i);
                MethodBase mb = f.GetMethod();

                if (!foundUserCode && mb.ReflectedType == typeof(Report))
                {
                    continue;
                }

                foundUserCode = true;

                sb.Append("\tin ");

                if (f.GetFileLineNumber() > 0)
                {
                    sb.AppendFormat("(at {0}:{1}) ", f.GetFileName(), f.GetFileLineNumber());
                }

                sb.AppendFormat("{0}.{1} (", mb.ReflectedType.Name, mb.Name);

                bool first = true;
                foreach (ParameterInfo pi in mb.GetParameters())
                {
                    if (!first)
                    {
                        sb.Append(", ");
                    }
                    first = false;

                    sb.Append(TypeManager.CSharpName(pi.ParameterType));
                }
                sb.Append(")\n");
            }

            return(sb.ToString());
        }
        public override void Emit()
        {
            ResolveContext rc = new ResolveContext(this);
            IntConstant    buffer_size_const = initializer.Resolve(rc) as IntConstant;

            if (buffer_size_const == null)
            {
                return;
            }

            int buffer_size = buffer_size_const.Value;

            if (buffer_size <= 0)
            {
                Report.Error(1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError());
                return;
            }

            int type_size = Expression.GetTypeSize(MemberType);

            if (buffer_size > int.MaxValue / type_size)
            {
                Report.Error(1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
                             GetSignatureForError(), buffer_size.ToString(), TypeManager.CSharpName(MemberType));
                return;
            }

            EmitFieldSize(buffer_size);

#if STATIC
            if (Module.HasDefaultCharSet)
            {
                fixed_buffer_type.__SetAttributes(fixed_buffer_type.Attributes | Module.DefaultCharSetType);
            }
#endif

            Module.PredefinedAttributes.UnsafeValueType.EmitAttribute(fixed_buffer_type);
            Module.PredefinedAttributes.CompilerGenerated.EmitAttribute(fixed_buffer_type);
            fixed_buffer_type.CreateType();

            base.Emit();
        }
Exemple #11
0
        // <summary>
        //  Verifies whether the invocation arguments are compatible with the
        //  delegate's target method
        // </summary>
        public static bool VerifyApplicability(ResolveContext ec, Type delegate_type, ref Arguments args, Location loc)
        {
            int arg_count;

            if (args == null)
            {
                arg_count = 0;
            }
            else
            {
                arg_count = args.Count;
            }

            MethodBase      mb = GetInvokeMethod(ec.Compiler, ec.CurrentType, delegate_type);
            MethodGroupExpr me = new MethodGroupExpr(new MemberInfo [] { mb }, delegate_type, loc);

            AParametersCollection pd = TypeManager.GetParameterData(mb);

            int pd_count = pd.Count;

            bool params_method        = pd.HasParams;
            bool is_params_applicable = false;
            bool is_applicable        = me.IsApplicable(ec, ref args, arg_count, ref mb, ref is_params_applicable) == 0;

            if (args != null)
            {
                arg_count = args.Count;
            }

            if (!is_applicable && !params_method && arg_count != pd_count)
            {
                ec.Report.Error(1593, loc, "Delegate `{0}' does not take `{1}' arguments",
                                TypeManager.CSharpName(delegate_type), arg_count.ToString());
                return(false);
            }

            return(me.VerifyArgumentsCompat(
                       ec, ref args, arg_count, mb,
                       is_params_applicable || (!is_applicable && params_method),
                       false, loc));
        }
        public virtual string GetSignatureForError()
        {
            string type_name;

            if (parameter_type != null)
            {
                type_name = TypeManager.CSharpName(parameter_type);
            }
            else
            {
                type_name = texpr.GetSignatureForError();
            }

            string mod = GetModifierSignature(modFlags);

            if (mod.Length > 0)
            {
                return(String.Concat(mod, " ", type_name));
            }

            return(type_name);
        }
        public string ParameterDesc(int pos)
        {
            if (types == null || types [pos] == null)
            {
                return(((Parameter)FixedParameters [pos]).GetSignatureForError());
            }

            string type = TypeManager.CSharpName(types [pos]);

            if (FixedParameters [pos].HasExtensionMethodModifier)
            {
                return("this " + type);
            }

            Parameter.Modifier mod = FixedParameters [pos].ModFlags;
            if (mod == 0)
            {
                return(type);
            }

            return(Parameter.GetModifierSignature(mod) + " " + type);
        }
Exemple #14
0
        static public string GetVars()
        {
            lock (evaluator_lock){
                StringBuilder sb = new StringBuilder();

                foreach (DictionaryEntry de in fields)
                {
                    FieldInfo fi    = LookupField((string)de.Key);
                    object    value = null;
                    bool      error = false;

                    try {
                        if (value == null)
                        {
                            value = "null";
                        }
                        value = fi.GetValue(null);
                        if (value is string)
                        {
                            value = Quote((string)value);
                        }
                    } catch {
                        error = true;
                    }

                    if (error)
                    {
                        sb.Append(String.Format("{0} {1} <error reading value>", TypeManager.CSharpName(fi.FieldType), de.Key));
                    }
                    else
                    {
                        sb.Append(String.Format("{0} {1} = {2}", TypeManager.CSharpName(fi.FieldType), de.Key, value));
                    }
                }

                return(sb.ToString());
            }
        }
        public override Type LookupTypeReflection(string name, Location loc)
        {
            Type found_type = base.LookupTypeReflection(name, loc);

            if (modules != null)
            {
                foreach (Module module in modules)
                {
                    Type t = module.GetType(name);
                    if (t == null)
                    {
                        continue;
                    }

                    if (found_type == null)
                    {
                        found_type = t;
                        continue;
                    }

                    Report.SymbolRelatedToPreviousError(found_type);
                    if (loc.IsNull)
                    {
                        DeclSpace ds = TypeManager.LookupDeclSpace(t);
                        Report.Warning(1685, 1, ds.Location, "The type `{0}' conflicts with the predefined type `{1}' and will be ignored",
                                       ds.GetSignatureForError(), TypeManager.CSharpName(found_type));
                        return(found_type);
                    }
                    Report.SymbolRelatedToPreviousError(t);
                    Report.Warning(436, 2, loc, "The type `{0}' conflicts with the imported type `{1}'. Ignoring the imported type definition",
                                   TypeManager.CSharpName(t), TypeManager.CSharpName(found_type));
                    return(t);
                }
            }

            return(found_type);
        }
Exemple #16
0
        /// <summary>
        ///   Verifies that any pending abstract methods or interface methods
        ///   were implemented.
        /// </summary>
        public bool VerifyPendingMethods()
        {
            int  top    = pending_implementations.Length;
            bool errors = false;
            int  i;

            for (i = 0; i < top; i++)
            {
                TypeSpec type = pending_implementations [i].type;

                bool base_implements_type = type.IsInterface &&
                                            container.BaseType != null &&
                                            container.BaseType.ImplementsInterface(type, false);

                for (int j = 0; j < pending_implementations [i].methods.Count; ++j)
                {
                    var mi = pending_implementations[i].methods[j];
                    if (mi == null)
                    {
                        continue;
                    }

                    if (type.IsInterface)
                    {
                        var need_proxy =
                            pending_implementations [i].need_proxy [j];

                        if (need_proxy != null)
                        {
                            DefineProxy(type, need_proxy, mi);
                            continue;
                        }

                        if (pending_implementations [i].optional)
                        {
                            continue;
                        }

                        MethodSpec candidate = null;
                        if (base_implements_type || BaseImplements(type, mi, out candidate))
                        {
                            continue;
                        }

                        if (candidate == null)
                        {
                            MethodData md = pending_implementations [i].found [j];
                            if (md != null)
                            {
                                candidate = md.method.Spec;
                            }
                        }

                        Report.SymbolRelatedToPreviousError(mi);
                        if (candidate != null)
                        {
                            Report.SymbolRelatedToPreviousError(candidate);
                            if (candidate.IsStatic)
                            {
                                Report.Error(736, container.Location,
                                             "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' is static",
                                             container.GetSignatureForError(), mi.GetSignatureForError(), TypeManager.CSharpSignature(candidate));
                            }
                            else if ((candidate.Modifiers & Modifiers.PUBLIC) == 0)
                            {
                                Report.Error(737, container.Location,
                                             "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' in not public",
                                             container.GetSignatureForError(), mi.GetSignatureForError(), candidate.GetSignatureForError());
                            }
                            else
                            {
                                Report.Error(738, container.Location,
                                             "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' return type `{3}' does not match interface member return type `{4}'",
                                             container.GetSignatureForError(), mi.GetSignatureForError(), TypeManager.CSharpSignature(candidate),
                                             TypeManager.CSharpName(candidate.ReturnType), TypeManager.CSharpName(mi.ReturnType));
                            }
                        }
                        else
                        {
                            Report.Error(535, container.Location, "`{0}' does not implement interface member `{1}'",
                                         container.GetSignatureForError(), mi.GetSignatureForError());
                        }
                    }
                    else
                    {
                        Report.SymbolRelatedToPreviousError(mi);
                        Report.Error(534, container.Location, "`{0}' does not implement inherited abstract member `{1}'",
                                     container.GetSignatureForError(), mi.GetSignatureForError());
                    }
                    errors = true;
                }
            }
            return(errors);
        }
Exemple #17
0
        public ArrayInitializer CreateDynamicBinderArguments(ResolveContext rc)
        {
            Location loc = Location.Null;
            var      all = new ArrayInitializer(args.Count, loc);

            MemberAccess binder = DynamicExpressionStatement.GetBinderNamespace(loc);

            foreach (Argument a in args)
            {
                Arguments dargs = new Arguments(2);

                // CSharpArgumentInfoFlags.None = 0
                const string info_flags_enum = "CSharpArgumentInfoFlags";
                Expression   info_flags      = new IntLiteral(rc.BuiltinTypes, 0, loc);

                if (a.Expr is Constant)
                {
                    info_flags = new Binary(Binary.Operator.BitwiseOr, info_flags,
                                            new MemberAccess(new MemberAccess(binder, info_flags_enum, loc), "Constant", loc), loc);
                }
                else if (a.ArgType == Argument.AType.Ref)
                {
                    info_flags = new Binary(Binary.Operator.BitwiseOr, info_flags,
                                            new MemberAccess(new MemberAccess(binder, info_flags_enum, loc), "IsRef", loc), loc);
                    info_flags = new Binary(Binary.Operator.BitwiseOr, info_flags,
                                            new MemberAccess(new MemberAccess(binder, info_flags_enum, loc), "UseCompileTimeType", loc), loc);
                }
                else if (a.ArgType == Argument.AType.Out)
                {
                    info_flags = new Binary(Binary.Operator.BitwiseOr, info_flags,
                                            new MemberAccess(new MemberAccess(binder, info_flags_enum, loc), "IsOut", loc), loc);
                    info_flags = new Binary(Binary.Operator.BitwiseOr, info_flags,
                                            new MemberAccess(new MemberAccess(binder, info_flags_enum, loc), "UseCompileTimeType", loc), loc);
                }
                else if (a.ArgType == Argument.AType.DynamicTypeName)
                {
                    info_flags = new Binary(Binary.Operator.BitwiseOr, info_flags,
                                            new MemberAccess(new MemberAccess(binder, info_flags_enum, loc), "IsStaticType", loc), loc);
                }

                var arg_type = a.Expr.Type;

                if (arg_type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && arg_type != InternalType.NullLiteral)
                {
                    MethodGroupExpr mg = a.Expr as MethodGroupExpr;
                    if (mg != null)
                    {
                        rc.Report.Error(1976, a.Expr.Location,
                                        "The method group `{0}' cannot be used as an argument of dynamic operation. Consider using parentheses to invoke the method",
                                        mg.Name);
                    }
                    else if (arg_type == InternalType.AnonymousMethod)
                    {
                        rc.Report.Error(1977, a.Expr.Location,
                                        "An anonymous method or lambda expression cannot be used as an argument of dynamic operation. Consider using a cast");
                    }
                    else if (arg_type.Kind == MemberKind.Void || arg_type == InternalType.Arglist || arg_type.IsPointer)
                    {
                        rc.Report.Error(1978, a.Expr.Location,
                                        "An expression of type `{0}' cannot be used as an argument of dynamic operation",
                                        TypeManager.CSharpName(arg_type));
                    }

                    info_flags = new Binary(Binary.Operator.BitwiseOr, info_flags,
                                            new MemberAccess(new MemberAccess(binder, info_flags_enum, loc), "UseCompileTimeType", loc), loc);
                }

                string        named_value;
                NamedArgument na = a as NamedArgument;
                if (na != null)
                {
                    info_flags = new Binary(Binary.Operator.BitwiseOr, info_flags,
                                            new MemberAccess(new MemberAccess(binder, info_flags_enum, loc), "NamedArgument", loc), loc);

                    named_value = na.Name;
                }
                else
                {
                    named_value = null;
                }

                dargs.Add(new Argument(info_flags));
                dargs.Add(new Argument(new StringLiteral(rc.BuiltinTypes, named_value, loc)));
                all.Add(new Invocation(new MemberAccess(new MemberAccess(binder, "CSharpArgumentInfo", loc), "Create", loc), dargs));
            }

            return(all);
        }
Exemple #18
0
        protected override bool VerifyClsCompliance()
        {
            if (!base.VerifyClsCompliance())
            {
                return(false);
            }

            if (UnderlyingType == TypeManager.uint32_type ||
                UnderlyingType == TypeManager.uint64_type ||
                UnderlyingType == TypeManager.ushort_type)
            {
                Report.Warning(3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError(), TypeManager.CSharpName(UnderlyingType));
            }

            return(true);
        }
Exemple #19
0
        public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
        {
            Report Report = RootContext.ToplevelTypes.Compiler.Report;

            if (a.Type == pa.In && ModFlags == Modifier.OUT)
            {
                Report.Error(36, a.Location, "An out parameter cannot have the `In' attribute");
                return;
            }

            if (a.Type == pa.ParamArray)
            {
                Report.Error(674, a.Location, "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead");
                return;
            }

            if (a.Type == PredefinedAttributes.Get.Out && (ModFlags & Modifier.REF) == Modifier.REF &&
                !OptAttributes.Contains(pa.In))
            {
                Report.Error(662, a.Location,
                             "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and `Out' attributes or neither");
                return;
            }

            if (a.Type == pa.CLSCompliant)
            {
                Report.Warning(3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead");
            }

            if (HasDefaultValue && (a.Type == pa.DefaultParameterValue || a.Type == pa.OptionalParameter))
            {
                Report.Error(1745, a.Location,
                             "Cannot specify `{0}' attribute on optional parameter `{1}'",
                             TypeManager.CSharpName(a.Type).Replace("Attribute", ""), Name);
                return;
            }

            if (a.Type == pa.DefaultParameterValue)
            {
                object val = a.GetParameterDefaultValue();
                if (val != null)
                {
                    Type t = val.GetType();
                    if (t.IsArray || TypeManager.IsSubclassOf(t, TypeManager.type_type))
                    {
                        if (parameter_type == TypeManager.object_type)
                        {
                            if (!t.IsArray)
                            {
                                t = TypeManager.type_type;
                            }

                            Report.Error(1910, a.Location, "Argument of type `{0}' is not applicable for the DefaultParameterValue attribute",
                                         TypeManager.CSharpName(t));
                        }
                        else
                        {
                            Report.Error(1909, a.Location, "The DefaultParameterValue attribute is not applicable on parameters of type `{0}'",
                                         TypeManager.CSharpName(parameter_type));;
                        }
                        return;
                    }
                }

                if (parameter_type == TypeManager.object_type ||
                    (val == null && !TypeManager.IsGenericParameter(parameter_type) && TypeManager.IsReferenceType(parameter_type)) ||
                    (val != null && TypeManager.TypeToCoreType(val.GetType()) == parameter_type))
                {
                    builder.SetConstant(val);
                }
                else
                {
                    Report.Error(1908, a.Location, "The type of the default value should match the type of the parameter");
                }
                return;
            }

            base.ApplyAttributeBuilder(a, cb, pa);
        }
Exemple #20
0
        // <summary>
        //   Resolve is used in method definitions
        // </summary>
        public virtual Type Resolve(IMemberContext rc)
        {
            if (parameter_type != null)
            {
                return(parameter_type);
            }

            if (attributes != null)
            {
                attributes.AttachTo(this, rc);
            }

            TypeExpr texpr = TypeName.ResolveAsTypeTerminal(rc, false);

            if (texpr == null)
            {
                return(null);
            }

            parameter_type = texpr.Type;

            // Ignore all checks for dummy members
            AbstractPropertyEventMethod pem = rc as AbstractPropertyEventMethod;

            if (pem != null && pem.IsDummy)
            {
                return(parameter_type);
            }

            if (default_expr != null)
            {
                ResolveContext ec = new ResolveContext(rc);
                default_expr = default_expr.Resolve(ec);
                if (default_expr != null)
                {
                    Constant value = default_expr as Constant;
                    if (value == null)
                    {
                        if (default_expr != null)
                        {
                            bool is_valid = false;
                            if (default_expr is DefaultValueExpression)
                            {
                                is_valid = true;
                            }
                            else if (default_expr is New && ((New)default_expr).IsDefaultValueType)
                            {
                                is_valid = TypeManager.IsEqual(parameter_type, default_expr.Type) ||
                                           (TypeManager.IsNullableType(parameter_type) &&
                                            Convert.ImplicitNulableConversion(ec, default_expr, parameter_type) != EmptyExpression.Null);
                            }
                            else
                            {
                                rc.Compiler.Report.Error(1736, default_expr.Location,
                                                         "The expression being assigned to optional parameter `{0}' must be a constant or default value",
                                                         Name);
                                is_valid = true;
                            }

                            if (!is_valid)
                            {
                                default_expr = null;
                                ec.Compiler.Report.Error(1763, Location,
                                                         "Optional parameter `{0}' of type `{1}' can only be initialized with `null'",
                                                         Name, GetSignatureForError());
                            }
                        }
                    }
                    else
                    {
                        Constant c = value.ConvertImplicitly(parameter_type);
                        if (c == null)
                        {
                            if (parameter_type == TypeManager.object_type)
                            {
                                rc.Compiler.Report.Error(1763, Location,
                                                         "Optional parameter `{0}' of type `{1}' can only be initialized with `null'",
                                                         Name, GetSignatureForError());
                            }
                            else
                            {
                                rc.Compiler.Report.Error(1750, Location,
                                                         "Optional parameter value `{0}' cannot be converted to parameter type `{1}'",
                                                         value.GetValue(), GetSignatureForError());
                            }
                            default_expr = null;
                        }
                    }
                }
            }

            if ((modFlags & Parameter.Modifier.ISBYREF) != 0 &&
                TypeManager.IsSpecialType(parameter_type))
            {
                rc.Compiler.Report.Error(1601, Location, "Method or delegate parameter cannot be of type `{0}'",
                                         GetSignatureForError());
                return(null);
            }

            TypeManager.CheckTypeVariance(parameter_type,
                                          (modFlags & Parameter.Modifier.ISBYREF) != 0 ? Variance.None : Variance.Contravariant,
                                          rc);

            if (TypeManager.IsGenericParameter(parameter_type))
            {
                return(parameter_type);
            }

            if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute)
            {
                rc.Compiler.Report.Error(721, Location, "`{0}': static types cannot be used as parameters",
                                         texpr.GetSignatureForError());
                return(parameter_type);
            }

            if ((modFlags & Modifier.This) != 0 && (parameter_type.IsPointer || TypeManager.IsDynamicType(parameter_type)))
            {
                rc.Compiler.Report.Error(1103, Location, "The extension method cannot be of type `{0}'",
                                         TypeManager.CSharpName(parameter_type));
            }

            return(parameter_type);
        }
Exemple #21
0
        public void ApplyAttributeBuilder(Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
        {
            if (a.IsValidSecurityAttribute())
            {
                a.ExtractSecurityPermissionSet(ctor, ref declarative_security);
                return;
            }

            if (a.Type == pa.AssemblyCulture)
            {
                string value = a.GetString();
                if (value == null || value.Length == 0)
                {
                    return;
                }

                if (Compiler.Settings.Target == Target.Exe)
                {
                    a.Error_AttributeEmitError("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
                    return;
                }

                if (value == "neutral")
                {
                    value = "";
                }

                if (Compiler.Settings.Target == Target.Module)
                {
                    SetCustomAttribute(ctor, cdata);
                }
                else
                {
                    builder_extra.SetCulture(value, a.Location);
                }

                return;
            }

            if (a.Type == pa.AssemblyVersion)
            {
                string value = a.GetString();
                if (value == null || value.Length == 0)
                {
                    return;
                }

                var vinfo = IsValidAssemblyVersion(value, true);
                if (vinfo == null)
                {
                    a.Error_AttributeEmitError(string.Format("Specified version `{0}' is not valid", value));
                    return;
                }

                if (Compiler.Settings.Target == Target.Module)
                {
                    SetCustomAttribute(ctor, cdata);
                }
                else
                {
                    builder_extra.SetVersion(vinfo, a.Location);
                }

                return;
            }

            if (a.Type == pa.AssemblyAlgorithmId)
            {
                const int pos = 2;                 // skip CA header
                uint      alg = (uint)cdata [pos];
                alg |= ((uint)cdata [pos + 1]) << 8;
                alg |= ((uint)cdata [pos + 2]) << 16;
                alg |= ((uint)cdata [pos + 3]) << 24;

                if (Compiler.Settings.Target == Target.Module)
                {
                    SetCustomAttribute(ctor, cdata);
                }
                else
                {
                    builder_extra.SetAlgorithmId(alg, a.Location);
                }

                return;
            }

            if (a.Type == pa.AssemblyFlags)
            {
                const int pos   = 2;               // skip CA header
                uint      flags = (uint)cdata[pos];
                flags |= ((uint)cdata [pos + 1]) << 8;
                flags |= ((uint)cdata [pos + 2]) << 16;
                flags |= ((uint)cdata [pos + 3]) << 24;

                // Ignore set PublicKey flag if assembly is not strongnamed
                if ((flags & (uint)AssemblyNameFlags.PublicKey) != 0 && public_key == null)
                {
                    flags &= ~(uint)AssemblyNameFlags.PublicKey;
                }

                if (Compiler.Settings.Target == Target.Module)
                {
                    SetCustomAttribute(ctor, cdata);
                }
                else
                {
                    builder_extra.SetFlags(flags, a.Location);
                }

                return;
            }

            if (a.Type == pa.TypeForwarder)
            {
                TypeSpec t = a.GetArgumentType();
                if (t == null || TypeManager.HasElementType(t))
                {
                    Report.Error(735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
                    return;
                }

                if (emitted_forwarders == null)
                {
                    emitted_forwarders = new Dictionary <ITypeDefinition, Attribute> ();
                }
                else if (emitted_forwarders.ContainsKey(t.MemberDefinition))
                {
                    Report.SymbolRelatedToPreviousError(emitted_forwarders[t.MemberDefinition].Location, null);
                    Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
                                 TypeManager.CSharpName(t));
                    return;
                }

                emitted_forwarders.Add(t.MemberDefinition, a);

                if (t.MemberDefinition.DeclaringAssembly == this)
                {
                    Report.SymbolRelatedToPreviousError(t);
                    Report.Error(729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
                                 TypeManager.CSharpName(t));
                    return;
                }

                if (t.IsNested)
                {
                    Report.Error(730, a.Location, "Cannot forward type `{0}' because it is a nested type",
                                 TypeManager.CSharpName(t));
                    return;
                }

                builder_extra.AddTypeForwarder(t.GetDefinition(), a.Location);
                return;
            }

            if (a.Type == pa.Extension)
            {
                a.Error_MisusedExtensionAttribute();
                return;
            }

            if (a.Type == pa.InternalsVisibleTo)
            {
                string assembly_name = a.GetString();
                if (assembly_name.Length == 0)
                {
                    return;
                }
#if STATIC
                ParsedAssemblyName  aname;
                ParseAssemblyResult r = Fusion.ParseAssemblyName(assembly_name, out aname);
                if (r != ParseAssemblyResult.OK)
                {
                    Report.Warning(1700, 3, a.Location, "Assembly reference `{0}' is invalid and cannot be resolved",
                                   assembly_name);
                    return;
                }

                if (aname.Version != null || aname.Culture != null || aname.ProcessorArchitecture != ProcessorArchitecture.None)
                {
                    Report.Error(1725, a.Location,
                                 "Friend assembly reference `{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture or processor architecture specified",
                                 assembly_name);

                    return;
                }

                if (public_key != null && !aname.HasPublicKey)
                {
                    Report.Error(1726, a.Location,
                                 "Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations",
                                 assembly_name);
                    return;
                }
#endif
            }
            else if (a.Type == pa.RuntimeCompatibility)
            {
                wrap_non_exception_throws_custom = true;
            }
            else if (a.Type == pa.AssemblyFileVersion)
            {
                string value = a.GetString();
                if (string.IsNullOrEmpty(value) || IsValidAssemblyVersion(value, false) == null)
                {
                    Report.Warning(1607, 1, a.Location, "The version number `{0}' specified for `{1}' is invalid",
                                   value, a.Name);
                    return;
                }
            }


            SetCustomAttribute(ctor, cdata);
        }
Exemple #22
0
        void EmitFieldSize(int buffer_size)
        {
            int type_size = BuiltinTypeSpec.GetSize(MemberType);

            if (buffer_size > int.MaxValue / type_size)
            {
                Report.Error(1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
                             GetSignatureForError(), buffer_size.ToString(), TypeManager.CSharpName(MemberType));
                return;
            }

            AttributeEncoder encoder;

            var ctor = Module.PredefinedMembers.StructLayoutAttributeCtor.Resolve(Location);

            if (ctor == null)
            {
                return;
            }

            var field_size    = Module.PredefinedMembers.StructLayoutSize.Resolve(Location);
            var field_charset = Module.PredefinedMembers.StructLayoutCharSet.Resolve(Location);

            if (field_size == null || field_charset == null)
            {
                return;
            }

            var char_set = CharSet ?? Module.DefaultCharSet ?? 0;

            encoder = new AttributeEncoder();
            encoder.Encode((short)LayoutKind.Sequential);
            encoder.EncodeNamedArguments(
                new [] { field_size, field_charset },
                new Constant [] {
                new IntConstant(Compiler.BuiltinTypes, buffer_size * type_size, Location),
                new IntConstant(Compiler.BuiltinTypes, (int)char_set, Location)
            }
                );

            fixed_buffer_type.SetCustomAttribute((ConstructorInfo)ctor.GetMetaInfo(), encoder.ToArray());

            //
            // Don't emit FixedBufferAttribute attribute for private types
            //
            if ((ModFlags & Modifiers.PRIVATE) != 0)
            {
                return;
            }

            ctor = Module.PredefinedMembers.FixedBufferAttributeCtor.Resolve(Location);
            if (ctor == null)
            {
                return;
            }

            encoder = new AttributeEncoder();
            encoder.EncodeTypeName(MemberType);
            encoder.Encode(buffer_size);
            encoder.EncodeEmptyNamedArguments();

            FieldBuilder.SetCustomAttribute((ConstructorInfo)ctor.GetMetaInfo(), encoder.ToArray());
        }
Exemple #23
0
        /// <summary>
        ///   Verifies that any pending abstract methods or interface methods
        ///   were implemented.
        /// </summary>
        public bool VerifyPendingMethods()
        {
            int  top    = pending_implementations.Length;
            bool errors = false;
            int  i;

            for (i = 0; i < top; i++)
            {
                Type type = pending_implementations [i].type;
                int  j    = 0;

                bool base_implements_type = type.IsInterface &&
                                            container.TypeBuilder.BaseType != null &&
                                            TypeManager.ImplementsInterface(container.TypeBuilder.BaseType, type);

                foreach (MethodInfo mi in pending_implementations[i].methods)
                {
                    if (mi == null)
                    {
                        continue;
                    }

                    if (type.IsInterface)
                    {
                        MethodInfo need_proxy =
                            pending_implementations [i].need_proxy [j];

                        if (need_proxy != null)
                        {
                            DefineProxy(type, need_proxy, mi, TypeManager.GetParameterData(mi));
                            continue;
                        }

                        if (pending_implementations [i].optional)
                        {
                            continue;
                        }

                        MethodInfo candidate = null;
                        if (base_implements_type || BaseImplements(type, mi, out candidate))
                        {
                            continue;
                        }

                        if (candidate == null)
                        {
                            MethodData md = pending_implementations [i].found [j];
                            if (md != null)
                            {
                                candidate = md.MethodBuilder;
                            }
                        }

                        Report.SymbolRelatedToPreviousError(mi);
                        if (candidate != null)
                        {
                            Report.SymbolRelatedToPreviousError(candidate);
                            if (candidate.IsStatic)
                            {
                                Report.Error(736, container.Location,
                                             "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' is static",
                                             container.GetSignatureForError(), TypeManager.CSharpSignature(mi, true), TypeManager.CSharpSignature(candidate));
                            }
                            else if (!candidate.IsPublic)
                            {
                                Report.Error(737, container.Location,
                                             "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' in not public",
                                             container.GetSignatureForError(), TypeManager.CSharpSignature(mi, true), TypeManager.CSharpSignature(candidate, true));
                            }
                            else
                            {
                                Report.Error(738, container.Location,
                                             "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' return type `{3}' does not match interface member return type `{4}'",
                                             container.GetSignatureForError(), TypeManager.CSharpSignature(mi, true), TypeManager.CSharpSignature(candidate),
                                             TypeManager.CSharpName(candidate.ReturnType), TypeManager.CSharpName(mi.ReturnType));
                            }
                        }
                        else
                        {
                            Report.Error(535, container.Location, "`{0}' does not implement interface member `{1}'",
                                         container.GetSignatureForError(), TypeManager.CSharpSignature(mi, true));
                        }
                    }
                    else
                    {
                        Report.Error(534, container.Location, "`{0}' does not implement inherited abstract member `{1}'",
                                     container.GetSignatureForError(), TypeManager.CSharpSignature(mi, true));
                    }
                    errors = true;
                    j++;
                }
            }
            return(errors);
        }
Exemple #24
0
        protected override Expression DoResolve(ResolveContext ec)
        {
            constructor_method = Delegate.GetConstructor(type);

            var invoke_method = Delegate.GetInvokeMethod(type);

            Arguments arguments = CreateDelegateMethodArguments(invoke_method.Parameters, invoke_method.Parameters.Types, loc);

            method_group = method_group.OverloadResolve(ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
            if (method_group == null)
            {
                return(null);
            }

            var delegate_method = method_group.BestCandidate;

            if (delegate_method.DeclaringType.IsNullableType)
            {
                ec.Report.Error(1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
                                delegate_method.GetSignatureForError());
                return(null);
            }

            Invocation.IsSpecialMethodInvocation(ec, delegate_method, loc);

            ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;

            if (emg != null)
            {
                method_group.InstanceExpression = emg.ExtensionExpression;
                TypeSpec e_type = emg.ExtensionExpression.Type;
                if (TypeManager.IsValueType(e_type))
                {
                    ec.Report.Error(1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
                                    delegate_method.GetSignatureForError(), TypeManager.CSharpName(e_type));
                }
            }

            TypeSpec rt = delegate_method.ReturnType;

            if (!Delegate.IsTypeCovariant(ec, rt, invoke_method.ReturnType))
            {
                Expression ret_expr = new TypeExpression(rt, loc);
                Error_ConversionFailed(ec, delegate_method, ret_expr);
            }

            if (delegate_method.IsConditionallyExcluded(ec.Module.Compiler, loc))
            {
                ec.Report.SymbolRelatedToPreviousError(delegate_method);
                MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
                if (m != null && m.IsPartialDefinition)
                {
                    ec.Report.Error(762, loc, "Cannot create delegate from partial method declaration `{0}'",
                                    delegate_method.GetSignatureForError());
                }
                else
                {
                    ec.Report.Error(1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
                                    TypeManager.CSharpSignature(delegate_method));
                }
            }

            var expr = method_group.InstanceExpression;

            if (expr != null && (expr.Type.IsGenericParameter || !TypeManager.IsReferenceType(expr.Type)))
            {
                method_group.InstanceExpression = new BoxedCast(expr, ec.BuiltinTypes.Object);
            }

            eclass = ExprClass.Value;
            return(this);
        }
        void EmitFieldSize(int buffer_size)
        {
            int type_size = Expression.GetTypeSize(MemberType);

            if (buffer_size > int.MaxValue / type_size)
            {
                Report.Error(1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
                             GetSignatureForError(), buffer_size.ToString(), TypeManager.CSharpName(MemberType));
                return;
            }

            PredefinedAttribute pa;
            AttributeEncoder    encoder;

            pa = Module.PredefinedAttributes.StructLayout;
            if (pa.Constructor == null && !pa.ResolveConstructor(Location, TypeManager.short_type))
            {
                return;
            }

            var char_set_type = Module.PredefinedTypes.CharSet.Resolve(Location);

            if (char_set_type == null)
            {
                return;
            }

            var field_size    = pa.GetField("Size", TypeManager.int32_type, Location);
            var field_charset = pa.GetField("CharSet", char_set_type, Location);

            if (field_size == null || field_charset == null)
            {
                return;
            }

            var char_set = CharSet ?? Module.DefaultCharSet;

            encoder = new AttributeEncoder();
            encoder.Encode((short)LayoutKind.Sequential);
            encoder.EncodeNamedArguments(
                new [] { field_size, field_charset },
                new Constant [] { new IntConstant(buffer_size * type_size, Location), new IntConstant((int)char_set, Location) }
                );

            pa.EmitAttribute(fixed_buffer_type, encoder);

            //
            // Don't emit FixedBufferAttribute attribute for private types
            //
            if ((ModFlags & Modifiers.PRIVATE) != 0)
            {
                return;
            }

            pa = Module.PredefinedAttributes.FixedBuffer;
            if (pa.Constructor == null && !pa.ResolveConstructor(Location, TypeManager.type_type, TypeManager.int32_type))
            {
                return;
            }

            encoder = new AttributeEncoder();
            encoder.EncodeTypeName(MemberType);
            encoder.Encode(buffer_size);
            encoder.EncodeEmptyNamedArguments();

            pa.EmitAttribute(FieldBuilder, encoder);
        }
        public static void CreateIterator(IMethodData method, TypeContainer parent, int modifiers)
        {
            bool is_enumerable;
            Type iterator_type;

            Type ret = method.ReturnType;

            if (ret == null)
            {
                return;
            }

            if (!CheckType(ret, out iterator_type, out is_enumerable))
            {
                Report.Error(1624, method.Location,
                             "The body of `{0}' cannot be an iterator block " +
                             "because `{1}' is not an iterator interface type",
                             method.GetSignatureForError(),
                             TypeManager.CSharpName(ret));
                return;
            }

            Parameters parameters = method.ParameterInfo;

            for (int i = 0; i < parameters.Count; i++)
            {
                Parameter          p   = parameters [i];
                Parameter.Modifier mod = p.ModFlags;
                if ((mod & Parameter.Modifier.ISBYREF) != 0)
                {
                    Report.Error(1623, p.Location,
                                 "Iterators cannot have ref or out parameters");
                    return;
                }

                if ((mod & Parameter.Modifier.ARGLIST) != 0)
                {
                    Report.Error(1636, method.Location,
                                 "__arglist is not allowed in parameter list of iterators");
                    return;
                }

                if (parameters.Types [i].IsPointer)
                {
                    Report.Error(1637, p.Location,
                                 "Iterators cannot have unsafe parameters or " +
                                 "yield types");
                    return;
                }
            }

            if ((modifiers & Modifiers.UNSAFE) != 0)
            {
                Report.Error(1629, method.Location, "Unsafe code may not appear in iterators");
                return;
            }

            Iterator iter = new Iterator(method, parent, iterator_type, is_enumerable);

            iter.Storey.DefineType();
        }
Exemple #27
0
        protected override bool DoDefineMembers()
        {
            var builtin_types = Compiler.BuiltinTypes;

            var ctor_parameters = ParametersCompiled.CreateFullyResolved(
                new [] {
                new Parameter(new TypeExpression(builtin_types.Object, Location), "object", Parameter.Modifier.NONE, null, Location),
                new Parameter(new TypeExpression(builtin_types.IntPtr, Location), "method", Parameter.Modifier.NONE, null, Location)
            },
                new [] {
                builtin_types.Object,
                builtin_types.IntPtr
            }
                );

            Constructor = new Constructor(this, Constructor.ConstructorName,
                                          Modifiers.PUBLIC, null, ctor_parameters, null, Location);
            Constructor.Define();

            //
            // Here the various methods like Invoke, BeginInvoke etc are defined
            //
            // First, call the `out of band' special method for
            // defining recursively any types we need:
            //
            var p = parameters;

            if (!p.Resolve(this))
            {
                return(false);
            }

            //
            // Invoke method
            //

            // Check accessibility
            foreach (var partype in p.Types)
            {
                if (!IsAccessibleAs(partype))
                {
                    Report.SymbolRelatedToPreviousError(partype);
                    Report.Error(59, Location,
                                 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
                                 TypeManager.CSharpName(partype), GetSignatureForError());
                }
            }

            ReturnType = ReturnType.ResolveAsTypeTerminal(this, false);
            if (ReturnType == null)
            {
                return(false);
            }

            var ret_type = ReturnType.Type;

            //
            // We don't have to check any others because they are all
            // guaranteed to be accessible - they are standard types.
            //
            if (!IsAccessibleAs(ret_type))
            {
                Report.SymbolRelatedToPreviousError(ret_type);
                Report.Error(58, Location,
                             "Inconsistent accessibility: return type `" +
                             TypeManager.CSharpName(ret_type) + "' is less " +
                             "accessible than delegate `" + GetSignatureForError() + "'");
                return(false);
            }

            CheckProtectedModifier();

            if (Compiler.Settings.StdLib && ret_type.IsSpecialRuntimeType)
            {
                Method.Error1599(Location, ret_type, Report);
                return(false);
            }

            TypeManager.CheckTypeVariance(ret_type, Variance.Covariant, this);

            InvokeBuilder = new Method(this, null, ReturnType, MethodModifiers, new MemberName(InvokeMethodName), p, null);
            InvokeBuilder.Define();

            //
            // Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
            //
            if (!IsCompilerGenerated)
            {
                DefineAsyncMethods(Parameters.CallingConvention);
            }

            return(true);
        }
Exemple #28
0
        public override Expression DoResolve(ResolveContext ec)
        {
            constructor_method = Delegate.GetConstructor(ec.Compiler, ec.CurrentType, type);

            MethodInfo invoke_method = Delegate.GetInvokeMethod(ec.Compiler, ec.CurrentType, type);

            method_group.DelegateType       = type;
            method_group.CustomErrorHandler = this;

            Arguments arguments = CreateDelegateMethodArguments(TypeManager.GetParameterData(invoke_method), loc);

            method_group = method_group.OverloadResolve(ec, ref arguments, false, loc);
            if (method_group == null)
            {
                return(null);
            }

            delegate_method = (MethodInfo)method_group;

            if (TypeManager.IsNullableType(delegate_method.DeclaringType))
            {
                ec.Report.Error(1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
                                TypeManager.GetFullNameSignature(delegate_method));
                return(null);
            }

            Invocation.IsSpecialMethodInvocation(ec, delegate_method, loc);

            ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;

            if (emg != null)
            {
                delegate_instance_expression = emg.ExtensionExpression;
                Type e_type = delegate_instance_expression.Type;
                if (TypeManager.IsValueType(e_type))
                {
                    ec.Report.Error(1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
                                    TypeManager.CSharpSignature(delegate_method), TypeManager.CSharpName(e_type));
                }
            }

            Type       rt       = TypeManager.TypeToCoreType(delegate_method.ReturnType);
            Expression ret_expr = new TypeExpression(rt, loc);

            if (!Delegate.IsTypeCovariant(ret_expr, (TypeManager.TypeToCoreType(invoke_method.ReturnType))))
            {
                Error_ConversionFailed(ec, delegate_method, ret_expr);
            }

            if (Invocation.IsMethodExcluded(delegate_method, loc))
            {
                ec.Report.SymbolRelatedToPreviousError(delegate_method);
                MethodOrOperator m = TypeManager.GetMethod(delegate_method) as MethodOrOperator;
                if (m != null && m.IsPartialDefinition)
                {
                    ec.Report.Error(762, loc, "Cannot create delegate from partial method declaration `{0}'",
                                    TypeManager.CSharpSignature(delegate_method));
                }
                else
                {
                    ec.Report.Error(1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
                                    TypeManager.CSharpSignature(delegate_method));
                }
            }

            DoResolveInstanceExpression(ec);
            eclass = ExprClass.Value;
            return(this);
        }
Exemple #29
0
 public static void Error_ConstantCanBeInitializedWithNullOnly(Type type, Location loc, string name, Report Report)
 {
     Report.Error(134, loc, "A constant `{0}' of reference type `{1}' can only be initialized with null",
                  name, TypeManager.CSharpName(type));
 }
Exemple #30
0
        protected override bool DoDefineMembers()
        {
            if (IsGeneric)
            {
                foreach (TypeParameter type_param in TypeParameters)
                {
                    if (!type_param.Resolve(this))
                    {
                        return(false);
                    }
                }

                foreach (TypeParameter type_param in TypeParameters)
                {
                    if (!type_param.DefineType(this))
                    {
                        return(false);
                    }
                }
            }

            member_cache = new MemberCache(TypeManager.multicast_delegate_type, this);

            // FIXME: POSSIBLY make this static, as it is always constant
            //
            Type [] const_arg_types = new Type [2];
            const_arg_types [0] = TypeManager.object_type;
            const_arg_types [1] = TypeManager.intptr_type;

            const MethodAttributes ctor_mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
                                                MethodAttributes.HideBySig | MethodAttributes.Public;

            ConstructorBuilder = TypeBuilder.DefineConstructor(ctor_mattr,
                                                               CallingConventions.Standard,
                                                               const_arg_types);

            ConstructorBuilder.DefineParameter(1, ParameterAttributes.None, "object");
            ConstructorBuilder.DefineParameter(2, ParameterAttributes.None, "method");
            //
            // HACK because System.Reflection.Emit is lame
            //
            IParameterData [] fixed_pars = new IParameterData [] {
                new ParameterData("object", Parameter.Modifier.NONE),
                new ParameterData("method", Parameter.Modifier.NONE)
            };

            AParametersCollection const_parameters = new ParametersImported(
                fixed_pars,
                new Type[] { TypeManager.object_type, TypeManager.intptr_type });

            TypeManager.RegisterMethod(ConstructorBuilder, const_parameters);
            member_cache.AddMember(ConstructorBuilder, this);

            ConstructorBuilder.SetImplementationFlags(MethodImplAttributes.Runtime);

            //
            // Here the various methods like Invoke, BeginInvoke etc are defined
            //
            // First, call the `out of band' special method for
            // defining recursively any types we need:

            if (!Parameters.Resolve(this))
            {
                return(false);
            }

            //
            // Invoke method
            //

            // Check accessibility
            foreach (Type partype in Parameters.Types)
            {
                if (!IsAccessibleAs(partype))
                {
                    Report.SymbolRelatedToPreviousError(partype);
                    Report.Error(59, Location,
                                 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
                                 TypeManager.CSharpName(partype),
                                 GetSignatureForError());
                    return(false);
                }
            }

            ReturnType = ReturnType.ResolveAsTypeTerminal(this, false);
            if (ReturnType == null)
            {
                return(false);
            }

            ret_type = ReturnType.Type;

            if (!IsAccessibleAs(ret_type))
            {
                Report.SymbolRelatedToPreviousError(ret_type);
                Report.Error(58, Location,
                             "Inconsistent accessibility: return type `" +
                             TypeManager.CSharpName(ret_type) + "' is less " +
                             "accessible than delegate `" + GetSignatureForError() + "'");
                return(false);
            }

            CheckProtectedModifier();

            if (RootContext.StdLib && TypeManager.IsSpecialType(ret_type))
            {
                Method.Error1599(Location, ret_type, Report);
                return(false);
            }

            TypeManager.CheckTypeVariance(ret_type, Variance.Covariant, this);

            //
            // We don't have to check any others because they are all
            // guaranteed to be accessible - they are standard types.
            //

            CallingConventions cc = Parameters.CallingConvention;

            InvokeBuilder = TypeBuilder.DefineMethod("Invoke",
                                                     mattr,
                                                     cc,
                                                     ret_type,
                                                     Parameters.GetEmitTypes());

            InvokeBuilder.SetImplementationFlags(MethodImplAttributes.Runtime);

            TypeManager.RegisterMethod(InvokeBuilder, Parameters);
            member_cache.AddMember(InvokeBuilder, this);

            //
            // Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
            //
            if (TypeManager.iasyncresult_type != null && TypeManager.asynccallback_type != null && !IsCompilerGenerated)
            {
                DefineAsyncMethods(cc);
            }

            return(true);
        }