Error() public méthode

public Error ( int code, Mono.CSharp.Location loc, string error ) : void
code int
loc Mono.CSharp.Location
error string
Résultat void
Exemple #1
0
 public static void Error_InvalidConstantType(TypeSpec t, Location loc, Report Report)
 {
     if (t.IsGenericParameter) {
         Report.Error (1959, loc,
             "Type parameter `{0}' cannot be declared const", TypeManager.CSharpName (t));
     } else {
         Report.Error (283, loc,
             "The type `{0}' cannot be declared const", TypeManager.CSharpName (t));
     }
 }
Exemple #2
0
        static public void Save(string name, bool saveDebugInfo, Report Report)
        {
#if GMCS_SOURCE
            PortableExecutableKinds pekind;
            ImageFileMachine        machine;

            switch (RootContext.Platform)
            {
            case Platform.X86:
                pekind  = PortableExecutableKinds.Required32Bit;
                machine = ImageFileMachine.I386;
                break;

            case Platform.X64:
                pekind  = PortableExecutableKinds.PE32Plus;
                machine = ImageFileMachine.AMD64;
                break;

            case Platform.IA64:
                pekind  = PortableExecutableKinds.PE32Plus;
                machine = ImageFileMachine.IA64;
                break;

            case Platform.AnyCPU:
            default:
                pekind  = PortableExecutableKinds.ILOnly;
                machine = ImageFileMachine.I386;
                break;
            }
#endif
            try {
#if GMCS_SOURCE
                Assembly.Builder.Save(Basename(name), pekind, machine);
#else
                Assembly.Builder.Save(Basename(name));
#endif
            }
            catch (COMException) {
                if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
                {
                    throw;
                }

                // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
                Report.Error(1548, "Couldn't delay-sign the assembly with the '" +
                             RootContext.StrongNameKeyFile +
                             "', Use MCS with the Mono runtime or CSC to compile this assembly.");
            }
            catch (System.IO.IOException io) {
                Report.Error(16, "Could not write to file `" + name + "', cause: " + io.Message);
                return;
            }
            catch (System.UnauthorizedAccessException ua) {
                Report.Error(16, "Could not write to file `" + name + "', cause: " + ua.Message);
                return;
            }
            catch (System.NotImplementedException nie) {
                Report.RuntimeMissingSupport(Location.Null, nie.Message);
                return;
            }

            //
            // Write debuger symbol file
            //
            if (saveDebugInfo)
            {
                SymbolWriter.WriteSymbolFile();
            }
        }
 public static void Error_GlobalNamespaceRedefined(Report report, Location loc)
 {
     report.Error (1681, loc, "The global extern alias cannot be redefined");
 }
Exemple #4
0
	static void Error_FriendAccessNameNotMatching (string other_name, Report Report)
	{
		Report.Error (281,
			"Friend access was granted to `{0}', but the output assembly is named `{1}'. Try adding a reference to `{0}' or change the output assembly name to match it",
			other_name, CodeGen.Assembly.Name.FullName);
	}
		public override void Error_NamespaceDoesNotExist (Location loc, string name, Report Report)
		{
			Report.Error (400, loc, "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
				name);
		}
		public bool CheckExistingMembersOverloads (MemberCore member, string name, ParametersCompiled parameters, Report Report)
		{
			ArrayList entries = (ArrayList)member_hash [name];
			if (entries == null)
				return true;

			int method_param_count = parameters.Count;
			for (int i = entries.Count - 1; i >= 0; --i) {
				CacheEntry ce = (CacheEntry) entries [i];

				if (ce.Container != member.Parent.PartialContainer)
					return true;

				Type [] p_types;
				AParametersCollection pd;
				if ((ce.EntryType & EntryType.Property) != 0) {
					pd = TypeManager.GetParameterData ((PropertyInfo) ce.Member);
					p_types = pd.Types;
				} else {
					MethodBase mb = (MethodBase) ce.Member;
		
					// TODO: This is more like a hack, because we are adding generic methods
					// twice with and without arity name
					if (TypeManager.IsGenericMethod (mb) && !member.MemberName.IsGeneric)
						continue;

					pd = TypeManager.GetParameterData (mb);
					p_types = pd.Types;
				}

				if (p_types.Length != method_param_count)
					continue;

				if (method_param_count > 0) {
					int ii = method_param_count - 1;
					Type type_a, type_b;
					do {
						type_a = parameters.Types [ii];
						type_b = p_types [ii];

#if GMCS_SOURCE
						if (TypeManager.IsGenericParameter (type_a) && type_a.DeclaringMethod != null)
							type_a = typeof (TypeParameter);

						if (TypeManager.IsGenericParameter (type_b) && type_b.DeclaringMethod != null)
							type_b = typeof (TypeParameter);
#endif
						if ((pd.FixedParameters [ii].ModFlags & Parameter.Modifier.ISBYREF) !=
							(parameters.FixedParameters [ii].ModFlags & Parameter.Modifier.ISBYREF))
							type_a = null;

					} while (type_a == type_b && ii-- != 0);

					if (ii >= 0)
						continue;

					//
					// Operators can differ in return type only
					//
					if (member is Operator) {
						Operator op = TypeManager.GetMethod ((MethodBase) ce.Member) as Operator;
						if (op != null && op.ReturnType != ((Operator) member).ReturnType)
							continue;
					}

					//
					// Report difference in parameter modifiers only
					//
					if (pd != null && member is MethodCore) {
						ii = method_param_count;
						while (ii-- != 0 && parameters.FixedParameters [ii].ModFlags == pd.FixedParameters [ii].ModFlags &&
							parameters.ExtensionMethodType == pd.ExtensionMethodType);

						if (ii >= 0) {
							MethodCore mc = TypeManager.GetMethod ((MethodBase) ce.Member) as MethodCore;
							Report.SymbolRelatedToPreviousError (ce.Member);
							if ((member.ModFlags & Modifiers.PARTIAL) != 0 && (mc.ModFlags & Modifiers.PARTIAL) != 0) {
								if (parameters.HasParams || pd.HasParams) {
									Report.Error (758, member.Location,
										"A partial method declaration and partial method implementation cannot differ on use of `params' modifier");
								} else {
									Report.Error (755, member.Location,
										"A partial method declaration and partial method implementation must be both an extension method or neither");
								}
							} else {
								if (member is Constructor) {
									Report.Error (851, member.Location,
										"Overloaded contructor `{0}' cannot differ on use of parameter modifiers only",
										member.GetSignatureForError ());
								} else {
									Report.Error (663, member.Location,
										"Overloaded method `{0}' cannot differ on use of parameter modifiers only",
										member.GetSignatureForError ());
								}
							}
							return false;
						}
					}
				}

				if ((ce.EntryType & EntryType.Method) != 0) {
					Method method_a = member as Method;
					Method method_b = TypeManager.GetMethod ((MethodBase) ce.Member) as Method;
					if (method_a != null && method_b != null && (method_a.ModFlags & method_b.ModFlags & Modifiers.PARTIAL) != 0) {
						const int partial_modifiers = Modifiers.STATIC | Modifiers.UNSAFE;
						if (method_a.IsPartialDefinition == method_b.IsPartialImplementation) {
							if ((method_a.ModFlags & partial_modifiers) == (method_b.ModFlags & partial_modifiers) ||
								method_a.Parent.IsUnsafe && method_b.Parent.IsUnsafe) {
								if (method_a.IsPartialImplementation) {
									method_a.SetPartialDefinition (method_b);
									entries.RemoveAt (i);
								} else {
									method_b.SetPartialDefinition (method_a);
								}
								continue;
							}

							if ((method_a.ModFlags & Modifiers.STATIC) != (method_b.ModFlags & Modifiers.STATIC)) {
								Report.SymbolRelatedToPreviousError (ce.Member);
								Report.Error (763, member.Location,
									"A partial method declaration and partial method implementation must be both `static' or neither");
							}

							Report.SymbolRelatedToPreviousError (ce.Member);
							Report.Error (764, member.Location,
								"A partial method declaration and partial method implementation must be both `unsafe' or neither");
							return false;
						}

						Report.SymbolRelatedToPreviousError (ce.Member);
						if (method_a.IsPartialDefinition) {
							Report.Error (756, member.Location, "A partial method `{0}' declaration is already defined",
								member.GetSignatureForError ());
						}

						Report.Error (757, member.Location, "A partial method `{0}' implementation is already defined",
							member.GetSignatureForError ());
						return false;
					}

					Report.SymbolRelatedToPreviousError (ce.Member);
					IMethodData duplicate_member = TypeManager.GetMethod ((MethodBase) ce.Member);
					if (member is Operator && duplicate_member is Operator) {
						Report.Error (557, member.Location, "Duplicate user-defined conversion in type `{0}'",
							member.Parent.GetSignatureForError ());
						return false;
					}

					bool is_reserved_a = member is AbstractPropertyEventMethod || member is Operator;
					bool is_reserved_b = duplicate_member is AbstractPropertyEventMethod || duplicate_member is Operator;

					if (is_reserved_a || is_reserved_b) {
						Report.Error (82, member.Location, "A member `{0}' is already reserved",
							is_reserved_a ?
							TypeManager.GetFullNameSignature (ce.Member) :
							member.GetSignatureForError ());
						return false;
					}
				} else {
					Report.SymbolRelatedToPreviousError (ce.Member);
				}
				
				Report.Error (111, member.Location,
					"A member `{0}' is already defined. Rename this member or use different parameter types",
					member.GetSignatureForError ());
				return false;
			}

			return true;
		}
