Add cleanup call.
[mono.git] / mcs / mcs / rootcontext.cs
index b207617bbca9c707a61ea72feb926ba50bf7d93b..b429b974de11d5c2ee4ab09df266c47ff387ce9b 100755 (executable)
@@ -2,6 +2,7 @@
 // rootcontext.cs: keeps track of our tree representation, and assemblies loaded.
 //
 // Author: Miguel de Icaza (miguel@ximian.com)
+//         Ravi Pratap     (ravi@ximian.com)
 //
 // Licensed under the terms of the GNU GPL
 //
@@ -13,492 +14,359 @@ using System.Reflection;
 using System.Reflection.Emit;
 using System.Diagnostics;
 
-namespace CIR {
+namespace Mono.CSharp {
 
        public class RootContext {
 
                //
                // Contains the parsed tree
                //
-               Tree tree;
+               static Tree tree;
 
                //
-               // Contains loaded assemblies and our generated code as we go.
+               // This hashtable contains all of the #definitions across the source code
+               // it is used by the ConditionalAttribute handler.
                //
-               TypeManager type_manager;
-
+               public static Hashtable AllDefines = new Hashtable ();
+               
                //
-               // The System.Reflection.Emit CodeGenerator
+               // The list of global attributes (those that target the assembly)
                //
-               CodeGen cg;
-
+               static Hashtable global_attributes = new Hashtable ();
+               
                //
-               // The module builder pointer
+               // Whether we are being linked against the standard libraries.
+               // This is only used to tell whether `System.Object' should
+               // have a parent or not.
                //
-               ModuleBuilder mb;
+               public static bool StdLib = true;
 
                //
-               // Error reporting object
-               // 
-               Report report;
-
+               // This keeps track of the order in which classes were defined
+               // so that we can poulate them in that order.
                //
-               // The `System.Object' and `System.ValueType' types, as they
-               // are used often
+               // Order is important, because we need to be able to tell by
+               // examining the parent's list of methods which ones are virtual
+               // or abstract as well as the parent names (to implement new, 
+               // override).
                //
-               Type object_type;
-               Type value_type;
+               static ArrayList type_container_resolve_order;
+               static ArrayList interface_resolve_order;
+               static ArrayList attribute_types;
 
                //
-               // Whether we are being linked against the standard libraries.
-               // This is only used to tell whether `System.Object' should
-               // have a parent or not.
+               // Holds a reference to the Private Implementation Details
+               // class.
                //
-               bool stdlib = true;
+               static TypeBuilder impl_details_class;
+
+               public static int WarningLevel = 2;
                
-               public RootContext ()
+               //
+               // Constructor
+               //
+               static RootContext ()
                {
-                       tree = new Tree (this);
-                       type_manager = new TypeManager ();
-                       report = new Report ();
-
-                       object_type = System.Type.GetType ("System.Object");
-                       value_type = System.Type.GetType ("System.ValueType");
+                       tree = new Tree ();
+                       interface_resolve_order = new ArrayList ();
+                       type_container_resolve_order = new ArrayList ();
                }
 
-               public TypeManager TypeManager {
-                       get {
-                               return type_manager;
-                       }
-               }
-
-               public Tree Tree {
+               static public Tree Tree {
                        get {
                                return tree;
                        }
                }
 
-               public CodeGen CodeGen {
-                       get {
-                               return cg;
-                       }
-
-                       set {
-                               //
-                               // Temporary hack, we should probably
-                               // intialize `cg' rather than depending on
-                               // external initialization of it.
-                               //
-                               cg = value;
-                               mb = cg.ModuleBuilder;
-                       }
+               static public string MainClass;
+               
+               public static void RegisterOrder (Interface iface)
+               {
+                       interface_resolve_order.Add (iface);
                }
-
-               //
-               // Returns the Type that represents the interface whose name
-               // is `name'.
-               //
                
-               Type GetInterfaceTypeByName (string name)
+               public static void RegisterOrder (TypeContainer tc)
                {
-                       Interface parent;
-                       Type t = type_manager.LookupType (name);
-
-                       if (t != null) {
-
-                               if (t.IsInterface)
-                                       return t;
-                               
-                               string cause;
-                               
-                               if (t.IsValueType)
-                                       cause = "is a struct";
-                               else if (t.IsClass) 
-                                       cause = "is a class";
-                               else
-                                       cause = "Should not happen.";
-
-                               report.Error (527, "`"+name+"' " + cause + ", need an interface instead");
-                               
-                               return null;
-                       }
+                       type_container_resolve_order.Add (tc);
+               }
 
-                       parent = (Interface) tree.Interfaces [name];
-                       if (parent == null){
-                               string cause = "is undefined";
-                               
-                               if (tree.Classes [name] != null)
-                                       cause = "is a class";
-                               else if (tree.Structs [name] != null)
-                                       cause = "is a struct";
-                               
-                               report.Error (527, "`"+name+"' " + cause + ", need an interface instead");
-                               return null;
-                       }
+               public static void RegisterAttribute (TypeContainer tc)
+               {
+                       if (attribute_types == null)
+                               attribute_types = new ArrayList ();
                        
-                       t = CreateInterface ((Interface) parent);
-                       if (t == null){
-                               report.Error (529,
-                                             "Inherited interface `"+name+"' is circular");
-                               return null;
-                       }
-
-                       return t;
+                       attribute_types.Add (tc);
                }
                
+               // 
+               // The default compiler checked state
                //
-               // Returns the list of interfaces that this interface implements
-               // Or null if it does not implement any interface.
+               static public bool Checked = false;
+
                //
-               // Sets the error boolean accoringly.
+               // Whether to allow Unsafe code
                //
-               Type [] GetInterfaceBases (Interface iface, out bool error)
+               static public bool Unsafe = false;
+               
+               static string MakeFQN (string nsn, string name)
                {
-                       ArrayList bases = iface.Bases;
-                       Type [] tbases;
-                       int i;
-
-                       error = false;
-                       if (bases == null)
-                               return null;
-                       
-                       tbases = new Type [bases.Count];
-                       i = 0;
-
-                       foreach (string name in iface.Bases){
-                               Type t;
-
-                               t = GetInterfaceTypeByName (name);
-                               if (t == null){
-                                       error = true;
-                                       return null;
-                               }
-                               
-                               tbases [i++] = t;
-                       }
+                       string prefix = (nsn == "" ? "" : nsn + ".");
 
-                       return tbases;
+                       return prefix + name;
                }
-               
-               //
-               // Creates the Interface @iface using the ModuleBuilder
-               //
-               // TODO:
-               //   Rework the way we recurse, because for recursive
-               //   definitions of interfaces (A:B and B:A) we report the
-               //   error twice, rather than once.  
+                      
+               // <remarks>
+               //   This function is used to resolve the hierarchy tree.
+               //   It processes interfaces, structs and classes in that order.
                //
-               TypeBuilder CreateInterface (Interface iface)
+               //   It creates the TypeBuilder's as it processes the user defined
+               //   types.  
+               // </remarks>
+               static public void ResolveTree ()
                {
-                       TypeBuilder tb = iface.TypeBuilder;
-                       Type [] ifaces;
-                       string name;
-                       bool error;
-
-                       if (tb != null)
-                               return tb;
-                       
-                       if (iface.InTransit)
-                               return null;
+                       //
+                       // Process the attribute types separately and before anything else
+                       //
+                       if (attribute_types != null)
+                               foreach (TypeContainer tc in attribute_types)
+                                       tc.DefineType ();
                        
-                       iface.InTransit = true;
-
-                       name = iface.Name;
-
-                       ifaces = GetInterfaceBases (iface, out error);
+                       //
+                       // Interfaces are processed next, as classes and
+                       // structs might inherit from an object or implement
+                       // a set of interfaces, we need to be able to tell
+                       // them appart by just using the TypeManager.
+                       //
+                       TypeContainer root = Tree.Types;
 
-                       if (error)
-                               return null;
+                       ArrayList ifaces = root.Interfaces;
+                       if (ifaces != null){
+                               foreach (Interface i in ifaces) 
+                                       i.DefineType ();
+                       }
 
-                       // FIXME: use the actual accesibility here, not
-                       // TypeAttributes.Public.
-                       tb = mb.DefineType (name,
-                                           TypeAttributes.Interface |
-                                           TypeAttributes.Public |
-                                           TypeAttributes.Abstract,
-                                           null,   // Parent Type
-                                           ifaces);
-                       iface.TypeBuilder = tb;
+                       
+                       foreach (TypeContainer tc in root.Types) 
+                               tc.DefineType ();
 
-                       type_manager.AddUserType (name, tb);
+                       if (root.Delegates != null)
+                               foreach (Delegate d in root.Delegates) 
+                                       d.DefineType ();
 
-                       iface.InTransit = false;
-                       return tb;
+                       if (root.Enums != null)
+                               foreach (Enum e in root.Enums)
+                                       e.DefineType ();
+                       
                }
 
-               string MakeFQN (string nsn, string name)
+               static void Error_TypeConflict (string name, Location loc)
                {
-                       string prefix = (nsn == "" ? "" : nsn + ".");
-
-                       return prefix + name;
+                       Report.Error (
+                               520, loc, "`" + name + "' conflicts with a predefined type");
                }
-                      
-               Type LookupInterfaceOrClass (string ns, string name, bool is_class, out bool error)
-               {
-                       TypeContainer parent;
-                       Type t;
 
-                       error = false;
-                       name = MakeFQN (ns, name);
-                       Console.WriteLine ("Attempting to locate " + name);
-
-                       t  = type_manager.LookupType (name);
-                       if (t != null)
-                               return t;
+               static void Error_TypeConflict (string name)
+               {
+                       Report.Error (
+                               520, "`" + name + "' conflicts with a predefined type");
+               }
 
-                       if (is_class){
-                               parent = (Class) tree.Classes [name];
-                       } else {
-                               parent = (Struct) tree.Structs [name];
+               //
+               // Resolves a single class during the corlib bootstrap process
+               //
+               static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
+               {
+                       object o = root.GetDefinition (name);
+                       if (o == null){
+                               Report.Error (518, "The predefined type `" + name + "' is not defined");
+                               return null;
                        }
 
-                       if (parent != null){
-                               t = CreateType (parent, is_class);
-                               if (t == null){
-                                       report.Error (146, "Class definition is circular: `"+name+"'");
-                                       error = true;
-                                       return null;
-                               }
+                       if (!(o is Class)){
+                               if (o is DeclSpace){
+                                       DeclSpace d = (DeclSpace) o;
 
-                               return t;
+                                       Error_TypeConflict (name, d.Location);
+                               } else
+                                       Error_TypeConflict (name);
+
+                               return null;
                        }
 
-                       return null;
+                       return ((DeclSpace) o).DefineType ();
                }
-               
+
                //
-               // returns the type for an interface or a class, this will recursively
-               // try to define the types that it depends on.
+               // Resolves a struct during the corlib bootstrap process
                //
-               Type GetInterfaceOrClass (TypeContainer tc, string name, bool is_class)
+               static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
                {
-                       Type t;
-                       bool error;
-
-                       //
-                       // Attempt to lookup the class on our namespace
-                       //
-                       t = LookupInterfaceOrClass (tc.Namespace.Name, name, is_class, out error);
-                       if (error)
-                               return null;
-                       
-                       if (t != null)
-                               return t;
+                       object o = root.GetDefinition (name);
+                       if (o == null){
+                               Report.Error (518, "The predefined type `" + name + "' is not defined");
+                               return;
+                       }
 
-                       //
-                       // Attempt to lookup the class on any of the `using'
-                       // namespaces
-                       //
-                       for (Namespace ns = tc.Namespace; ns != null; ns = ns.Parent){
-                               ArrayList using_list = ns.UsingTable;
+                       if (!(o is Struct)){
+                               if (o is DeclSpace){
+                                       DeclSpace d = (DeclSpace) o;
 
-                               if (using_list == null)
-                                       continue;
-                               
-                               foreach (string n in using_list){
-                                       t = LookupInterfaceOrClass (n, name, is_class, out error);
-                                       if (error)
-                                               return null;
+                                       Error_TypeConflict (name, d.Location);
+                               } else
+                                       Error_TypeConflict (name);
 
-                                       if (t != null)
-                                               return t;
-                               }
-                               
+                               return;
                        }
-                       report.Error (246, "Can not find type `"+name+"'");
-                       return null;
+
+                       ((DeclSpace) o).DefineType ();
                }
 
                //
-               // This function computes the Base class and also the
-               // list of interfaces that the class or struct @c implements.
+               // Resolves a struct during the corlib bootstrap process
                //
-               // The return value is an array (might be null) of
-               // interfaces implemented (as Types).
-               //
-               // The @parent argument is set to the parent object or null
-               // if this is `System.Object'. 
-               //
-               Type [] GetClassBases (TypeContainer tc, bool is_class, out Type parent, out bool error)
+               static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
                {
-                       ArrayList bases = tc.Bases;
-                       int count;
-                       int start, j, i;
-                       
-                       error = false;
-
-                       if (is_class)
-                               parent = null;
-                       else
-                               parent = value_type;
-
-                       if (bases == null){
-                               if (is_class){
-                                       if (stdlib)
-                                               parent = object_type;
-                                       else if (tc.Name != "System.Object")
-                                               parent = object_type;
-                               } else {
-                                       //
-                                       // If we are compiling our runtime,
-                                       // and we are defining ValueType, then our
-                                       // parent is `System.Object'.
-                                       //
-                                       if (!stdlib && tc. Name == "System.ValueType")
-                                               parent = object_type;
-                               }
-
-                               return null;
+                       object o = root.GetDefinition (name);
+                       if (o == null){
+                               Report.Error (518, "The predefined type `" + name + "' is not defined");
+                               return;
                        }
 
-                       //
-                       // Bases should be null if there are no bases at all
-                       //
-                       count = bases.Count;
-                       Debug.Assert (count > 0);
+                       if (!(o is Interface)){
+                               if (o is DeclSpace){
+                                       DeclSpace d = (DeclSpace) o;
 
-                       if (is_class){
-                               string name = (string) bases [0];
-                               Type first = GetInterfaceOrClass (tc, name, is_class);
+                                       Error_TypeConflict (name, d.Location);
+                               } else
+                                       Error_TypeConflict (name);
 
-                               if (first == null){
-                                       error = true;
-                                       return null;
-                               }
-                               
-                               if (first.IsClass){
-                                       parent = first;
-                                       start = 1;
-                               } else {
-                                       parent = object_type;
-                                       start = 0;
-                               }
-                       } else {
-                               start = 0;
+                               return;
                        }
 
-                       Type [] ifaces = new Type [count-start];
-                       
-                       for (i = start, j = 0; i < count; i++, j++){
-                               string name = (string) bases [i];
-                               Type t = GetInterfaceOrClass (tc, name, is_class);
-
-                               if (t == null){
-                                       error = true;
-                                       return null;
-                               }
+                       ((DeclSpace) o).DefineType ();
+               }
 
-                               if (is_class == false && !t.IsInterface){
-                                       report.Error (527, "In Struct `"+tc.Name+"', type `"+
-                                                     name+"' is not an interface");
-                                       error = true;
-                                       return null;
-                               }
-                               
-                               if (t.IsSealed) {
-                                       string detail = "";
-                                       
-                                       if (t.IsValueType)
-                                               detail = " (a class can not inherit from a struct)";
-                                                       
-                                       report.Error (509, "class `"+tc.Name+
-                                                     "': Cannot inherit from sealed class `"+
-                                                     bases [i]+"'"+detail);
-                                       error = true;
-                                       return null;
-                               }
+               //
+               // Resolves a delegate during the corlib bootstrap process
+               //
+               static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
+               {
+                       object o = root.GetDefinition (name);
+                       if (o == null){
+                               Report.Error (518, "The predefined type `" + name + "' is not defined");
+                               Environment.Exit (0);
+                       }
 
-                               if (t.IsClass) {
-                                       if (parent != null){
-                                               report.Error (527, "In Class `"+tc.Name+"', type `"+
-                                                             name+"' is not an interface");
-                                               error = true;
-                                               return null;
-                                       }
-                               }
-                               
-                               ifaces [j] = t;
+                       if (!(o is Delegate)){
+                               Error_TypeConflict (name);
+                               return;
                        }
 
-                       return ifaces;
+                       ((DeclSpace) o).DefineType ();
                }
+               
 
-               // <remarks>
-               //   Creates the TypeBuilder for the TypeContainer @tc (a Class or a Struct)
-               // </remarks>
-               //
-               TypeBuilder CreateType (TypeContainer tc, bool is_class)
+               /// <summary>
+               ///    Resolves the core types in the compiler when compiling with --nostdlib
+               /// </summary>
+               static public void ResolveCore ()
                {
-                       TypeBuilder tb = tc.TypeBuilder;
-                       Type parent;
-                       Type [] ifaces;
-                       bool error;
-                       string name;
-                       
-                       if (tb != null)
-                               return tb;
+                       TypeContainer root = Tree.Types;
 
-                       if (tc.InTransit)
-                               return null;
-                       tc.InTransit = true;
-
-                       name = tc.Name;
+                       TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
+                       TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
+                       TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
+                       
+                       string [] interfaces_first_stage = {
+                               "System.IComparable", "System.ICloneable",
+                               "System.IConvertible",
+                               
+                               "System.Collections.IEnumerable",
+                               "System.Collections.ICollection",
+                               "System.Collections.IEnumerator",
+                               "System.Collections.IList", 
+                               "System.IAsyncResult",
+                               "System.IDisposable",
+                               
+                               "System.Runtime.Serialization.ISerializable",
 
-                       ifaces = GetClassBases (tc, is_class, out parent, out error); 
+                               "System.Reflection.IReflect",
+                               "System.Reflection.ICustomAttributeProvider"
+                       };
 
-                       if (error)
-                               return null;
+                       foreach (string iname in interfaces_first_stage)
+                               BootstrapCorlib_ResolveInterface (root, iname);
 
-                       tb = mb.DefineType (name,
-                                           tc.TypeAttr | TypeAttributes.Class,
-                                           parent,
-                                           ifaces);
+                       //
+                       // These are the base value types
+                       //
+                       string [] structs_first_stage = {
+                               "System.Byte",    "System.SByte",
+                               "System.Int16",   "System.UInt16",
+                               "System.Int32",   "System.UInt32",
+                               "System.Int64",   "System.UInt64",
+                       };
 
-                       tc.TypeBuilder = tb;
-                       type_manager.AddUserType (name, tb);
-                       tc.InTransit = false;
-                       
-                       return tb;
-               }
-
-               // <remarks>
-               //   This function is used to resolve the hierarchy tree.
-               //   It processes interfaces, structs and classes in that order.
-               //
-               //   It creates the TypeBuilder's as it processes the user defined
-               //   types.  
-               // </remarks>
-               public void ResolveTree ()
-               {
-                       Hashtable ifaces, classes, structs;
+                       foreach (string cname in structs_first_stage)
+                               BootstrapCorlib_ResolveStruct (root, cname);
 
                        //
-                       // Interfaces are processed first, as classes and
-                       // structs might inherit from an object or implement
-                       // a set of interfaces, we need to be able to tell
-                       // them appart by just using the TypeManager.
+                       // Now, we can load the enumerations, after this point,
+                       // we can use enums.
                        //
-                       ifaces = tree.Interfaces;
-                       if (ifaces != null){
-                               foreach (DictionaryEntry de in ifaces)
-                                       CreateInterface ((Interface) de.Value);
-                       }
-
+                       TypeManager.InitEnumUnderlyingTypes ();
+
+                       string [] structs_second_stage = {
+                               "System.Single",  "System.Double",
+                               "System.Char",    "System.Boolean",
+                               "System.Decimal", "System.Void",
+                               "System.RuntimeFieldHandle",
+                               "System.RuntimeTypeHandle",
+                               "System.IntPtr"
+                       };
+                       
+                       foreach (string cname in structs_second_stage)
+                               BootstrapCorlib_ResolveStruct (root, cname);
+                       
                        //
-                       // Process structs and classes next.  Our code assumes
-                       // this order (just for error reporting purposes).
+                       // These are classes that depends on the core interfaces
                        //
-                       structs = tree.Structs;
-                       if (structs != null){
-                               foreach (DictionaryEntry de in structs)
-                                       CreateType ((Struct) de.Value, false);
-                       }
+                       string [] classes_second_stage = {
+                               "System.Reflection.MemberInfo",
+                               "System.Type",
+                               "System.Exception",
 
-                       classes = tree.Classes;
-                       if (classes != null){
-                               foreach (DictionaryEntry de in classes)
-                                       CreateType ((Class) de.Value, true);
-                       }
+                               //
+                               // These are not really important in the order, but they
+                               // are used by the compiler later on (typemanager/CoreLookupType-d)
+                               //
+                               "System.Runtime.CompilerServices.RuntimeHelpers",
+                               "System.Reflection.DefaultMemberAttribute",
+                               "System.Threading.Monitor",
+                               
+                               "System.AttributeUsageAttribute",
+                               "System.Runtime.InteropServices.DllImportAttribute",
+                               "System.Runtime.CompilerServices.MethodImplAttribute",
+                               "System.Runtime.InteropServices.MarshalAsAttribute",
+                               "System.Diagnostics.ConditionalAttribute",
+                               "System.ObsoleteAttribute",
+                               "System.ParamArrayAttribute",
+                               "System.Security.UnverifiableCodeAttribute",
+                               "System.Runtime.CompilerServices.IndexerNameAttribute",
+                               "System.Runtime.InteropServices.InAttribute"
+                       };
+
+                       // We must store them here before calling BootstrapCorlib_ResolveDelegate.
+                       TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
+                       TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
+                       TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
+                       TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
+                       TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
+                       
+                       foreach (string cname in classes_second_stage)
+                               BootstrapCorlib_ResolveClass (root, cname);
+
+                       BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
                }
                        
                // <summary>
@@ -507,60 +375,256 @@ namespace CIR {
                //
                // <remarks>
                //   We usually use TypeBuilder types.  When we are done
-               //   creating the type (which will happen after we have addded
+               //   creating the type (which will happen after we have added
                //   methods, fields, etc) we need to "Define" them before we
                //   can save the Assembly
                // </remarks>
-               public void CloseTypes ()
+               static public void CloseTypes ()
                {
-                       foreach (TypeBuilder t in type_manager.UserTypes){
-                               t.CreateType ();
+                       TypeContainer root = Tree.Types;
+                       
+                       ArrayList ifaces = root.Interfaces;
+
+                       if (root.Enums != null)
+                               foreach (Enum en in root.Enums)
+                                       en.CloseType ();
+
+                       if (attribute_types != null)
+                               foreach (TypeContainer tc in attribute_types)
+                                       tc.CloseType ();
+                       
+                       foreach (Interface iface in interface_resolve_order)
+                               iface.CloseType ();
+
+                       //
+                       // We do this in two passes, first we close the structs,
+                       // then the classes, because it seems the code needs it this
+                       // way.  If this is really what is going on, we should probably
+                       // make sure that we define the structs in order as well.
+                       //
+                       foreach (TypeContainer tc in type_container_resolve_order){
+                               if (tc is Struct && tc.Parent == tree.Types){
+                                       tc.CloseType ();
+                               }
+                       }
+
+                       foreach (TypeContainer tc in type_container_resolve_order){
+                               if (!(tc is Struct && tc.Parent == tree.Types))
+                                       tc.CloseType ();                                        
+                       }
+                       
+                       if (root.Delegates != null)
+                               foreach (Delegate d in root.Delegates)
+                                       d.CloseType ();
+
+
+                       //
+                       // If we have a <PrivateImplementationDetails> class, close it
+                       //
+                       if (impl_details_class != null){
+                               impl_details_class.CreateType ();
                        }
                }
 
                //
-               // Public function used to locate types, this can only
-               // be used after the ResolveTree function has been invoked.
+               // This idea is from Felix Arrese-Igor
                //
-               // Returns: Type or null if they type can not be found.
+               // Returns : the implicit parent of a composite namespace string
+               //   eg. Implicit parent of A.B is A
                //
-               public Type LookupType (TypeContainer tc, string name, bool silent)
+               static public string ImplicitParent (string ns)
                {
-                       Type t;
+                       int i = ns.LastIndexOf (".");
+                       if (i < 0)
+                               return null;
+                       
+                       return ns.Substring (0, i);
+               }
 
-                       t = type_manager.LookupType (MakeFQN (tc.Namespace.Name, name));
+               static Type NamespaceLookup (Namespace curr_ns, string name, Location loc)
+               {
+                       Type t;
+                       
+                       //
+                       // Try in the current namespace and all its implicit parents
+                       //
+                       for (string ns = curr_ns.Name; ns != null; ns = ImplicitParent (ns)) {
+                               t = TypeManager.LookupType (MakeFQN (ns, name));
+                               if (t != null)
+                                       return t;
+                       }
+                       
+                       //
+                       // It's possible that name already is fully qualified. So we do
+                       // a simple direct lookup without adding any namespace names
+                       //
+                       t = TypeManager.LookupType (name); 
                        if (t != null)
                                return t;
 
-                       for (Namespace ns = tc.Namespace; ns != null; ns = ns.Parent){
+                       //
+                       // Try the aliases in the current namespace
+                       //
+                       string alias = curr_ns.LookupAlias (name);
+
+                       if (alias != null) {
+                               t = TypeManager.LookupType (alias);
+                               if (t != null)
+                                       return t;
+
+                               t = TypeManager.LookupType (MakeFQN (alias, name));
+                               if (t != null)
+                                       return t;
+                       }
+                       
+                       for (Namespace ns = curr_ns; ns != null; ns = ns.Parent) {
+                               //
+                               // Look in the namespace ns
+                               //
+                               t = TypeManager.LookupType (MakeFQN (ns.Name, name));
+                               if (t != null)
+                                       return t;
+                               
+                               //
+                               // Then try with the using clauses
+                               //
                                ArrayList using_list = ns.UsingTable;
 
                                if (using_list == null)
                                        continue;
 
-                               foreach (string n in using_list){
-                                       t = type_manager.LookupType (MakeFQN (n, name));
+                               Type match = null;
+                               foreach (Namespace.UsingEntry ue in using_list) {
+                                       match = TypeManager.LookupType (MakeFQN (ue.Name, name));
+                                       if (match != null){
+                                               if (t != null){
+                                                       DeclSpace.Error_AmbiguousTypeReference (loc, name, t, match);
+                                                       return null;
+                                               }
+                                               
+                                               t = match;
+                                               ue.Used = true;
+                                       }
+                               }
+                               if (t != null)
+                                       return t;
+
+                               //
+                               // Try with aliases
+                               //
+                               string a = ns.LookupAlias (name);
+                               if (a != null) {
+                                       t = TypeManager.LookupType (a);
+                                       if (t != null)
+                                               return t;
+
+                                       t = TypeManager.LookupType (MakeFQN (a, name));
                                        if (t != null)
                                                return t;
                                }
                        }
 
+                       return null;
+               }
+               
+               //
+               // Public function used to locate types, this can only
+               // be used after the ResolveTree function has been invoked.
+               //
+               // Returns: Type or null if they type can not be found.
+               //
+               // Come to think of it, this should be a DeclSpace
+               //
+               static public Type LookupType (DeclSpace ds, string name, bool silent, Location loc)
+               {
+                       Type t;
+
+                       if (ds.Cache.Contains (name)){
+                               t = (Type) ds.Cache [name];
+                               if (t != null)
+                                       return t;
+                       } else {
+                               //
+                               // For the case the type we are looking for is nested within this one
+                               // or is in any base class
+                               //
+                               DeclSpace containing_ds = ds;
+                               while (containing_ds != null){
+                                       Type current_type = containing_ds.TypeBuilder;
+                                       
+                                       while (current_type != null) {
+                                               //
+                                               // nested class
+                                               //
+                                               t = TypeManager.LookupType (current_type.FullName + "." + name);
+                                               if (t != null){
+                                                       ds.Cache [name] = t;
+                                                       return t;
+                                               }
+                                               
+                                               current_type = current_type.BaseType;
+                                       }
+                                       
+                                       containing_ds = containing_ds.Parent;
+                               }
+                               
+                               t = NamespaceLookup (ds.Namespace, name, loc);
+                               if (t != null){
+                                       ds.Cache [name] = t;
+                                       return t;
+                               }
+                       }
+
                        if (!silent)
-                               report.Error (246, "Can not find type `"+name+"'");
+                               Report.Error (246, loc, "Cannot find type `"+name+"'");
                        
                        return null;
                }
 
-               public Type LookupType (TypeContainer tc, string name)
+               // <summary>
+               //   This is the silent version of LookupType, you can use this
+               //   to `probe' for a type
+               // </summary>
+               static public Type LookupType (TypeContainer tc, string name, Location loc)
                {
-                       return LookupType (tc, name, true);
+                       return LookupType (tc, name, true, loc);
                }
 
-               public bool IsNamespace (string name)
+               static public bool IsNamespace (string name)
                {
-                       Console.WriteLine ("FIXME: IsNamespace returns false always!");
+                       Namespace ns;
+
+                       if (tree.Namespaces != null){
+                               ns = (Namespace) tree.Namespaces [name];
+
+                               if (ns != null)
+                                       return true;
+                       }
+
                        return false;
                }
+
+               static void Report1530 (Location loc)
+               {
+                       Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
+               }
+               
+               static public void PopulateCoreType (TypeContainer root, string name)
+               {
+                       DeclSpace ds = (DeclSpace) root.GetDefinition (name);
+
+                       ds.DefineMembers (root);
+                       ds.Define (root);
+               }
+               
+               static public void BootCorlib_PopulateCoreTypes ()
+               {
+                       TypeContainer root = tree.Types;
+
+                       PopulateCoreType (root, "System.Object");
+                       PopulateCoreType (root, "System.ValueType");
+                       PopulateCoreType (root, "System.Attribute");
+               }
                
                // <summary>
                //   Populates the structs and classes with fields and methods
@@ -568,64 +632,218 @@ namespace CIR {
                //
                // This is invoked after all interfaces, structs and classes
                // have been defined through `ResolveTree' 
-               public void PopulateTypes ()
+               static public void PopulateTypes ()
                {
-                       Hashtable ifaces, classes;
+                       TypeContainer root = Tree.Types;
+
+                       if (attribute_types != null)
+                               foreach (TypeContainer tc in attribute_types)
+                                       tc.DefineMembers (root);
                        
-                       if ((ifaces = tree.Interfaces) != null){
-                               foreach (DictionaryEntry de in ifaces){
-                                       Interface iface = (Interface) de.Value;
+                       if (interface_resolve_order != null){
+                               foreach (Interface iface in interface_resolve_order)
+                                       if ((iface.ModFlags & Modifiers.NEW) == 0)
+                                               iface.DefineMembers (root);
+                                       else
+                                               Report1530 (iface.Location);
+                       }
 
-                                       iface.Populate ();
-                               }
+
+                       if (type_container_resolve_order != null){
+                               if (RootContext.StdLib){
+                                       foreach (TypeContainer tc in type_container_resolve_order) {
+                                               if ((tc.ModFlags & Modifiers.NEW) == 0)
+                                                       tc.DefineMembers (root);
+                                               else
+                                                       Report1530 (tc.Location);
+                                       }
+                               } else {
+                                       foreach (TypeContainer tc in type_container_resolve_order) {
+                                               // When compiling corlib, these types have already been
+                                               // populated from BootCorlib_PopulateCoreTypes ().
+                                               if (((tc.Name == "System.Object") ||
+                                                    (tc.Name == "System.Attribute") ||
+                                                    (tc.Name == "System.ValueType")))
+                                               continue;
+
+                                               if ((tc.ModFlags & Modifiers.NEW) == 0)
+                                                       tc.DefineMembers (root);
+                                               else
+                                                       Report1530 (tc.Location);
+                                       }
+                               } 
                        }
 
-                       if ((classes = tree.Classes) != null){
-                               foreach (DictionaryEntry de in classes){
-                                       TypeContainer tc = (TypeContainer) de.Value;
+                       ArrayList delegates = root.Delegates;
+                       if (delegates != null){
+                               foreach (Delegate d in delegates)
+                                       if ((d.ModFlags & Modifiers.NEW) == 0)
+                                               d.DefineMembers (root);
+                                       else
+                                               Report1530 (d.Location);
+                       }
 
-                                       tc.Populate ();
-                               }
+                       ArrayList enums = root.Enums;
+                       if (enums != null){
+                               foreach (Enum en in enums)
+                                       if ((en.ModFlags & Modifiers.NEW) == 0)
+                                               en.DefineMembers (root);
+                                       else
+                                               Report1530 (en.Location);
                        }
                }
 
-               public void EmitCode ()
+               static public void DefineTypes ()
                {
-                       Hashtable classes;
+                       TypeContainer root = Tree.Types;
+
+                       if (attribute_types != null)
+                               foreach (TypeContainer tc in attribute_types)
+                                       tc.Define (root);
                        
-                       if ((classes = tree.Classes) != null){
-                               foreach (DictionaryEntry de in classes){
-                                       TypeContainer tc = (TypeContainer) de.Value;
+                       if (interface_resolve_order != null){
+                               foreach (Interface iface in interface_resolve_order)
+                                       if ((iface.ModFlags & Modifiers.NEW) == 0)
+                                               iface.Define (root);
+                       }
 
-                                       tc.Emit ();
+
+                       if (type_container_resolve_order != null){
+                               foreach (TypeContainer tc in type_container_resolve_order) {
+                                       // When compiling corlib, these types have already been
+                                       // populated from BootCorlib_PopulateCoreTypes ().
+                                       if (!RootContext.StdLib &&
+                                           ((tc.Name == "System.Object") ||
+                                            (tc.Name == "System.Attribute") ||
+                                            (tc.Name == "System.ValueType")))
+                                               continue;
+
+                                       if ((tc.ModFlags & Modifiers.NEW) == 0)
+                                               tc.Define (root);
                                }
                        }
-               }
-               
-               // <summary>
-               //   Compiling against Standard Libraries property.
-               // </summary>
-               public bool StdLib {
-                       get {
-                               return stdlib;
+
+                       ArrayList delegates = root.Delegates;
+                       if (delegates != null){
+                               foreach (Delegate d in delegates)
+                                       if ((d.ModFlags & Modifiers.NEW) == 0)
+                                               d.Define (root);
                        }
 
-                       set {
-                               stdlib = value;
+                       ArrayList enums = root.Enums;
+                       if (enums != null){
+                               foreach (Enum en in enums)
+                                       if ((en.ModFlags & Modifiers.NEW) == 0)
+                                               en.Define (root);
                        }
                }
 
-               public Report Report {
-                       get {
-                               return report;
+               static public void EmitCode ()
+               {
+                       //
+                       // Because of the strange way in which we do things, global
+                       // attributes must be processed first.
+                       //
+                       if (global_attributes.Count > 0){
+                               AssemblyBuilder ab = CodeGen.AssemblyBuilder;
+                               TypeContainer dummy = new TypeContainer (null, "", new Location (-1));
+                               EmitContext temp_ec = new EmitContext (
+                                       dummy, Mono.CSharp.Location.Null, null, null, 0, false);
+                       
+                               foreach (DictionaryEntry de in global_attributes){
+                                       Namespace ns = (Namespace) de.Key;
+                                       Attributes attrs = (Attributes) de.Value;
+                                       
+                                       dummy.Namespace = ns;
+                                       Attribute.ApplyAttributes (temp_ec, ab, ab, attrs);
+                               }
                        }
-               }
 
+                       if (attribute_types != null)
+                               foreach (TypeContainer tc in attribute_types)
+                                       tc.Emit ();
+                       
+                       if (type_container_resolve_order != null) {
+                               foreach (TypeContainer tc in type_container_resolve_order)
+                                       tc.EmitConstants ();
+                               
+                               foreach (TypeContainer tc in type_container_resolve_order)
+                                       tc.Emit ();
+                       }
+                       
+                       if (Unsafe) {
+                               if (TypeManager.unverifiable_code_ctor == null) {
+                                       Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
+                                       return;
+                               }
+                               
+                               CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor,
+                                                                                       new object [0]);
+                               CodeGen.ModuleBuilder.SetCustomAttribute (cb);
+                       }
+               }
+               
                //
                // Public Field, used to track which method is the public entry
                // point.
                //
-               public MethodInfo EntryPoint;
+               static public MethodInfo EntryPoint;
+
+                //
+                // Track the location of the entry point.
+                //
+                static public Location EntryPointLocation;
+
+               //
+               // These are used to generate unique names on the structs and fields.
+               //
+               static int field_count;
+               
+               //
+               // Makes an initialized struct, returns the field builder that
+               // references the data.  Thanks go to Sergey Chaban for researching
+               // how to do this.  And coming up with a shorter mechanism than I
+               // was able to figure out.
+               //
+               // This works but makes an implicit public struct $ArrayType$SIZE and
+               // makes the fields point to it.  We could get more control if we did
+               // use instead:
+               //
+               // 1. DefineNestedType on the impl_details_class with our struct.
+               //
+               // 2. Define the field on the impl_details_class
+               //
+               static public FieldBuilder MakeStaticData (byte [] data)
+               {
+                       FieldBuilder fb;
+                       int size = data.Length;
+                       
+                       if (impl_details_class == null)
+                               impl_details_class = CodeGen.ModuleBuilder.DefineType (
+                                       "<PrivateImplementationDetails>", TypeAttributes.NotPublic, TypeManager.object_type);
+
+                       fb = impl_details_class.DefineInitializedData (
+                               "$$field-" + (field_count++), data,
+                               FieldAttributes.Static | FieldAttributes.Assembly);
+                       
+                       return fb;
+               }
+
+               //
+               // Adds a global attribute that was declared in `container', 
+               // the attribute is in `attr', and it was defined at `loc'
+               //
+               static public void AddGlobalAttributeSection (TypeContainer container, AttributeSection attr)
+               {
+                       Namespace ns = container.Namespace;
+                       Attributes a = (Attributes) global_attributes [ns];
+
+                       if (a == null)
+                               global_attributes [ns] = new Attributes (attr);
+                       else
+                               a.AddAttributeSection (attr);
+               }
        }
 }
              
+