Merge pull request #487 from mayerwin/patch-1
[mono.git] / mcs / mcs / ikvm.cs
index 3e11c3812ca740724cdd2e2cdb3085a389cb0680..7aed47394189f3150401b8424039ea9391c36f3f 100644 (file)
@@ -6,6 +6,7 @@
 // Dual licensed under the terms of the MIT X11 or GNU GPL
 //
 // Copyright 2009-2010 Novell, Inc. 
+// Copyright 2011 Xamarin Inc
 //
 //
 
@@ -22,7 +23,7 @@ namespace Mono.CSharp
 #if !STATIC
        public class StaticImporter
        {
-               public StaticImporter (BuildinTypes buildin)
+               public StaticImporter (BuiltinTypes builtin)
                {
                        throw new NotSupportedException ();
                }
@@ -47,22 +48,32 @@ namespace Mono.CSharp
 
        sealed class StaticImporter : MetadataImporter
        {
-               public StaticImporter ()
+               public StaticImporter (ModuleContainer module)
+                       : base (module)
                {
                }
 
+               public void AddCompiledAssembly (AssemblyDefinitionStatic assembly)
+               {
+                       assembly_2_definition.Add (assembly.Builder, assembly);
+               }
+
+               public override void AddCompiledType (TypeBuilder type, TypeSpec spec)
+               {
+                       compiled_types.Add (type, spec);
+               }
+
                protected override MemberKind DetermineKindFromBaseType (MetaType baseType)
                {
                        string name = baseType.Name;
 
-                       // TODO: namespace check
-                       if (name == "ValueType")
+                       if (name == "ValueType" && baseType.Namespace == "System")
                                return MemberKind.Struct;
 
-                       if (name == "Enum")
+                       if (name == "Enum" && baseType.Namespace == "System")
                                return MemberKind.Enum;
 
-                       if (name == "MulticastDelegate")
+                       if (name == "MulticastDelegate" && baseType.Namespace == "System")
                                return MemberKind.Delegate;
 
                        return MemberKind.Class;
@@ -78,24 +89,24 @@ namespace Mono.CSharp
                        return false;
                }
 
-               public override void GetCustomAttributeTypeName (CustomAttributeData cad, out string typeNamespace, out string typeName)
-               {
-                       cad.__ReadTypeName (out typeNamespace, out typeName);
-               }
-
                public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
                {
                        // It can be used more than once when importing same assembly
                        // into 2 or more global aliases
-                       var definition = GetAssemblyDefinition (assembly);
+                       // TODO: Should be just Add
+                       GetAssemblyDefinition (assembly);
 
                        var all_types = assembly.GetTypes ();
-                       ImportTypes (all_types, targetNamespace, definition.HasExtensionMethod);
+                       ImportTypes (all_types, targetNamespace, true);
+
+                       all_types = assembly.ManifestModule.__GetExportedTypes ();
+                       if (all_types.Length != 0)
+                               ImportForwardedTypes (all_types, targetNamespace);
                }
 
                public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
                {
-                       var module_definition = new ImportedModuleDefinition (module, this);
+                       var module_definition = new ImportedModuleDefinition (module);
                        module_definition.ReadAttributes ();
 
                        var all_types = module.GetTypes ();
@@ -104,13 +115,38 @@ namespace Mono.CSharp
                        return module_definition;
                }
 
-               public void InitializeBuildinTypes (BuildinTypes buildin, Assembly corlib)
+               void ImportForwardedTypes (MetaType[] types, Namespace targetNamespace)
+               {
+                       Namespace ns = targetNamespace;
+                       string prev_namespace = null;
+                       foreach (var t in types) {
+                               // IsMissing tells us the type has been forwarded and target assembly is missing 
+                               if (!t.__IsMissing)
+                                       continue;
+
+                               if (t.Name[0] == '<')
+                                       continue;
+
+                               var it = CreateType (t, null, new DynamicTypeReader (t), true);
+                               if (it == null)
+                                       continue;
+
+                               if (prev_namespace != t.Namespace) {
+                                       ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
+                                       prev_namespace = t.Namespace;
+                               }
+
+                               ns.AddType (module, it);
+                       }
+               }
+
+               public void InitializeBuiltinTypes (BuiltinTypes builtin, Assembly corlib)
                {
                        //
                        // Setup mapping for build-in types to avoid duplication of their definition
                        //
-                       foreach (var type in buildin.AllTypes) {
-                               buildin_types.Add (corlib.GetType (type.FullName), type);
+                       foreach (var type in builtin.AllTypes) {
+                               compiled_types.Add (corlib.GetType (type.FullName), type);
                        }
                }
        }
@@ -118,34 +154,56 @@ namespace Mono.CSharp
 
        class AssemblyDefinitionStatic : AssemblyDefinition
        {
+               readonly StaticLoader loader;
+
                //
                // Assembly container with file output
                //
-               public AssemblyDefinitionStatic (ModuleContainer module, string name, string fileName)
+               public AssemblyDefinitionStatic (ModuleContainer module, StaticLoader loader, string name, string fileName)
                        : base (module, name, fileName)
                {
+                       this.loader = loader;
+                       Importer = loader.MetadataImporter;
                }
 
                //
-               // Initializes the code generator
+               // Initializes the assembly SRE domain
                //
-               public bool Create (Universe domain)
+               public void Create (Universe domain)
                {
                        ResolveAssemblySecurityAttributes ();
                        var an = CreateAssemblyName ();
 
                        Builder = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, Path.GetDirectoryName (file_name));
+                       module.Create (this, CreateModuleBuilder ());
+               }
 
-                       // Sets output file metadata version, this makes sense for mscorlib
-                       // compilation only but won't restrict that for now
-                       if (RootContext.StdLibRuntimeVersion == RuntimeVersion.v4) {
-                               Builder.__SetImageRuntimeVersion ("v4.0.30319", 0x20000);
+               public override void Emit ()
+               {
+                       if (loader.Corlib != null && !(loader.Corlib is AssemblyBuilder)) {
+                               Builder.__SetImageRuntimeVersion (loader.Corlib.ImageRuntimeVersion, 0x20000);
                        } else {
-                               // otherwise we default to v2.0.50727
+                               // Sets output file metadata version when there is no mscorlib
+                               switch (module.Compiler.Settings.StdLibRuntimeVersion) {
+                               case RuntimeVersion.v4:
+                                       Builder.__SetImageRuntimeVersion ("v4.0.30319", 0x20000);
+                                       break;
+                               case RuntimeVersion.v2:
+                                       Builder.__SetImageRuntimeVersion ("v2.0.50727", 0x20000);
+                                       break;
+                               case RuntimeVersion.v1:
+                                       // Compiler does not do any checks whether the produced metadata
+                                       // are valid in the context of 1.0 stream version
+                                       Builder.__SetImageRuntimeVersion ("v1.1.4322", 0x10000);
+                                       break;
+                               default:
+                                       throw new NotImplementedException ();
+                               }
                        }
 
                        builder_extra = new AssemblyBuilderIKVM (Builder, Compiler);
-                       return true;
+
+                       base.Emit ();
                }
 
                public Module IncludeModule (RawModule moduleFile)
@@ -164,22 +222,61 @@ namespace Mono.CSharp
                readonly StaticImporter importer;
                readonly Universe domain;
                Assembly corlib;
+               List<Tuple<AssemblyName, string, Assembly>> loaded_names;
+               static readonly Dictionary<string, string[]> sdk_directory;
+
+               static StaticLoader ()
+               {
+                       sdk_directory = new Dictionary<string, string[]> ();
+                       sdk_directory.Add ("2", new string[] { "2.0", "net_2_0", "v2.0.50727" });
+                       sdk_directory.Add ("4", new string[] { "4.0", "net_4_0", "v4.0.30319" });
+                       sdk_directory.Add ("4.5", new string[] { "4.5", "net_4_5", "v4.0.30319" });
+               }
 
                public StaticLoader (StaticImporter importer, CompilerContext compiler)
                        : base (compiler)
                {
                        this.importer = importer;
-                       domain = new Universe ();
+                       domain = new Universe (UniverseOptions.MetadataOnly);
+                       domain.EnableMissingMemberResolution ();
                        domain.AssemblyResolve += AssemblyReferenceResolver;
+                       loaded_names = new List<Tuple<AssemblyName, string, Assembly>> ();
+
+                       if (compiler.Settings.StdLib) {
+                               var corlib_path = Path.GetDirectoryName (typeof (object).Assembly.Location);
+                               string fx_path = corlib_path.Substring (0, corlib_path.LastIndexOf (Path.DirectorySeparatorChar));
+
+                               string sdk_path = null;
+
+                               string sdk_version = compiler.Settings.SdkVersion ?? "4.5";
+                               string[] sdk_sub_dirs;
+
+                               if (!sdk_directory.TryGetValue (sdk_version, out sdk_sub_dirs))
+                                       sdk_sub_dirs = new string[] { sdk_version };
+
+                               foreach (var dir in sdk_sub_dirs) {
+                                       sdk_path = Path.Combine (fx_path, dir);
+                                       if (File.Exists (Path.Combine (sdk_path, "mscorlib.dll")))
+                                               break;
+
+                                       sdk_path = null;
+                               }
+
+                               if (sdk_path == null) {
+                                       compiler.Report.Warning (-1, 1, "SDK path could not be resolved");
+                                       sdk_path = corlib_path;
+                               }
+
+                               paths.Add (sdk_path);
+                       }
                }
 
+               #region Properties
+
                public Assembly Corlib {
                        get {
                                return corlib;
                        }
-                       set {
-                               corlib = value;
-                       }
                }
 
                public Universe Domain {
@@ -188,14 +285,86 @@ namespace Mono.CSharp
                        }
                }
 
+               public StaticImporter MetadataImporter {
+                       get {
+                               return importer;
+                       }
+               }
+
+               #endregion
+
                Assembly AssemblyReferenceResolver (object sender, IKVM.Reflection.ResolveEventArgs args)
                {
-                       if (args.Name == "mscorlib")
+                       var refname = args.Name;
+                       if (refname == "mscorlib")
                                return corlib;
 
+                       Assembly version_mismatch = null;
+                       bool is_fx_assembly = false;
+
+                       foreach (var assembly in domain.GetAssemblies ()) {
+                               AssemblyComparisonResult result;
+                               if (!Fusion.CompareAssemblyIdentityPure (refname, false, assembly.FullName, false, out result)) {
+                                       if ((result == AssemblyComparisonResult.NonEquivalentVersion || result == AssemblyComparisonResult.NonEquivalentPartialVersion) &&
+                                               (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version) &&
+                                               !is_fx_assembly) {
+                                               version_mismatch = assembly;
+                                       }
+
+                                       continue;
+                               }
+
+                               if (result == AssemblyComparisonResult.EquivalentFullMatch ||
+                                       result == AssemblyComparisonResult.EquivalentWeakNamed ||
+                                       result == AssemblyComparisonResult.EquivalentPartialMatch) {
+                                       return assembly;
+                               }
+
+                               if (result == AssemblyComparisonResult.EquivalentFXUnified) {
+                                       is_fx_assembly = true;
+
+                                       if (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version)
+                                               version_mismatch = assembly;
+
+                                       continue;
+                               }
+
+                               throw new NotImplementedException ("Assembly equality = " + result.ToString ());
+                       }
+
+                       if (version_mismatch != null) {
+                               if (version_mismatch is AssemblyBuilder)
+                                       return version_mismatch;
+
+                               var v1 = new AssemblyName (refname).Version;
+                               var v2 = version_mismatch.GetName ().Version;
+
+                               if (v1 > v2) {
+//                                     compiler.Report.SymbolRelatedToPreviousError (args.RequestingAssembly.Location);
+                                       compiler.Report.Error (1705, "Assembly `{0}' references `{1}' which has a higher version number than imported assembly `{2}'",
+                                               args.RequestingAssembly.FullName, refname, version_mismatch.GetName ().FullName);
+
+                                       return domain.CreateMissingAssembly (args.Name);
+                               }
+
+                               if (!is_fx_assembly) {
+                                       if (v1.Major != v2.Major || v1.Minor != v2.Minor) {
+                                               compiler.Report.Warning (1701, 2,
+                                                       "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
+                                                       refname, version_mismatch.GetName ().FullName);
+                                       } else {
+                                               compiler.Report.Warning (1702, 3,
+                                                       "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
+                                                       refname, version_mismatch.GetName ().FullName);
+                                       }
+                               }
+
+                               return version_mismatch;
+                       }
+
                        // AssemblyReference has not been found in the domain
                        // create missing reference and continue
-                       return new MissingAssembly (domain, args.Name);
+                       return domain.CreateMissingAssembly (args.Name);
                }
 
                public void Dispose ()
@@ -209,36 +378,32 @@ namespace Mono.CSharp
                        // For now the "default config" is harcoded into the compiler
                        // we can move this outside later
                        //
-                       var default_references = new List<string> (8);
+                       var default_references = new List<string> (4);
 
                        default_references.Add ("System.dll");
                        default_references.Add ("System.Xml.dll");
-#if NET_2_1
-                       default_references.Add ("System.Net.dll");
-                       default_references.Add ("System.Windows.dll");
-                       default_references.Add ("System.Windows.Browser.dll");
-#endif
+                       default_references.Add ("System.Core.dll");
 
-                       // TODO: Will have to do it based on mscorlib version or something like that
-
-                       if (RootContext.Version > LanguageVersion.ISO_2)
-                               default_references.Add ("System.Core.dll");
-                       if (RootContext.Version > LanguageVersion.V_3)
+                       if (corlib != null && corlib.GetName ().Version.Major >= 4) {
                                default_references.Add ("Microsoft.CSharp.dll");
+                       }
 
                        return default_references.ToArray ();
                }
 
                public override bool HasObjectType (Assembly assembly)
                {
-                       return assembly.GetType (compiler.BuildinTypes.Object.FullName) != null;
+                       return assembly.GetType (compiler.BuiltinTypes.Object.FullName) != null;
                }
 
-               public override Assembly LoadAssemblyFile (string fileName)
+               public override Assembly LoadAssemblyFile (string fileName, bool isImplicitReference)
                {
                        bool? has_extension = null;
                        foreach (var path in paths) {
                                var file = Path.Combine (path, fileName);
+                               if (compiler.Settings.DebugFlags > 0)
+                                       Console.WriteLine ("Probing assembly location `{0}'", file);
+
                                if (!File.Exists (file)) {
                                        if (!has_extension.HasValue)
                                                has_extension = fileName.EndsWith (".dll", StringComparison.Ordinal) || fileName.EndsWith (".exe", StringComparison.Ordinal);
@@ -252,21 +417,69 @@ namespace Mono.CSharp
                                }
 
                                try {
-                                       using (RawModule module = domain.OpenRawModule (file)) {
-                                               if (!module.IsManifestModule) {
-                                                       Error_AssemblyIsModule (fileName);
-                                                       return null;
+                                       using (var stream = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.Read)) {
+                                               using (RawModule module = domain.OpenRawModule (stream, file)) {
+                                                       if (!module.IsManifestModule) {
+                                                               Error_AssemblyIsModule (fileName);
+                                                               return null;
+                                                       }
+
+                                                       //
+                                                       // check whether the assembly can be actually imported without
+                                                       // collision
+                                                       //
+                                                       var an = module.GetAssemblyName ();
+                                                       foreach (var entry in loaded_names) {
+                                                               var loaded_name = entry.Item1;
+                                                               if (an.Name != loaded_name.Name)
+                                                                       continue;
+
+                                                               if (module.ModuleVersionId == entry.Item3.ManifestModule.ModuleVersionId)
+                                                                       return entry.Item3;
+                                                       
+                                                               if (((an.Flags | loaded_name.Flags) & AssemblyNameFlags.PublicKey) == 0) {
+                                                                       compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
+                                                                       compiler.Report.SymbolRelatedToPreviousError (fileName);
+                                                                       compiler.Report.Error (1704,
+                                                                               "An assembly with the same name `{0}' has already been imported. Consider removing one of the references or sign the assembly",
+                                                                               an.Name);
+                                                                       return null;
+                                                               }
+
+                                                               if ((an.Flags & AssemblyNameFlags.PublicKey) == (loaded_name.Flags & AssemblyNameFlags.PublicKey) && an.Version.Equals (loaded_name.Version)) {
+                                                                       compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
+                                                                       compiler.Report.SymbolRelatedToPreviousError (fileName);
+                                                                       compiler.Report.Error (1703,
+                                                                               "An assembly with the same identity `{0}' has already been imported. Consider removing one of the references",
+                                                                               an.FullName);
+                                                                       return null;
+                                                               }
+                                                       }
+
+                                                       if (compiler.Settings.DebugFlags > 0)
+                                                               Console.WriteLine ("Loading assembly `{0}'", fileName);
+
+                                                       var assembly = domain.LoadAssembly (module);
+                                                       if (assembly != null)
+                                                               loaded_names.Add (Tuple.Create (an, fileName, assembly));
+
+                                                       return assembly;
                                                }
-
-                                               return domain.LoadAssembly (module);
                                        }
-                               } catch {
-                                       Error_FileCorrupted (file);
+                               } catch (Exception e) {
+                                       if (compiler.Settings.DebugFlags > 0)
+                                               Console.WriteLine ("Exception during loading: {0}'", e.ToString ());
+
+                                       if (!isImplicitReference)
+                                               Error_FileCorrupted (file);
+
                                        return null;
                                }
                        }
 
-                       Error_FileNotFound (fileName);
+                       if (!isImplicitReference)
+                               Error_FileNotFound (fileName);
+
                        return null;
                }
 
@@ -295,54 +508,37 @@ namespace Mono.CSharp
                        return null;                            
                }
 
-               //
-               // Optimized default assembly loader version
-               //
-               public override Assembly LoadAssemblyDefault (string assembly)
-               {
-                       foreach (var path in paths) {
-                               var file = Path.Combine (path, assembly);
-                               if (!File.Exists (file))
-                                       continue;
-
-                               try {
-                                       return domain.LoadFile (file);
-                               } catch {
-                                       // Default assemblies can fail to load without error
-                                       return null;
-                               }
-                       }
-
-                       return null;
-               }
-
                public override void LoadReferences (ModuleContainer module)
                {
                        List<Tuple<RootNamespace, Assembly>> loaded;
                        base.LoadReferencesCore (module, out corlib, out loaded);
 
-                       if (corlib != null) {
-                               importer.InitializeBuildinTypes (compiler.BuildinTypes, corlib);
+                       compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesImporting);
+
+                       if (corlib == null) {
+                               // System.Object was not found in any referenced assembly, use compiled assembly as corlib
+                               corlib = module.DeclaringAssembly.Builder;
+                       } else {
+                               importer.InitializeBuiltinTypes (compiler.BuiltinTypes, corlib);
                                importer.ImportAssembly (corlib, module.GlobalRootNamespace);
                        }
 
                        foreach (var entry in loaded) {
                                importer.ImportAssembly (entry.Item2, entry.Item1);
                        }
+
+                       compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesImporting);
                }
 
                public void LoadModules (AssemblyDefinitionStatic assembly, RootNamespace targetNamespace)
                {
-                       if (RootContext.Modules.Count == 0)
-                               return;
-
-                       foreach (var moduleName in RootContext.Modules) {
+                       foreach (var moduleName in compiler.Settings.Modules) {
                                var m = LoadModuleFile (moduleName);
                                if (m == null)
                                        continue;
 
                                if (m.IsManifestModule) {
-                                       Error_FileCorrupted (moduleName);
+                                       Error_ModuleIsAssembly (moduleName);
                                        continue;
                                }
 
@@ -352,153 +548,6 @@ namespace Mono.CSharp
                }
        }
 
-       //
-       // Represents missing assembly reference
-       //
-       class MissingAssembly : Assembly
-       {
-               readonly string full_name;
-               Dictionary<string, MetaType> types;
-
-               public MissingAssembly (Universe universe, string fullName)
-                       : base (universe)
-               {
-                       this.full_name = fullName;
-                       types = new Dictionary<string, MetaType> ();
-               }
-
-               public override MetaType[] GetTypes ()
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override string FullName {
-                       get {
-                               return full_name;
-                       }
-               }
-
-               public override AssemblyName GetName ()
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override string ImageRuntimeVersion {
-                       get {
-                               throw new NotImplementedException ();
-                       }
-               }
-
-               public override Module ManifestModule {
-                       get {
-                               throw new NotImplementedException ();
-                       }
-               }
-
-               public override MethodInfo EntryPoint {
-                       get {
-                               throw new NotImplementedException ();
-                       }
-               }
-
-               public override string Location {
-                       get {
-                               throw new NotImplementedException ();
-                       }
-               }
-
-               public override AssemblyName[] GetReferencedAssemblies ()
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Module[] GetModules (bool getResourceModules)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Module[] GetLoadedModules (bool getResourceModules)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Module GetModule (string name)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override string[] GetManifestResourceNames ()
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override ManifestResourceInfo GetManifestResourceInfo (string resourceName)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Stream GetManifestResourceStream (string resourceName)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               internal override MetaType GetTypeImpl (string typeName)
-               {
-                       //
-                       // We are loading a type from missing reference
-                       // this itself is fine. The error will be reported
-                       // later when the type is actually used
-                       //
-                       MetaType t;
-                       if (!types.TryGetValue (typeName, out t)) {
-                               t = new MissingType (typeName);
-                               types.Add (typeName, t);
-                       }
-
-                       return t;
-               }
-
-               internal override IList<CustomAttributeData> GetCustomAttributesData (MetaType attributeType)
-               {
-                       throw new NotImplementedException ();
-               }
-       }
-
-       class MissingType : MetaType
-       {
-               readonly string full_name;
-
-               public MissingType (string typeName)
-               {
-                       this.full_name = typeName;
-               }
-
-               public override TypeAttributes Attributes {
-                       get {
-                               // TODO: Don't know yet
-                               return TypeAttributes.Public;
-                       }
-               }
-
-               public override MetaType BaseType {
-                       get {
-                               return null;
-                       }
-               }
-
-               public override string FullName {
-                       get {
-                               return full_name;
-                       }
-               }
-
-               public override Module Module {
-                       get {
-                               throw new NotImplementedException ();
-                       }
-               }
-       }
-
        class AssemblyBuilderIKVM : AssemblyBuilderExtension
        {
                readonly AssemblyBuilder builder;
@@ -531,7 +580,7 @@ namespace Mono.CSharp
 
                public override void SetFlags (uint flags, Location loc)
                {
-                       builder.__SetAssemblyFlags ((AssemblyNameFlags) flags);
+                       builder.__AssemblyFlags = (AssemblyNameFlags) flags;
                }
 
                public override void SetVersion (Version version, Location loc)
@@ -539,4 +588,4 @@ namespace Mono.CSharp
                        builder.__SetAssemblyVersion (version);
                }
        }
-}
\ No newline at end of file
+}