Exemple #7
0
 //
 // Outputs XML documentation comment from tokenized comments.
 //
 public bool OutputDocComment(string asmfilename, Report Report)
 {
     XmlTextWriter w = null;
     try {
         w = new XmlTextWriter (docfilename, null);
         w.Indentation = 4;
         w.Formatting = Formatting.Indented;
         w.WriteStartDocument ();
         w.WriteStartElement ("doc");
         w.WriteStartElement ("assembly");
         w.WriteStartElement ("name");
         w.WriteString (Path.ChangeExtension (asmfilename, null));
         w.WriteEndElement (); // name
         w.WriteEndElement (); // assembly
         w.WriteStartElement ("members");
         XmlCommentOutput = w;
         GenerateDocComment (Report);
         w.WriteFullEndElement (); // members
         w.WriteEndElement ();
         w.WriteWhitespace (Environment.NewLine);
         w.WriteEndDocument ();
         return true;
     } catch (Exception ex) {
         Report.Error (1569, "Error generating XML documentation file `{0}' (`{1}')", docfilename, ex.Message);
         return false;
     } finally {
         if (w != null)
             w.Close ();
     }
 }
Exemple #8
0
		/// <summary>
		/// Common method for Obsolete error/warning reporting.
		/// </summary>
		public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc, Report Report)
		{
			if (oa.IsError) {
				Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
				return;
			}

			if (oa.Message == null || oa.Message.Length == 0) {
				Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
				return;
			}
			Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
		}
Exemple #9
0
        public void EmbedResources()
        {
            //
            // Add Win32 resources
            //
            if (Compiler.Settings.Win32ResourceFile != null)
            {
                Builder.DefineUnmanagedResource(Compiler.Settings.Win32ResourceFile);
            }
            else
            {
                Builder.DefineVersionInfoResource(vi_product, vi_product_version, vi_company, vi_copyright, vi_trademark);
            }

            if (Compiler.Settings.Win32IconFile != null)
            {
                builder_extra.DefineWin32IconResource(Compiler.Settings.Win32IconFile);
            }

            if (Compiler.Settings.Resources != null)
            {
                if (Compiler.Settings.Target == Target.Module)
                {
                    Report.Error(1507, "Cannot link resource file when building a module");
                }
                else
                {
                    int counter = 0;
                    foreach (var res in Compiler.Settings.Resources)
                    {
                        if (!File.Exists(res.FileName))
                        {
                            Report.Error(1566, "Error reading resource file `{0}'", res.FileName);
                            continue;
                        }

                        if (res.IsEmbeded)
                        {
                            Stream stream;
                            if (counter++ < 10)
                            {
                                stream = File.OpenRead(res.FileName);
                            }
                            else
                            {
                                // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
                                // we workaround it by reading everything into memory to compile projects with
                                // many embedded resource (over 3500) references
                                stream = new MemoryStream(File.ReadAllBytes(res.FileName));
                            }

                            module.Builder.DefineManifestResource(res.Name, stream, res.Attributes);
                        }
                        else
                        {
                            Builder.AddResourceFile(res.Name, Path.GetFileName(res.FileName), res.Attributes);
                        }
                    }
                }
            }
        }
Exemple #10
0
        public void Resolve()
        {
            if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define())
            {
                //
                // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
                // when -unsafe option was specified
                //
                Location loc = Location.Null;

                MemberAccess system_security_permissions = new MemberAccess(new MemberAccess(
                                                                                new QualifiedAliasMember(QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);

                var req_min = module.PredefinedMembers.SecurityActionRequestMinimum.Resolve(loc);

                Arguments pos = new Arguments(1);
                pos.Add(new Argument(req_min.GetConstant(null)));

                Arguments named = new Arguments(1);
                named.Add(new NamedArgument("SkipVerification", loc, new BoolLiteral(Compiler.BuiltinTypes, true, loc)));

                Attribute g = new Attribute("assembly",
                                            new MemberAccess(system_security_permissions, "SecurityPermissionAttribute"),
                                            new Arguments[] { pos, named }, loc, false);
                g.AttachTo(module, module);

                // Disable no-location warnings (e.g. obsolete) for compiler generated attribute
                Compiler.Report.DisableReporting();
                try {
                    var ctor = g.Resolve();
                    if (ctor != null)
                    {
                        g.ExtractSecurityPermissionSet(ctor, ref declarative_security);
                    }
                } finally {
                    Compiler.Report.EnableReporting();
                }
            }

            if (module.OptAttributes == null)
            {
                return;
            }

            // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
            if (!module.OptAttributes.CheckTargets())
            {
                return;
            }

            cls_attribute = module.ResolveAssemblyAttribute(module.PredefinedAttributes.CLSCompliant);

            if (cls_attribute != null)
            {
                is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue();
            }

            if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant)
            {
                foreach (var m in added_modules)
                {
                    if (!m.IsCLSCompliant)
                    {
                        Report.Error(3013,
                                     "Added modules must be marked with the CLSCompliant attribute to match the assembly",
                                     m.Name);
                    }
                }
            }

            Attribute a = module.ResolveAssemblyAttribute(module.PredefinedAttributes.RuntimeCompatibility);

            if (a != null)
            {
                var val = a.GetNamedValue("WrapNonExceptionThrows") as BoolConstant;
                if (val != null)
                {
                    wrap_non_exception_throws = val.Value;
                }
            }
        }
Exemple #11
0
 static void Error_664(Location loc, string type, string suffix)
 {
     Report.Error(664, loc,
                  "Literal of type double cannot be implicitly converted to type `{0}'. Add suffix `{1}' to create a literal of this type",
                  type, suffix);
 }
Exemple #12
0
		public CompilerSettings ParseArguments (string[] args)
		{
			CompilerSettings settings = new CompilerSettings ();
			List<string> response_file_list = null;
			bool parsing_options = true;
			stop_argument = false;
			source_file_index = new Dictionary<string, int> ();

			for (int i = 0; i < args.Length; i++) {
				string arg = args[i];
				if (arg.Length == 0)
					continue;

				if (arg[0] == '@') {
					string[] extra_args;
					string response_file = arg.Substring (1);

					if (response_file_list == null)
						response_file_list = new List<string> ();

					if (response_file_list.Contains (response_file)) {
						report.Error (1515, "Response file `{0}' specified multiple times", response_file);
						return null;
					}

					response_file_list.Add (response_file);

					extra_args = LoadArgs (response_file);
					if (extra_args == null) {
						report.Error (2011, "Unable to open response file: " + response_file);
						return null;
					}

					args = AddArgs (args, extra_args);
					continue;
				}

				if (parsing_options) {
					if (arg == "--") {
						parsing_options = false;
						continue;
					}

					bool dash_opt = arg[0] == '-';
					bool slash_opt = arg[0] == '/';
					if (dash_opt) {
						switch (ParseOptionUnix (arg, ref args, ref i, settings)) {
						case ParseResult.Error:
						case ParseResult.Success:
							continue;
						case ParseResult.Stop:
							stop_argument = true;
							return settings;
						case ParseResult.UnknownOption:
							if (UnknownOptionHandler != null) {
								var ret = UnknownOptionHandler (args, i);
								if (ret != -1) {
									i = ret;
									continue;
								}
							}
							break;
						}
					}

					if (dash_opt || slash_opt) {
						// Try a -CSCOPTION
						string csc_opt = dash_opt ? "/" + arg.Substring (1) : arg;
						switch (ParseOption (csc_opt, ref args, settings)) {
						case ParseResult.Error:
						case ParseResult.Success:
							continue;
						case ParseResult.UnknownOption:
							// Need to skip `/home/test.cs' however /test.cs is considered as error
							if ((slash_opt && arg.Length > 3 && arg.IndexOf ('/', 2) > 0))
								break;

							if (UnknownOptionHandler != null) {
								var ret = UnknownOptionHandler (args, i);
								if (ret != -1) {
									i = ret;
									continue;
								}
							}

							Error_WrongOption (arg);
							return null;

						case ParseResult.Stop:
							stop_argument = true;
							return settings;
						}
					}
				}

				ProcessSourceFiles (arg, false, settings.SourceFiles);
			}

			return settings;
		}
        public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
        {
            if (a.Type == TypeManager.in_attribute_type && ModFlags == Modifier.OUT)
            {
                Report.Error(36, a.Location, "An out parameter cannot have the `In' attribute");
                return;
            }

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

            if (a.Type == TypeManager.out_attribute_type && (ModFlags & Modifier.REF) == Modifier.REF &&
                TypeManager.in_attribute_type != null && !OptAttributes.Contains(TypeManager.in_attribute_type))
            {
                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 == TypeManager.cls_compliant_attribute_type)
            {
                Report.Warning(3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead");
            }

            // TypeManager.default_parameter_value_attribute_type is null if !NET_2_0, or if System.dll is not referenced
            if (a.Type == TypeManager.default_parameter_value_attribute_type)
            {
                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 DefaultValue attribute",
                                         TypeManager.CSharpName(t));
                        }
                        else
                        {
                            Report.Error(1909, a.Location, "The DefaultValue attribute is not applicable on parameters of type `{0}'",
                                         TypeManager.CSharpName(parameter_type));;
                        }
                        return;
                    }
                }

                if (parameter_type == TypeManager.object_type ||
                    (val == null && !TypeManager.IsValueType(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);
        }
 protected virtual void ErrorDuplicateName(Parameter p)
 {
     Report.Error(100, p.Location, "The parameter name `{0}' is a duplicate", p.Name);
 }
Exemple #15
0
        // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
        public AssemblyName GetAssemblyName(string name, string output)
        {
            if (OptAttributes != null)
            {
                foreach (Attribute a in OptAttributes.Attrs)
                {
                    // cannot rely on any resolve-based members before you call Resolve
                    if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
                    {
                        continue;
                    }

                    // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
                    //       However, this is invoked by CodeGen.Init, when none of the namespaces
                    //       are loaded yet.
                    // TODO: Does not handle quoted attributes properly
                    switch (a.Name)
                    {
                    case "AssemblyKeyFile":
                    case "AssemblyKeyFileAttribute":
                    case "System.Reflection.AssemblyKeyFileAttribute":
                        if (RootContext.StrongNameKeyFile != null)
                        {
                            Report.SymbolRelatedToPreviousError(a.Location, a.GetSignatureForError());
                            Report.Warning(1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
                                           "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
                        }
                        else
                        {
                            string value = a.GetString();
                            if (value != null && value.Length != 0)
                            {
                                RootContext.StrongNameKeyFile = value;
                            }
                        }
                        break;

                    case "AssemblyKeyName":
                    case "AssemblyKeyNameAttribute":
                    case "System.Reflection.AssemblyKeyNameAttribute":
                        if (RootContext.StrongNameKeyContainer != null)
                        {
                            Report.SymbolRelatedToPreviousError(a.Location, a.GetSignatureForError());
                            Report.Warning(1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
                                           "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
                        }
                        else
                        {
                            string value = a.GetString();
                            if (value != null && value.Length != 0)
                            {
                                RootContext.StrongNameKeyContainer = value;
                            }
                        }
                        break;

                    case "AssemblyDelaySign":
                    case "AssemblyDelaySignAttribute":
                    case "System.Reflection.AssemblyDelaySignAttribute":
                        RootContext.StrongNameDelaySign = a.GetBoolean();
                        break;
                    }
                }
            }

            AssemblyName an = new AssemblyName();

            an.Name = Path.GetFileNameWithoutExtension(name);

            // note: delay doesn't apply when using a key container
            if (RootContext.StrongNameKeyContainer != null)
            {
                an.KeyPair = new StrongNameKeyPair(RootContext.StrongNameKeyContainer);
                return(an);
            }

            // strongname is optional
            if (RootContext.StrongNameKeyFile == null)
            {
                return(an);
            }

            string AssemblyDir = Path.GetDirectoryName(output);

            // the StrongName key file may be relative to (a) the compiled
            // file or (b) to the output assembly. See bugzilla #55320
            // http://bugzilla.ximian.com/show_bug.cgi?id=55320

            // (a) relative to the compiled file
            string filename = Path.GetFullPath(RootContext.StrongNameKeyFile);
            bool   exist    = File.Exists(filename);

            if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty))
            {
                // (b) relative to the outputed assembly
                filename = Path.GetFullPath(Path.Combine(AssemblyDir, RootContext.StrongNameKeyFile));
                exist    = File.Exists(filename);
            }

            if (exist)
            {
                using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) {
                    byte[] snkeypair = new byte [fs.Length];
                    fs.Read(snkeypair, 0, snkeypair.Length);

                    if (RootContext.StrongNameDelaySign)
                    {
                        // delayed signing - DO NOT include private key
                        SetPublicKey(an, snkeypair);
                    }
                    else
                    {
                        // no delay so we make sure we have the private key
                        try {
                            CryptoConvert.FromCapiPrivateKeyBlob(snkeypair);
                            an.KeyPair = new StrongNameKeyPair(snkeypair);
                        }
                        catch (CryptographicException) {
                            if (snkeypair.Length == 16)
                            {
                                // error # is different for ECMA key
                                Report.Error(1606, "Could not sign the assembly. " +
                                             "ECMA key can only be used to delay-sign assemblies");
                            }
                            else
                            {
                                Error_AssemblySigning("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
                            }
                            return(null);
                        }
                    }
                }
            }
            else
            {
                Error_AssemblySigning("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
                return(null);
            }
            return(an);
        }
Exemple #16
0
        /// <summary>
        ///   Verifies that any pending abstract methods or interface methods
        ///   were implemented.
        /// </summary>
        public bool VerifyPendingMethods(Report Report)
        {
            int top = pending_implementations.Length;
            bool errors = false;
            int i;

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

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

                foreach (var mi in pending_implementations [i].methods){
                    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;
                    j++;
                }
            }
            return errors;
        }
Exemple #17
0
		public void Parse (SourceFile file, ModuleContainer module, ParserSession session, Report report)
		{
			Stream input;

			try {
				input = File.OpenRead (file.Name);
			} catch {
				report.Error (2001, "Source file `{0}' could not be found", file.Name);
				return;
			}

			// Check 'MZ' header
			if (input.ReadByte () == 77 && input.ReadByte () == 90) {

				report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
				input.Close ();
				return;
			}

			input.Position = 0;
			SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding, session.StreamReaderBuffer);

			Parse (reader, file, module, session, report);

			if (ctx.Settings.GenerateDebugInfo && report.Errors == 0 && !file.HasChecksum) {
				input.Position = 0;
				var checksum = session.GetChecksumAlgorithm ();
				file.SetChecksum (checksum.ComputeHash (input));
			}

			reader.Dispose ();
			input.Close ();
		}
Exemple #18
0
        public void Save()
        {
            PortableExecutableKinds pekind = PortableExecutableKinds.ILOnly;
            ImageFileMachine        machine;

            switch (Compiler.Settings.Platform)
            {
            case Platform.X86:
                pekind |= PortableExecutableKinds.Required32Bit;
                machine = ImageFileMachine.I386;
                break;

            case Platform.X64:
                pekind |= PortableExecutableKinds.PE32Plus;
                machine = ImageFileMachine.AMD64;
                break;

            case Platform.IA64:
                machine = ImageFileMachine.IA64;
                break;

            case Platform.AnyCPU32Preferred:
#if STATIC
                pekind |= PortableExecutableKinds.Preferred32Bit;
                machine = ImageFileMachine.I386;
                break;
#else
                throw new NotSupportedException();
#endif
            case Platform.Arm:
#if STATIC
                machine = ImageFileMachine.ARM;
                break;
#else
                throw new NotSupportedException();
#endif
            case Platform.AnyCPU:
            default:
                machine = ImageFileMachine.I386;
                break;
            }

            Compiler.TimeReporter.Start(TimeReporter.TimerType.OutputSave);
            try {
                if (Compiler.Settings.Target == Target.Module)
                {
                    SaveModule(pekind, machine);
                }
                else
                {
                    Builder.Save(module.Builder.ScopeName, pekind, machine);
                }
            } catch (Exception e) {
                Report.Error(16, "Could not write to file `" + name + "', cause: " + e.Message);
            }
            Compiler.TimeReporter.Stop(TimeReporter.TimerType.OutputSave);

            // Save debug symbols file
            if (symbol_writer != null && Compiler.Report.Errors == 0)
            {
                // TODO: it should run in parallel
                Compiler.TimeReporter.Start(TimeReporter.TimerType.DebugSave);

                var filename = file_name + ".mdb";
                try {
                    // We mmap the file, so unlink the previous version since it may be in use
                    File.Delete(filename);
                } catch {
                    // We can safely ignore
                }

                module.WriteDebugSymbol(symbol_writer);

                using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write)) {
                    symbol_writer.CreateSymbolFile(module.Builder.ModuleVersionId, fs);
                }

                Compiler.TimeReporter.Stop(TimeReporter.TimerType.DebugSave);
            }
        }
Exemple #19
0
			protected override void ErrorDuplicateName (Parameter p, Report Report)
			{
				Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
					p.Name);
			}
Exemple #20
0
 public static void Error_InvalidModifier(Location l, string name)
 {
     Report.Error(106, l, "The modifier `" + name + "' is not valid for this item");
 }
Exemple #21
0
		public static string GetPackageFlags (string packages, Report report)
		{
			ProcessStartInfo pi = new ProcessStartInfo ();
			pi.FileName = "pkg-config";
			pi.RedirectStandardOutput = true;
			pi.UseShellExecute = false;
			pi.Arguments = "--libs " + packages;
			Process p = null;
			try {
				p = Process.Start (pi);
			} catch (Exception e) {
				if (report == null)
					throw;

				report.Error (-27, "Couldn't run pkg-config: " + e.Message);
				return null;
			}
			
			if (p.StandardOutput == null) {
				if (report == null)
					throw new ApplicationException ("Specified package did not return any information");

				report.Warning (-27, 1, "Specified package did not return any information");
				p.Close ();
				return null;
			}

			string pkgout = p.StandardOutput.ReadToEnd ();
			p.WaitForExit ();
			if (p.ExitCode != 0) {
				if (report == null)
					throw new ApplicationException (pkgout);

				report.Error (-27, "Error running pkg-config. Check the above output.");
				p.Close ();
				return null;
			}

			p.Close ();
			return pkgout;
		}
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(), MemberType.GetSignatureForError());
                return;
            }

            AttributeEncoder encoder;
            MethodSpec       ctor;

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

#if STATIC
            //
            // Set struct layout without resolving StructLayoutAttribute which is not always available
            //

            TypeAttributes attribs = TypeAttributes.SequentialLayout;
            switch (char_set)
            {
            case CharSet.None:
            case CharSet.Ansi:
                attribs |= TypeAttributes.AnsiClass;
                break;

            case CharSet.Auto:
                attribs |= TypeAttributes.AutoClass;
                break;

            case CharSet.Unicode:
                attribs |= TypeAttributes.UnicodeClass;
                break;
            }

            fixed_buffer_type.__SetAttributes(fixed_buffer_type.Attributes | attribs);
            fixed_buffer_type.__SetLayout(0, buffer_size * type_size);
#else
            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;
            }

            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());
#endif
            //
            // 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());
        }
		public static void Error_GlobalNamespaceRedefined (Location loc, Report Report)
		{
			Report.Error (1681, loc, "You cannot redefine the global extern alias");
		}
Exemple #24
0
        protected override bool DoDefineMembers()
        {
            PredefinedType builder_type;
            PredefinedMember <MethodSpec> bf;
            PredefinedMember <MethodSpec> bs;
            PredefinedMember <MethodSpec> sr;
            PredefinedMember <MethodSpec> se;
            PredefinedMember <MethodSpec> sm;
            bool has_task_return_type = false;
            var  pred_members         = Module.PredefinedMembers;

            if (return_type.Kind == MemberKind.Void)
            {
                builder_type = Module.PredefinedTypes.AsyncVoidMethodBuilder;
                bf           = pred_members.AsyncVoidMethodBuilderCreate;
                bs           = pred_members.AsyncVoidMethodBuilderStart;
                sr           = pred_members.AsyncVoidMethodBuilderSetResult;
                se           = pred_members.AsyncVoidMethodBuilderSetException;
                sm           = pred_members.AsyncVoidMethodBuilderSetStateMachine;
            }
            else if (return_type == Module.PredefinedTypes.Task.TypeSpec)
            {
                builder_type = Module.PredefinedTypes.AsyncTaskMethodBuilder;
                bf           = pred_members.AsyncTaskMethodBuilderCreate;
                bs           = pred_members.AsyncTaskMethodBuilderStart;
                sr           = pred_members.AsyncTaskMethodBuilderSetResult;
                se           = pred_members.AsyncTaskMethodBuilderSetException;
                sm           = pred_members.AsyncTaskMethodBuilderSetStateMachine;
                task         = pred_members.AsyncTaskMethodBuilderTask.Get();
            }
            else
            {
                builder_type         = Module.PredefinedTypes.AsyncTaskMethodBuilderGeneric;
                bf                   = pred_members.AsyncTaskMethodBuilderGenericCreate;
                bs                   = pred_members.AsyncTaskMethodBuilderGenericStart;
                sr                   = pred_members.AsyncTaskMethodBuilderGenericSetResult;
                se                   = pred_members.AsyncTaskMethodBuilderGenericSetException;
                sm                   = pred_members.AsyncTaskMethodBuilderGenericSetStateMachine;
                task                 = pred_members.AsyncTaskMethodBuilderGenericTask.Get();
                has_task_return_type = true;
            }

            set_result      = sr.Get();
            set_exception   = se.Get();
            builder_factory = bf.Get();
            builder_start   = bs.Get();

            var istate_machine   = Module.PredefinedTypes.IAsyncStateMachine;
            var set_statemachine = sm.Get();

            if (!builder_type.Define() || !istate_machine.Define() || set_result == null || builder_factory == null ||
                set_exception == null || set_statemachine == null || builder_start == null ||
                !Module.PredefinedTypes.INotifyCompletion.Define())
            {
                Report.Error(1993, Location,
                             "Cannot find compiler required types for asynchronous functions support. Are you targeting the wrong framework version?");
                return(base.DoDefineMembers());
            }

            var bt = builder_type.TypeSpec;

            //
            // Inflate generic Task types
            //
            if (has_task_return_type)
            {
                var task_return_type = return_type.TypeArguments;
                if (mutator != null)
                {
                    task_return_type = mutator.Mutate(task_return_type);
                }

                bt               = bt.MakeGenericType(Module, task_return_type);
                set_result       = MemberCache.GetMember(bt, set_result);
                set_exception    = MemberCache.GetMember(bt, set_exception);
                set_statemachine = MemberCache.GetMember(bt, set_statemachine);

                if (task != null)
                {
                    task = MemberCache.GetMember(bt, task);
                }
            }

            builder = AddCompilerGeneratedField("$builder", new TypeExpression(bt, Location));

            var set_state_machine = new Method(this, new TypeExpression(Compiler.BuiltinTypes.Void, Location),
                                               Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN | Modifiers.PUBLIC,
                                               new MemberName("SetStateMachine"),
                                               ParametersCompiled.CreateFullyResolved(
                                                   new Parameter(new TypeExpression(istate_machine.TypeSpec, Location), "stateMachine", Parameter.Modifier.NONE, null, Location),
                                                   istate_machine.TypeSpec),
                                               null);

            ToplevelBlock block = new ToplevelBlock(Compiler, set_state_machine.ParameterInfo, Location);

            block.IsCompilerGenerated = true;
            set_state_machine.Block   = block;

            Members.Add(set_state_machine);

            if (!base.DoDefineMembers())
            {
                return(false);
            }

            //
            // Fabricates SetStateMachine method
            //
            // public void SetStateMachine (IAsyncStateMachine stateMachine)
            // {
            //    $builder.SetStateMachine (stateMachine);
            // }
            //
            var mg = MethodGroupExpr.CreatePredefined(set_statemachine, bt, Location);

            mg.InstanceExpression = new FieldExpr(builder, Location);

            var param_reference = block.GetParameterReference(0, Location);

            param_reference.Type   = istate_machine.TypeSpec;
            param_reference.eclass = ExprClass.Variable;

            var args = new Arguments(1);

            args.Add(new Argument(param_reference));
            set_state_machine.Block.AddStatement(new StatementExpression(new Invocation(mg, args)));

            if (has_task_return_type)
            {
                hoisted_return = LocalVariable.CreateCompilerGenerated(bt.TypeArguments[0], StateMachineMethod.Block, Location);
            }

            return(true);
        }
		public void AddUsingExternalAlias (string alias, Location loc, Report Report)
		{
			// TODO: Do this in parser
			bool not_first = using_clauses != null || DeclarationFound;
			if (using_aliases != null && !not_first) {
				foreach (UsingAliasEntry uae in using_aliases) {
					if (uae is LocalUsingAliasEntry) {
						not_first = true;
						break;
					}
				}
			}

			if (not_first)
				Report.Error (439, loc, "An extern alias declaration must precede all other elements");

			if (alias == "global") {
				Error_GlobalNamespaceRedefined (loc, Report);
				return;
			}

			AddUsingAlias (new UsingAliasEntry (alias, loc));
		}
        private FullNamedExpression Lookup(DeclSpace ds, string name, Location loc, bool ignore_cs0104)
        {
            //
            // Check whether it's in the namespace.
            //
            FullNamedExpression fne = ns.Lookup(ds, name, loc);

            //
            // Check aliases.
            //
            if (using_aliases != null)
            {
                foreach (UsingAliasEntry ue in using_aliases)
                {
                    if (ue.Alias == name)
                    {
                        if (fne != null)
                        {
                            if (Doppelganger != null)
                            {
                                // TODO: Namespace has broken location
                                //Report.SymbolRelatedToPreviousError (fne.Location, null);
                                Report.SymbolRelatedToPreviousError(ue.Location, null);
                                Report.Error(576, loc,
                                             "Namespace `{0}' contains a definition with same name as alias `{1}'",
                                             GetSignatureForError(), name);
                            }
                            else
                            {
                                return(fne);
                            }
                        }

                        return(ue.Resolve(Doppelganger));
                    }
                }
            }

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

            if (IsImplicit)
            {
                return(null);
            }

            //
            // Check using entries.
            //
            FullNamedExpression match = null;

            foreach (Namespace using_ns in GetUsingTable())
            {
                match = using_ns.Lookup(ds, name, loc);
                if (match == null || !(match is TypeExpr))
                {
                    continue;
                }
                if (fne != null)
                {
                    if (!ignore_cs0104)
                    {
                        Error_AmbiguousTypeReference(loc, name, fne, match);
                    }
                    return(null);
                }
                fne = match;
            }

            return(fne);
        }
Exemple #27
0
		bool CheckReachableExit (Report report)
		{
			if (block.HasReachableClosingBrace && ReturnType.Kind != MemberKind.Void) {
				// FIXME: Flow-analysis on MoveNext generated code
				if (!IsIterator) {
					report.Error (1643, StartLocation,
							"Not all code paths return a value in anonymous method of type `{0}'", GetSignatureForError ());

					return false;
				}
			}

			return true;
		}
 public static void Error_GlobalNamespaceRedefined(Location loc)
 {
     Report.Error(1681, loc, "You cannot redefine the global extern alias");
 }
Exemple #29
0
		public static void Error1599 (Location loc, TypeSpec t, Report Report)
		{
			Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", t.GetSignatureForError ());
		}
 public override void Error_NamespaceDoesNotExist(DeclSpace ds, Location loc, string name)
 {
     Report.Error(400, loc, "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
                  name);
 }
Exemple #31
0
		protected virtual void ErrorDuplicateName (Parameter p, Report Report)
		{
			Report.Error (100, p.Location, "The parameter name `{0}' is a duplicate", p.Name);
		}
 public static void Error_InvalidNumberOfTypeArguments(Type t, Location loc)
 {
     Report.SymbolRelatedToPreviousError(t);
     Report.Error(305, loc, "Using the generic type `{0}' requires `{1}' type argument(s)",
                  TypeManager.CSharpName(t), TypeManager.GetNumberOfTypeArguments(t).ToString());
 }
Exemple #33
0
		static void Error_InvalidModifier (Modifiers mod, Location l, Report Report)
		{
			Report.Error (106, l, "The modifier `{0}' is not valid for this item",
				Name (mod));
		}
 static void Error_TypeArgumentsCannotBeUsed(Location loc, string type, string name)
 {
     Report.Error(308, loc, "The non-generic {0} `{1}' cannot be used with the type arguments",
                  type, name);
 }
Exemple #35
0
		static public void Save (string name, bool saveDebugInfo, Report Report)
		{
			PortableExecutableKinds pekind;
			ImageFileMachine machine;

			switch (RootContext.Platform) {
			case Platform.X86:
				pekind = PortableExecutableKinds.Required32Bit;
				machine = ImageFileMachine.I386;
				break;
			case Platform.X64:
				pekind = PortableExecutableKinds.PE32Plus;
				machine = ImageFileMachine.AMD64;
				break;
			case Platform.IA64:
				pekind = PortableExecutableKinds.PE32Plus;
				machine = ImageFileMachine.IA64;
				break;
			case Platform.AnyCPU:
			default:
				pekind = PortableExecutableKinds.ILOnly;
				machine = ImageFileMachine.I386;
				break;
			}
			try {
				Assembly.Builder.Save (Basename (name), pekind, machine);
			}
			catch (COMException) {
				if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
					throw;

				// FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies 
				Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
					RootContext.StrongNameKeyFile +
					"', Use MCS with the Mono runtime or CSC to compile this assembly.");
			}
			catch (System.IO.IOException io) {
				Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
				return;
			}
			catch (System.UnauthorizedAccessException ua) {
				Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
				return;
			}
			catch (System.NotImplementedException nie) {
				Report.RuntimeMissingSupport (Location.Null, nie.Message);
				return;
			}

			//
			// Write debuger symbol file
			//
			if (saveDebugInfo)
				SymbolWriter.WriteSymbolFile ();
			}
Exemple #36
0
 public void Error_UnderlyingType(Location loc)
 {
     Report.Error(1008, loc,
                  "Type byte, sbyte, short, ushort, int, uint, long or ulong expected");
 }
Exemple #37
0
		public virtual void Error_FinallyClause (Report Report)
		{
			Report.Error (157, loc, "Control cannot leave the body of a finally clause");
		}
Exemple #38
0
        protected override bool DoDefineMembers()
        {
            action = Module.PredefinedTypes.Action.Resolve();

            PredefinedType builder_type;
            PredefinedMember <MethodSpec> bf;
            PredefinedMember <MethodSpec> sr;
            PredefinedMember <MethodSpec> se;
            bool has_task_return_type = false;
            var  pred_members         = Module.PredefinedMembers;

            if (return_type.Kind == MemberKind.Void)
            {
                builder_type = Module.PredefinedTypes.AsyncVoidMethodBuilder;
                bf           = pred_members.AsyncVoidMethodBuilderCreate;
                sr           = pred_members.AsyncVoidMethodBuilderSetResult;
                se           = pred_members.AsyncVoidMethodBuilderSetException;
            }
            else if (return_type == Module.PredefinedTypes.Task.TypeSpec)
            {
                builder_type = Module.PredefinedTypes.AsyncTaskMethodBuilder;
                bf           = pred_members.AsyncTaskMethodBuilderCreate;
                sr           = pred_members.AsyncTaskMethodBuilderSetResult;
                se           = pred_members.AsyncTaskMethodBuilderSetException;
                task         = pred_members.AsyncTaskMethodBuilderTask.Get();
            }
            else
            {
                builder_type         = Module.PredefinedTypes.AsyncTaskMethodBuilderGeneric;
                bf                   = pred_members.AsyncTaskMethodBuilderGenericCreate;
                sr                   = pred_members.AsyncTaskMethodBuilderGenericSetResult;
                se                   = pred_members.AsyncTaskMethodBuilderGenericSetException;
                task                 = pred_members.AsyncTaskMethodBuilderGenericTask.Get();
                has_task_return_type = true;
            }

            set_result    = sr.Get();
            set_exception = se.Get();
            var builder_factory = bf.Get();

            if (!builder_type.Define() || set_result == null || builder_factory == null || set_exception == null)
            {
                Report.Error(1993, Location,
                             "Cannot find compiler required types for asynchronous functions support. Are you targeting the wrong framework version?");
                return(base.DoDefineMembers());
            }

            var bt = builder_type.TypeSpec;

            //
            // Inflate generic Task types
            //
            if (has_task_return_type)
            {
                var task_return_type = return_type.TypeArguments;
                if (mutator != null)
                {
                    task_return_type = mutator.Mutate(task_return_type);
                }

                bt = bt.MakeGenericType(Module, task_return_type);
                builder_factory = MemberCache.GetMember <MethodSpec> (bt, builder_factory);
                set_result      = MemberCache.GetMember <MethodSpec> (bt, set_result);
                set_exception   = MemberCache.GetMember <MethodSpec> (bt, set_exception);

                if (task != null)
                {
                    task = MemberCache.GetMember <PropertySpec> (bt, task);
                }
            }

            builder = AddCompilerGeneratedField("$builder", new TypeExpression(bt, Location));

            if (!base.DoDefineMembers())
            {
                return(false);
            }

            var block = instance_constructors[0].Block;

            var mg = MethodGroupExpr.CreatePredefined(builder_factory, bt, Location);

            block.AddStatement(
                new StatementExpression(new SimpleAssign(
                                            new FieldExpr(builder, Location),
                                            new Invocation(mg, new Arguments(0)),
                                            Location)));

            if (has_task_return_type)
            {
                hoisted_return = LocalVariable.CreateCompilerGenerated(bt.TypeArguments[0], block, Location);
            }

            return(true);
        }
Exemple #39
0
		public static void Error_1008 (Location loc, Report Report)
		{
			Report.Error (1008, loc,
				"Type byte, sbyte, short, ushort, int, uint, long or ulong expected");
		}
Exemple #40
0
 public void Error_DuplicateName(Report r)
 {
     r.Error(100, Location, "The parameter name `{0}' is a duplicate", Name);
 }
Exemple #41
0
		public static void Error_UnknownLabel (Location loc, string label, Report Report)
		{
			Report.Error(159, loc, "The label `{0}:' could not be found within the scope of the goto statement",
				label);
		}
Exemple #42
0
 public static void Error_1008(Location loc, Report Report)
 {
     Report.Error(1008, loc,
                  "Type byte, sbyte, short, ushort, int, uint, long or ulong expected");
 }
Exemple #43
0
		public static void Error_InvalidConstantType (TypeSpec t, Location loc, Report Report)
		{
			if (t.IsGenericParameter) {
				Report.Error (1959, loc,
					"Type parameter `{0}' cannot be declared const", t.GetSignatureForError ());
			} else {
				Report.Error (283, loc,
					"The type `{0}' cannot be declared const", t.GetSignatureForError ());
			}
		}
Exemple #44
0
 public static void Error_VariableOfStaticClass(Location loc, string variable_name, TypeSpec static_class, Report Report)
 {
     Report.SymbolRelatedToPreviousError(static_class);
     Report.Error(723, loc, "`{0}': cannot declare variables of static types",
                  variable_name);
 }
Exemple #45
0
		public bool Define (DeclSpace parent, string method_full_name, Report Report)
		{
			TypeContainer container = parent.PartialContainer;

			PendingImplementation pending = container.PendingImplementations;
			if (pending != null){
				implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this);

				if (member.InterfaceType != null){
					if (implementing == null){
						if (member is PropertyBase) {
							Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
								      method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
								      member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));

						} else {
							Report.Error (539, method.Location,
								      "`{0}.{1}' in explicit interface declaration is not a member of interface",
								      TypeManager.CSharpName (member.InterfaceType), member.ShortName);
						}
						return false;
					}
					if (implementing.IsAccessor && !(method is AbstractPropertyEventMethod)) {
						Report.SymbolRelatedToPreviousError (implementing);
						Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
							member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
						return false;
					}
				} else {
					if (implementing != null) {
						AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
						if (prop_method == null) {
							if (implementing.IsAccessor) {
								Report.SymbolRelatedToPreviousError (implementing);
								Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}'",
									method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
							}
						} else if (implementing.DeclaringType.IsInterface) {
							if (!implementing.IsAccessor) {
								Report.SymbolRelatedToPreviousError (implementing);
								Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
									method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
							} else {
								PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
								if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
									Report.SymbolRelatedToPreviousError (implementing);
									Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
										method.GetSignatureForError (), implementing.GetSignatureForError ());
								}
							}
						}
					}
				}
			}

			//
			// For implicit implementations, make sure we are public, for
			// explicit implementations, make sure we are private.
			//
			if (implementing != null){
				//
				// Setting null inside this block will trigger a more
				// verbose error reporting for missing interface implementations
				//
				// The "candidate" function has been flagged already
				// but it wont get cleared
				//
				if (member.IsExplicitImpl){
					if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
						Report.SymbolRelatedToPreviousError (implementing);
						Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
							method.GetSignatureForError ());
					}
				} else {
					if (implementing.DeclaringType.IsInterface) {
						//
						// If this is an interface method implementation,
						// check for public accessibility
						//
						if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
						{
							implementing = null;
						}
					} else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
						// We may never be private.
						implementing = null;

					} else if ((modifiers & Modifiers.OVERRIDE) == 0){
						//
						// We may be protected if we're overriding something.
						//
						implementing = null;
					}
				}
					
				//
				// Static is not allowed
				//
				if ((modifiers & Modifiers.STATIC) != 0){
					implementing = null;
				}
			}
			
			//
			// If implementing is still valid, set flags
			//
			if (implementing != null){
				//
				// When implementing interface methods, set NewSlot
				// unless, we are overwriting a method.
				//
				if (implementing.DeclaringType.IsInterface){
					if ((modifiers & Modifiers.OVERRIDE) == 0)
						flags |= MethodAttributes.NewSlot;
				}

				flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;

				// Set Final unless we're virtual, abstract or already overriding a method.
				if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
					flags |= MethodAttributes.Final;

				//
				// clear the pending implementation flag (requires explicit methods to be defined first)
				//
				parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName,
					member.InterfaceType, this, member.IsExplicitImpl);

				//
				// Update indexer accessor name to match implementing abstract accessor
				//
				if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
					method_full_name = implementing.MemberDefinition.Name;
			}

			DefineMethodBuilder (container, method_full_name, method.ParameterInfo);

			if (builder == null)
				return false;

//			if (container.CurrentType != null)
//				declaring_type = container.CurrentType;
//			else
				declaring_type = container.Definition;

			if (implementing != null && member.IsExplicitImpl) {
				container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
			}

			return true;
		}
Exemple #46
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());
        }
		public static void Error_NamespaceNotFound (Location loc, string name, Report Report)
		{
			Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
				name);

			switch (name) {
			case "Gtk": case "GtkSharp":
				MsgtryPkg ("gtk-sharp");
				break;

			case "Gdk": case "GdkSharp":
				MsgtryPkg ("gdk-sharp");
				break;

			case "Glade": case "GladeSharp":
				MsgtryPkg ("glade-sharp");
				break;

			case "System.Drawing":
			case "System.Web.Services":
			case "System.Web":
			case "System.Data":
			case "System.Windows.Forms":
				MsgtryRef (name);
				break;
			}
		}
Exemple #48
0
 static void Error_InvalidModifier(Modifiers mod, Location l, Report Report)
 {
     Report.Error(106, l, "The modifier `{0}' is not valid for this item",
                  Name(mod));
 }
		public virtual void Error_NamespaceDoesNotExist (Location loc, string name, Report Report)
		{
			if (name.IndexOf ('`') > 0) {
				FullNamedExpression retval = Lookup (RootContext.ToplevelTypes.Compiler, SimpleName.RemoveGenericArity (name), loc);
				if (retval != null) {
					Error_TypeArgumentsCannotBeUsed (retval, loc);
					return;
				}
			} else {
				Type t = LookForAnyGenericType (name);
				if (t != null) {
					Error_InvalidNumberOfTypeArguments (t, loc);
					return;
				}
			}

			Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
				name, GetSignatureForError ());
		}
Exemple #50
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());
                }
            }

            var ret_type = ReturnType.ResolveAsType(this);

            if (ret_type == null)
            {
                return(false);
            }

            //
            // 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 #51
0
		public static void Error1599 (Location loc, TypeSpec t, Report Report)
		{
			Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
		}
Exemple #52
0
 public override void Error_FinallyClause(Report Report)
 {
     Report.Error(1625, loc, "Cannot yield in the body of a finally clause");
 }
Exemple #53
0
 public static void CheckUnsafeOption(Location loc, Report Report)
 {
     if (!Unsafe) {
         Report.Error (227, loc,
             "Unsafe code requires the `unsafe' command line option to be specified");
     }
 }
Exemple #54
0
        void SetEntryPoint()
        {
            if (!Compiler.Settings.NeedsEntryPoint)
            {
                if (Compiler.Settings.MainClass != null)
                {
                    Report.Error(2017, "Cannot specify -main if building a module or library");
                }

                return;
            }

            PEFileKinds file_kind;

            switch (Compiler.Settings.Target)
            {
            case Target.Library:
            case Target.Module:
                file_kind = PEFileKinds.Dll;
                break;

            case Target.WinExe:
                file_kind = PEFileKinds.WindowApplication;
                break;

            default:
                file_kind = PEFileKinds.ConsoleApplication;
                break;
            }

            if (entry_point == null)
            {
                string main_class = Compiler.Settings.MainClass;
                if (main_class != null)
                {
                    // TODO: Handle dotted names
                    var texpr = module.GlobalRootNamespace.LookupType(module, main_class, 0, LookupMode.Probing, Location.Null);
                    if (texpr == null)
                    {
                        Report.Error(1555, "Could not find `{0}' specified for Main method", main_class);
                        return;
                    }

                    var mtype = texpr.Type.MemberDefinition as ClassOrStruct;
                    if (mtype == null)
                    {
                        Report.Error(1556, "`{0}' specified for Main method must be a valid class or struct", main_class);
                        return;
                    }

                    Report.Error(1558, mtype.Location, "`{0}' does not have a suitable static Main method", mtype.GetSignatureForError());
                }
                else
                {
                    string pname = file_name == null ? name : Path.GetFileName(file_name);
                    Report.Error(5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
                                 pname);
                }

                return;
            }

            Builder.SetEntryPoint(entry_point.MethodBuilder, file_kind);
        }
Exemple #55
0
		public void Error_DuplicateName (Report r)
		{
			r.Error (100, Location, "The parameter name `{0}' is a duplicate", Name);
		}
Exemple #56
0
 void Error_AssemblySigning(string text)
 {
     Report.Error(1548, "Error during assembly signing. " + text);
 }
Exemple #57
0
 public override void Error_FinallyClause(Report Report)
 {
     Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
 }
Exemple #58
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);
                }

                IsSatelliteAssembly = true;
                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}'",
                                 t.GetSignatureForError());
                    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",
                                 t.GetSignatureForError());
                    return;
                }

                if (t.IsNested)
                {
                    Report.Error(730, a.Location, "Cannot forward type `{0}' because it is a nested type",
                                 t.GetSignatureForError());
                    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 #59
0
		public static void Error_VariableOfStaticClass (Location loc, string variable_name, TypeSpec static_class, Report Report)
		{
			Report.SymbolRelatedToPreviousError (static_class);
			Report.Error (723, loc, "`{0}': cannot declare variables of static types",
				variable_name);
		}
Exemple #60
0
 public static void Error(int code, string err, Report ec)
 {
     ec.Error(code, err);
 }