2007-01-25 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / namespace.cs
index 0f9206ab3528a3e33bc6fd0752243806034c1477..af9c93b0d6b3744526fb375606039b4e942eecf1 100644 (file)
 //
 // Author:
 //   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@seznam.cz)
 //
 // (C) 2001 Ximian, Inc.
 //
 using System;
 using System.Collections;
+using System.Collections.Specialized;
+using System.Reflection;
 
 namespace Mono.CSharp {
 
+       public class RootNamespace : Namespace {
+               static MethodInfo get_namespaces_method;
+
+               string alias_name;
+               Assembly referenced_assembly;
+
+               Hashtable all_namespaces;
+
+               static Hashtable root_namespaces;
+               public static GlobalRootNamespace Global;
+               
+               static RootNamespace ()
+               {
+                       get_namespaces_method = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance | BindingFlags.NonPublic);
+
+                       Reset ();
+               }
+
+               public static void Reset ()
+               {
+                       root_namespaces = new Hashtable ();
+                       Global = new GlobalRootNamespace ();
+                       root_namespaces ["global"] = Global;
+               }
+
+               protected RootNamespace (string alias_name, Assembly assembly)
+                       : base (null, String.Empty)
+               {
+                       this.alias_name = alias_name;
+                       referenced_assembly = assembly;
+
+                       all_namespaces = new Hashtable ();
+                       all_namespaces.Add ("", this);
+
+                       if (referenced_assembly != null)
+                               ComputeNamespaces (this.referenced_assembly);
+               }
+
+               public static void DefineRootNamespace (string name, Assembly assembly)
+               {
+                       if (name == "global") {
+                               // FIXME: Add proper error number
+                               Report.Error (-42, "Cannot define an external alias named `global'");
+                               return;
+                       }
+                       RootNamespace retval = GetRootNamespace (name);
+                       if (retval == null || retval.referenced_assembly != assembly)
+                               root_namespaces [name] = new RootNamespace (name, assembly);
+               }
+
+               public static RootNamespace GetRootNamespace (string name)
+               {
+                       return (RootNamespace) root_namespaces [name];
+               }
+
+               public virtual Type LookupTypeReflection (string name, Location loc)
+               {
+                       return GetTypeInAssembly (referenced_assembly, name);
+               }
+
+               public void RegisterNamespace (Namespace child)
+               {
+                       if (child != this)
+                               all_namespaces.Add (child.Name, child);
+               }
+
+               public bool IsNamespace (string name)
+               {
+                       return all_namespaces.Contains (name);
+               }
+
+               protected void EnsureNamespace (string dotted_name)
+               {
+                       if (dotted_name != null && dotted_name.Length != 0 && ! IsNamespace (dotted_name))
+                               GetNamespace (dotted_name, true);
+               }
+
+               protected void ComputeNamespaces (Assembly assembly)
+               {
+                       if (get_namespaces_method != null) {
+                               string [] namespaces = (string []) get_namespaces_method.Invoke (assembly, null);
+                               foreach (string ns in namespaces)
+                                       EnsureNamespace (ns);
+                               return;
+                       }
+
+                       foreach (Type t in assembly.GetExportedTypes ())
+                               EnsureNamespace (t.Namespace);
+               }
+               
+               protected static Type GetTypeInAssembly (Assembly assembly, string name)
+               {
+                       Type t = assembly.GetType (name);
+                       if (t == null)
+                               return null;
+
+                       if (t.IsPointer)
+                               throw new InternalErrorException ("Use GetPointerType() to get a pointer");
+
+                       TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
+                       if (ta == TypeAttributes.NestedPrivate)
+                               return null;
+
+                       if ((ta == TypeAttributes.NotPublic ||
+                            ta == TypeAttributes.NestedAssembly ||
+                            ta == TypeAttributes.NestedFamANDAssem) &&
+                           !TypeManager.IsFriendAssembly (t.Assembly))
+                               return null;
+
+                       return t;
+               }
+
+               public override string ToString ()
+               {
+                       return String.Format ("RootNamespace ({0}::)", alias_name);
+               }
+
+               public override string GetSignatureForError ()
+               {
+                       return alias_name + "::";
+               }
+       }
+
+       public class GlobalRootNamespace : RootNamespace {
+               Assembly [] assemblies;
+               Module [] modules;
+
+               public GlobalRootNamespace ()
+                       : base ("global", null)
+               {
+                       assemblies = new Assembly [0];
+               }
+
+               public Assembly [] Assemblies {
+                       get { return assemblies; }
+               }
+
+               public Module [] Modules {
+                       get { return modules; }
+               }
+
+               public void AddAssemblyReference (Assembly a)
+               {
+                       foreach (Assembly assembly in assemblies) {
+                               if (a == assembly)
+                                       return;
+                       }
+
+                       int top = assemblies.Length;
+                       Assembly [] n = new Assembly [top + 1];
+                       assemblies.CopyTo (n, 0);
+                       n [top] = a;
+                       assemblies = n;
+
+                       ComputeNamespaces (a);
+               }
+
+               public void AddModuleReference (Module m)
+               {
+                       int top = modules != null ? modules.Length : 0;
+                       Module [] n = new Module [top + 1];
+                       if (modules != null)
+                               modules.CopyTo (n, 0);
+                       n [top] = m;
+                       modules = n;
+
+                       if (m == CodeGen.Module.Builder)
+                               return;
+
+                       foreach (Type t in m.GetTypes ())
+                               EnsureNamespace (t.Namespace);
+               }
+
+               public override void Error_NamespaceDoesNotExist(DeclSpace ds, Location loc, string name)
+               {
+                       Report.Error (400, loc, "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
+                               name);
+               }
+
+               public override Type LookupTypeReflection (string name, Location loc)
+               {
+                       Type found_type = null;
+               
+                       foreach (Assembly a in assemblies) {
+                               Type t = GetTypeInAssembly (a, name);
+                               if (t == null)
+                                       continue;
+                                       
+                               if (found_type == null) {
+                                       found_type = t;
+                                       continue;
+                               }
+
+                               Report.SymbolRelatedToPreviousError (found_type);
+                               Report.SymbolRelatedToPreviousError (t);
+                               Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
+                                       
+                               return found_type;
+                       }
+
+                       if (modules != null) {
+                               foreach (Module module in modules) {
+                                       Type t = module.GetType (name);
+                                       if (t == null)
+                                               continue;
+
+                                       if (found_type == null) {
+                                               found_type = t;
+                                               continue;
+                                       }
+
+                                       Report.SymbolRelatedToPreviousError (found_type);
+                                       if (loc.IsNull) {
+                                               DeclSpace ds = TypeManager.LookupDeclSpace (t);
+                                               Report.Warning (1685, 1, ds.Location, "The type `{0}' conflicts with the predefined type `{1}' and will be ignored",
+                                                       ds.GetSignatureForError (), TypeManager.CSharpName (found_type));
+                                               return found_type;
+                                       }
+                                       Report.SymbolRelatedToPreviousError (t);
+                                       Report.Warning (436, 2, loc, "The type `{0}' conflicts with the imported type `{1}'. Ignoring the imported type definition",
+                                               TypeManager.CSharpName (t), TypeManager.CSharpName (found_type));
+                                       return t;
+                               }
+                       }
+
+                       return found_type;
+               }
+       }
+
        /// <summary>
        ///   Keeps track of the namespaces defined in the C# code.
        ///
        ///   This is an Expression to allow it to be referenced in the
        ///   compiler parse/intermediate tree during name resolution.
        /// </summary>
-       public class Namespace : FullNamedExpression, IAlias {
-               static ArrayList all_namespaces;
-               static Hashtable namespaces_map;
+       public class Namespace : FullNamedExpression {
                
                Namespace parent;
                string fullname;
-               ArrayList entries;
                Hashtable namespaces;
-               Hashtable defined_names;
+               IDictionary declspaces;
                Hashtable cached_types;
+               RootNamespace root;
 
                public readonly MemberName MemberName;
 
-               public static Namespace Root;
-
-               static Namespace ()
-               {
-                       Reset ();
-               }
-
-               public static void Reset ()
-               {
-                       all_namespaces = new ArrayList ();
-                       namespaces_map = new Hashtable ();
-
-                       Root = new Namespace (null, "");
-               }
-
                /// <summary>
                ///   Constructor Takes the current namespace and the
                ///   name.  This is bootstrapped with parent == null
@@ -54,11 +269,19 @@ namespace Mono.CSharp {
                {
                        // Expression members.
                        this.eclass = ExprClass.Namespace;
-                       this.Type = null;
+                       this.Type = typeof (Namespace);
                        this.loc = Location.Null;
 
                        this.parent = parent;
 
+                       if (parent != null)
+                               this.root = parent.root;
+                       else
+                               this.root = this as RootNamespace;
+
+                       if (this.root == null)
+                               throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
+                       
                        string pname = parent != null ? parent.Name : "";
                                
                        if (pname == "")
@@ -66,22 +289,20 @@ namespace Mono.CSharp {
                        else
                                fullname = parent.Name + "." + name;
 
+                       if (fullname == null)
+                               throw new InternalErrorException ("Namespace has a null fullname");
+
                        if (parent != null && parent.MemberName != MemberName.Null)
                                MemberName = new MemberName (parent.MemberName, name);
-                       else if (name == "")
+                       else if (name.Length == 0)
                                MemberName = MemberName.Null;
                        else
                                MemberName = new MemberName (name);
 
-                       entries = new ArrayList ();
                        namespaces = new Hashtable ();
-                       defined_names = new Hashtable ();
                        cached_types = new Hashtable ();
 
-                       all_namespaces.Add (this);
-                       if (namespaces_map.Contains (fullname))
-                               return;
-                       namespaces_map [fullname] = true;
+                       root.RegisterNamespace (this);
                }
 
                public override Expression DoResolve (EmitContext ec)
@@ -89,14 +310,48 @@ namespace Mono.CSharp {
                        return this;
                }
 
+               public virtual void Error_NamespaceDoesNotExist (DeclSpace ds, Location loc, string name)
+               {
+                       if (name.IndexOf ('`') > 0) {
+                               FullNamedExpression retval = Lookup (ds, SimpleName.RemoveGenericArity (name), loc);
+                               if (retval != null) {
+                                       Error_TypeArgumentsCannotBeUsed (retval.Type, loc, "type");
+                                       return;
+                               }
+                       } else {
+                               Type t = LookForAnyGenericType (name);
+                               if (t != null) {
+                                       Error_InvalidNumberOfTypeArguments (t, loc);
+                                       return;
+                               }
+                       }
+
+                       Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
+                               name, FullName);
+               }
+
+               public static void Error_InvalidNumberOfTypeArguments (Type t, Location loc)
+               {
+                       Report.SymbolRelatedToPreviousError (t);
+                       Report.Error (305, loc, "Using the generic type `{0}' requires `{1}' type argument(s)",
+                               TypeManager.CSharpName(t), TypeManager.GetNumberOfTypeArguments(t).ToString());
+               }
+
+               public static void Error_TypeArgumentsCannotBeUsed(Type t, Location loc, string symbol)
+               {
+                       Report.SymbolRelatedToPreviousError(t);
+                       Report.Error(308, loc, "The non-generic {0} `{1}' cannot be used with the type argument(s)",
+                               symbol, TypeManager.CSharpName(t));
+               }
+
                public override void Emit (EmitContext ec)
                {
                        throw new InternalErrorException ("Expression tree referenced namespace " + fullname + " during Emit ()");
                }
 
-               public static bool IsNamespace (string name)
+               public override string GetSignatureForError ()
                {
-                       return namespaces_map [name] != null;
+                       return Name;
                }
                
                public Namespace GetNamespace (string name, bool create)
@@ -125,23 +380,14 @@ namespace Mono.CSharp {
                        return ns;
                }
 
-               public static Namespace LookupNamespace (string name, bool create)
-               {
-                       return Root.GetNamespace (name, create);
-               }
-
-               public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
+               TypeExpr LookupType (string name, Location loc)
                {
-                       Namespace ns = GetNamespace (name, false);
-                       if (ns != null)
-                               return ns;
+                       if (cached_types.Contains (name))
+                               return cached_types [name] as TypeExpr;
 
-                       TypeExpr te;
-                       if (cached_types.Contains (name)) {
-                               te = (TypeExpr) cached_types [name];
-                       } else {
-                               Type t;
-                               DeclSpace tdecl = defined_names [name] as DeclSpace;
+                       Type t = null;
+                       if (declspaces != null) {
+                               DeclSpace tdecl = declspaces [name] as DeclSpace;
                                if (tdecl != null) {
                                        //
                                        // Note that this is not:
@@ -154,49 +400,67 @@ namespace Mono.CSharp {
                                        //
                                        tdecl.DefineType ();
                                        t = tdecl.TypeBuilder;
-                               } else {
-                                       string lookup = this == Namespace.Root ? name : fullname + "." + name;
-                                       t = TypeManager.LookupTypeReflection (lookup);
                                }
-                               te = t == null ? null : new TypeExpression (t, Location.Null);
-                               cached_types [name] = te;
                        }
+                       string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
+                       Type rt = root.LookupTypeReflection (lookup, loc);
 
-                       if (te != null && ds != null && !ds.CheckAccessLevel (te.Type))
-                               return null;
+                       // HACK: loc.IsNull when the type is core type
+                       if (t == null || (rt != null && loc.IsNull))
+                               t = rt;
 
+                       TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
+                       cached_types [name] = te;
                        return te;
                }
 
-               public void AddNamespaceEntry (NamespaceEntry entry)
+               ///
+               /// Used for better error reporting only
+               /// 
+               public Type LookForAnyGenericType (string typeName)
                {
-                       entries.Add (entry);
+                       if (declspaces == null)
+                               return null;
+
+                       typeName = SimpleName.RemoveGenericArity (typeName);
+
+                       foreach (DictionaryEntry de in declspaces) {
+                               string type_item = (string) de.Key;
+                               int pos = type_item.LastIndexOf ('`');
+                               if (pos == typeName.Length && String.Compare (typeName, 0, type_item, 0, pos) == 0)
+                                       return ((DeclSpace) de.Value).TypeBuilder;
+                       }
+                       return null;
                }
 
-               public void DefineName (string name, IAlias o)
+               public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
                {
-                       defined_names.Add (name, o);
+                       if (namespaces.Contains (name))
+                               return (Namespace) namespaces [name];
+
+                       TypeExpr te = LookupType (name, loc);
+                       if (te == null || !ds.CheckAccessLevel (te.Type))
+                               return null;
+
+                       return te;
                }
 
-               static public ArrayList UserDefinedNamespaces {
-                       get {
-                               return all_namespaces;
-                       }
+               public void AddDeclSpace (string name, DeclSpace ds)
+               {
+                       if (declspaces == null)
+                               declspaces = new HybridDictionary ();
+                       declspaces.Add (name, ds);
                }
 
                /// <summary>
                ///   The qualified name of the current namespace
                /// </summary>
                public string Name {
-                       get {
-                               return fullname;
-                       }
+                       get { return fullname; }
                }
 
                public override string FullName {
-                       get {
-                               return fullname;
-                       }
+                       get { return fullname; }
                }
 
                /// <summary>
@@ -204,51 +468,16 @@ namespace Mono.CSharp {
                ///   the current namespace declaration
                /// </summary>
                public Namespace Parent {
-                       get {
-                               return parent;
-                       }
-               }
-
-               public static void DefineNamespaces (SymbolWriter symwriter)
-               {
-                       foreach (Namespace ns in all_namespaces) {
-                               foreach (NamespaceEntry entry in ns.entries)
-                                       entry.DefineNamespace (symwriter);
-                       }
-               }
-
-               /// <summary>
-               ///   Used to validate that all the using clauses are correct
-               ///   after we are finished parsing all the files.  
-               /// </summary>
-               public static void VerifyUsing ()
-               {
-                       foreach (Namespace ns in all_namespaces) {
-                               foreach (NamespaceEntry entry in ns.entries)
-                                       entry.VerifyUsing ();
-                       }
+                       get { return parent; }
                }
 
                public override string ToString ()
                {
-                       if (this == Root)
-                               return "Namespace (<root>)";
-                       else
-                               return String.Format ("Namespace ({0})", Name);
-               }
-
-               bool IAlias.IsType {
-                       get { return false; }
-               }
-
-               TypeExpr IAlias.ResolveAsType (EmitContext ec)
-               {
-                       throw new InvalidOperationException ();
+                       return String.Format ("Namespace ({0})", Name);
                }
        }
 
-       public class NamespaceEntry
-       {
+       public class NamespaceEntry {
                Namespace ns;
                NamespaceEntry parent, implicit_parent;
                SourceFile file;
@@ -256,6 +485,18 @@ namespace Mono.CSharp {
                Hashtable aliases;
                ArrayList using_clauses;
                public bool DeclarationFound = false;
+               bool UsingFound;
+
+               public readonly DeclSpace SlaveDeclSpace;
+
+               ListDictionary extern_aliases;
+
+               static ArrayList entries = new ArrayList ();
+
+               public static void Reset ()
+               {
+                       entries = new ArrayList ();
+               }
 
                //
                // This class holds the location where a using definition is
@@ -264,90 +505,171 @@ namespace Mono.CSharp {
                // We use this to flag using clauses for namespaces that do not
                // exist.
                //
-               public class UsingEntry {
-                       public MemberName Name;
-                       public Expression Expr;
-                       public readonly NamespaceEntry NamespaceEntry;
-                       public readonly Location Location;
+               public class UsingEntry : IResolveContext {
+                       public readonly MemberName Name;
+                       readonly Expression Expr;
+                       readonly NamespaceEntry NamespaceEntry;
+                       readonly Location Location;
                        
                        public UsingEntry (NamespaceEntry entry, MemberName name, Location loc)
                        {
                                Name = name;
-                               Expr = name.GetTypeExpression (loc);
+                               Expr = name.GetTypeExpression ();
                                NamespaceEntry = entry;
                                Location = loc;
                        }
 
-                       internal FullNamedExpression resolved;
+                       internal Namespace resolved;
 
                        public Namespace Resolve ()
                        {
                                if (resolved != null)
-                                       return resolved as Namespace;
+                                       return resolved;
 
-                               DeclSpace root = RootContext.Tree.Types;
-                               root.NamespaceEntry = NamespaceEntry;
-                               resolved = Expr.ResolveAsTypeStep (root.EmitContext);
-                               root.NamespaceEntry = null;
+                               FullNamedExpression fne = Expr.ResolveAsTypeStep (this, false);
+                               if (fne == null) {
+                                       Error_NamespaceNotFound (Location, Name.ToString ());
+                                       return null;
+                               }
+
+                               resolved = fne as Namespace;
+                               if (resolved == null) {
+                                       Report.Error (138, Location,
+                                               "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces", Name.ToString ());
+                               }
+                               return resolved;
+                       }
 
-                               return resolved as Namespace;
+                       DeclSpace IResolveContext.DeclContainer {
+                               get { return NamespaceEntry.SlaveDeclSpace; }
+                       }
+
+                       DeclSpace IResolveContext.GenericDeclContainer {
+                               get { return NamespaceEntry.SlaveDeclSpace; }
+                       }
+
+                       bool IResolveContext.IsInObsoleteScope {
+                               get { return false; }
+                       }
+                       bool IResolveContext.IsInUnsafeScope {
+                               get { return false; }
                        }
                }
 
-               public class AliasEntry {
+               public abstract class AliasEntry {
                        public readonly string Name;
-                       public readonly Expression Alias;
                        public readonly NamespaceEntry NamespaceEntry;
                        public readonly Location Location;
                        
-                       public AliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc)
+                       protected AliasEntry (NamespaceEntry entry, string name, Location loc)
                        {
                                Name = name;
-                               Alias = alias.GetTypeExpression (loc);
                                NamespaceEntry = entry;
                                Location = loc;
                        }
-
-                       FullNamedExpression resolved;
+                       
+                       protected FullNamedExpression resolved;
+                       bool error;
 
                        public FullNamedExpression Resolve ()
                        {
-                               if (resolved != null)
+                               if (resolved != null || error)
                                        return resolved;
+                               resolved = DoResolve ();
+                               if (resolved == null)
+                                       error = true;
+                               return resolved;
+                       }
 
-                               DeclSpace root = RootContext.Tree.Types;
-                               root.NamespaceEntry = NamespaceEntry;
-                               resolved = Alias.ResolveAsTypeStep (root.EmitContext);
-                               root.NamespaceEntry = null;
+                       protected abstract FullNamedExpression DoResolve ();
+               }
+
+               public class LocalAliasEntry : AliasEntry, IResolveContext {
+                       public readonly Expression Alias;
+                       
+                       public LocalAliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc) :
+                               base (entry, name, loc)
+                       {
+                               Alias = alias.GetTypeExpression ();
+                       }
+
+                       protected override FullNamedExpression DoResolve ()
+                       {
+                               resolved = Alias.ResolveAsTypeStep (this, false);
+                               if (resolved == null)
+                                       return null;
+
+                               if (resolved.Type != null) {
+                                       TypeAttributes attr = resolved.Type.Attributes & TypeAttributes.VisibilityMask;
+                                       if (attr == TypeAttributes.NestedPrivate || attr == TypeAttributes.NestedFamily ||
+                                               ((attr == TypeAttributes.NestedFamORAssem || attr == TypeAttributes.NestedAssembly) && 
+                                               TypeManager.LookupDeclSpace (resolved.Type) == null)) {
+                                               Expression.ErrorIsInaccesible (Alias.Location, Alias.ToString ());
+                                               return null;
+                                       }
+                               }
 
                                return resolved;
                        }
+
+                       DeclSpace IResolveContext.DeclContainer {
+                               get { return NamespaceEntry.SlaveDeclSpace; }
+                       }
+
+                       DeclSpace IResolveContext.GenericDeclContainer {
+                               get { return NamespaceEntry.SlaveDeclSpace; }
+                       }
+
+                       bool IResolveContext.IsInObsoleteScope {
+                               get { return false; }
+                       }
+                       bool IResolveContext.IsInUnsafeScope {
+                               get { return false; }
+                       }
                }
 
-               public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name, Location loc)
+               public class ExternAliasEntry : AliasEntry {
+                       public ExternAliasEntry (NamespaceEntry entry, string name, Location loc) :
+                               base (entry, name, loc)
+                       {
+                       }
+
+                       protected override FullNamedExpression DoResolve ()
+                       {
+                               resolved = RootNamespace.GetRootNamespace (Name);
+                               if (resolved == null)
+                                       Report.Error (430, Location, "The extern alias '" + Name +
+                                                                       "' was not specified in a /reference option");
+
+                               return resolved;
+                       }
+               }
+
+               public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name)
                {
                        this.parent = parent;
                        this.file = file;
-                       this.IsImplicit = false;
-                       this.ID = ++next_id;
+                       entries.Add (this);
+                       this.ID = entries.Count;
 
                        if (parent != null)
                                ns = parent.NS.GetNamespace (name, true);
                        else if (name != null)
-                               ns = Namespace.LookupNamespace (name, true);
+                               ns = RootNamespace.Global.GetNamespace (name, true);
                        else
-                               ns = Namespace.Root;
-                       ns.AddNamespaceEntry (this);
+                               ns = RootNamespace.Global;
+                       SlaveDeclSpace = new RootDeclSpace (this);
                }
 
-
-               private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns)
+               private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns, bool slave)
                {
                        this.parent = parent;
                        this.file = file;
+                       // no need to add self to 'entries', since we don't have any aliases or using entries.
+                       this.ID = -1;
                        this.IsImplicit = true;
-                       this.ID = ++next_id;
                        this.ns = ns;
+                       this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
                }
 
                //
@@ -364,25 +686,20 @@ namespace Mono.CSharp {
                NamespaceEntry Doppelganger {
                        get {
                                if (!IsImplicit && doppelganger == null)
-                                       doppelganger = new NamespaceEntry (ImplicitParent, file, ns);
+                                       doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
                                return doppelganger;
                        }
                }
 
-               static int next_id = 0;
                public readonly int ID;
                public readonly bool IsImplicit;
 
                public Namespace NS {
-                       get {
-                               return ns;
-                       }
+                       get { return ns; }
                }
 
                public NamespaceEntry Parent {
-                       get {
-                               return parent;
-                       }
+                       get { return parent; }
                }
 
                public NamespaceEntry ImplicitParent {
@@ -392,7 +709,7 @@ namespace Mono.CSharp {
                                if (implicit_parent == null) {
                                        implicit_parent = (parent.NS == ns.Parent)
                                                ? parent
-                                               : new NamespaceEntry (parent, file, ns.Parent);
+                                               : new NamespaceEntry (parent, file, ns.Parent, false);
                                }
                                return implicit_parent;
                        }
@@ -404,10 +721,12 @@ namespace Mono.CSharp {
                public void Using (MemberName name, Location loc)
                {
                        if (DeclarationFound){
-                               Report.Error (1529, loc, "A using clause must precede all other namespace elements");
+                               Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
                                return;
                        }
 
+                       UsingFound = true;
+
                        if (name.Equals (ns.MemberName))
                                return;
                        
@@ -416,13 +735,11 @@ namespace Mono.CSharp {
 
                        foreach (UsingEntry old_entry in using_clauses) {
                                if (name.Equals (old_entry.Name)) {
-                                       if (RootContext.WarningLevel >= 3)
-                                               Report.Warning (105, loc, "The using directive for '{0}' appeared previously in this namespace", name);
+                                       Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetName ());
                                        return;
                                }
                        }
 
-
                        UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
                        using_clauses.Add (ue);
                }
@@ -430,131 +747,155 @@ namespace Mono.CSharp {
                public void UsingAlias (string name, MemberName alias, Location loc)
                {
                        if (DeclarationFound){
-                               Report.Error (1529, loc, "A using clause must precede all other namespace elements");
+                               Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
                                return;
                        }
 
+                       UsingFound = true;
+
                        if (aliases == null)
                                aliases = new Hashtable ();
-                       
-                       if (aliases.Contains (name)){
-                               AliasEntry ae = (AliasEntry)aliases [name];
+
+                       if (aliases.Contains (name)) {
+                               AliasEntry ae = (AliasEntry) aliases [name];
+                               Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
+                               Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
+                               return;
+                       }
+
+                       if (RootContext.Version == LanguageVersion.Default &&
+                           name == "global" && RootContext.WarningLevel >= 2)
+                               Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
+                                       " the global namespace will be used instead");
+
+                       // FIXME: get correct error number.  See if the above check can be merged
+                       if (extern_aliases != null && extern_aliases.Contains (name)) {
+                               AliasEntry ae = (AliasEntry) extern_aliases [name];
                                Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
-                               Report.Error (1537, loc, "The using alias `" + name +
-                                             "' appeared previously in this namespace");
+                               Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
                                return;
                        }
 
-                       aliases [name] = new AliasEntry (Doppelganger, name, alias, loc);
+                       aliases [name] = new LocalAliasEntry (Doppelganger, name, alias, loc);
                }
 
-               public FullNamedExpression LookupAlias (string alias)
+               public void UsingExternalAlias (string name, Location loc)
                {
-                       AliasEntry entry = null;
-                       if (aliases != null)
-                               entry = (AliasEntry) aliases [alias];
+                       if (UsingFound || DeclarationFound) {
+                               Report.Error (439, loc, "An extern alias declaration must precede all other elements");
+                               return;
+                       }
+                       
+                       // Share the extern_aliases field with the Doppelganger
+                       if (extern_aliases == null) {
+                               extern_aliases = new ListDictionary ();
+                               Doppelganger.extern_aliases = extern_aliases;
+                       }
 
-                       return entry == null ? null : entry.Resolve ();
-               }
+                       if (extern_aliases.Contains (name)) {
+                               AliasEntry ae = (AliasEntry) extern_aliases [name];
+                               Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
+                               Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
+                               return;
+                       }
+
+                       if (name == "global") {
+                               Report.Error (1681, loc, "You cannot redefine the global extern alias");
+                               return;
+                       }
 
-               static readonly char [] dot_array = { '.' };
+                       // Register the alias in aliases and extern_aliases, since we need both of them
+                       // to keep things simple (different resolution scenarios)
+                       ExternAliasEntry alias = new ExternAliasEntry (Doppelganger, name, loc);
+                       extern_aliases [name] = alias;
+               }
 
                public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
                {
+                       // Precondition: Only simple names (no dots) will be looked up with this function.
                        FullNamedExpression resolved = null;
-                       string rest = null;
-
-                       // If name is of the form `N.I', first lookup `N', then search a member `I' in it.
-                       int pos = name.IndexOf ('.');
-                       if (pos >= 0) {
-                               rest = name.Substring (pos + 1);
-                               name = name.Substring (0, pos);
-                       }
-
                        for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
                                if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
                                        break;
                        }
+                       return resolved;
+               }
 
-                       if (resolved == null || rest == null)
-                               return resolved;
-
-                       // Now handle the rest of the the name.
-                       string [] elements = rest.Split (dot_array);
-                       int count = elements.Length;
-                       int i = 0;
-                       while (i < count && resolved != null && resolved is Namespace) {
-                               Namespace ns = resolved as Namespace;
-                               resolved = ns.Lookup (ds, elements [i++], loc);
-                       }
-
-                       if (resolved == null || resolved is Namespace)
-                               return resolved;
+               static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
+               {
+                       Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
+                               name, t1.FullName, t2.FullName);
+               }
 
-                       Type t = ((TypeExpr) resolved).Type;
-                       
-                       while (t != null) {
-                               if (ds != null && !ds.CheckAccessLevel (t))
+               // Looks-up a alias named @name in this and surrounding namespace declarations
+               public FullNamedExpression LookupAlias (string name)
+               {
+                       AliasEntry entry = null;
+                       for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
+                               if (n.extern_aliases != null && (entry = n.extern_aliases [name] as AliasEntry) != null)
+                                       break;
+                               if (n.aliases != null && (entry = n.aliases [name] as AliasEntry) != null)
                                        break;
-                               if (i == count)
-                                       return new TypeExpression (t, Location.Null);
-                               t = TypeManager.GetNestedType (t, elements [i++]);
                        }
-
-                       return null;
+                       return entry == null ? null : entry.Resolve ();
                }
 
                private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
                {
-                       // Precondition: Only simple names (no dots) will be looked up with this function.
-
                        //
                        // Check whether it's in the namespace.
                        //
-                       FullNamedExpression o = NS.Lookup (ds, name, loc);
-                       if (o != null)
-                               return o;
+                       FullNamedExpression fne = NS.Lookup (ds, name, loc);
+                       if (fne != null)
+                               return fne;
 
+                       if (extern_aliases != null) {
+                               AliasEntry entry = extern_aliases [name] as AliasEntry;
+                               if (entry != null)
+                                       return entry.Resolve ();
+                       }
+                       
                        if (IsImplicit)
                                return null;
-
+                       
                        //
-                       // Check aliases.
+                       // Check aliases. 
                        //
-                       o = LookupAlias (name);
-                       if (o != null)
-                               return o;
+                       if (aliases != null) {
+                               AliasEntry entry = aliases [name] as AliasEntry;
+                               if (entry != null)
+                                       return entry.Resolve ();
+                       }
 
                        //
                        // Check using entries.
                        //
-                       FullNamedExpression t = null, match = null;
+                       FullNamedExpression match = null;
                        foreach (Namespace using_ns in GetUsingTable ()) {
                                match = using_ns.Lookup (ds, name, loc);
-                               if ((match != null) && (match is TypeExpr)) {
-                                       if (t != null) {
-                                               if (!ignore_cs0104)
-                                                       DeclSpace.Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
-                                               
-                                               return null;
-                                       } else {
-                                               t = match;
-                                       }
+                               if (match == null || !(match is TypeExpr))
+                                       continue;
+                               if (fne != null) {
+                                       if (!ignore_cs0104)
+                                               Error_AmbiguousTypeReference (loc, name, fne, match);
+                                       return null;
                                }
+                               fne = match;
                        }
 
-                       return t;
+                       return fne;
                }
 
                // Our cached computation.
+               readonly Namespace [] empty_namespaces = new Namespace [0];
                Namespace [] namespace_using_table;
-               public Namespace[] GetUsingTable ()
+               Namespace [] GetUsingTable ()
                {
                        if (namespace_using_table != null)
                                return namespace_using_table;
 
                        if (using_clauses == null) {
-                               namespace_using_table = new Namespace [0];
+                               namespace_using_table = empty_namespaces;
                                return namespace_using_table;
                        }
 
@@ -573,32 +914,22 @@ namespace Mono.CSharp {
                        return namespace_using_table;
                }
 
-               public void DefineNamespace (SymbolWriter symwriter)
-               {
-                       if (symfile_id != 0)
-                               return;
-                       if (parent != null)
-                               parent.DefineNamespace (symwriter);
-
-                       string[] using_list;
-                       if (using_clauses != null) {
-                               using_list = new string [using_clauses.Count];
-                               for (int i = 0; i < using_clauses.Count; i++)
-                                       using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
-                       } else {
-                               using_list = new string [0];
-                       }
-
-                       int parent_id = parent != null ? parent.symfile_id : 0;
-                       if (file.SourceFileEntry == null)
-                               return;
-
-                       symfile_id = symwriter.DefineNamespace (
-                               ns.Name, file.SourceFileEntry, using_list, parent_id);
-               }
+               readonly string [] empty_using_list = new string [0];
 
                public int SymbolFileID {
                        get {
+                               if (symfile_id == 0 && file.SourceFileEntry != null) {
+                                       int parent_id = parent == null ? 0 : parent.SymbolFileID;
+
+                                       string [] using_list = empty_using_list;
+                                       if (using_clauses != null) {
+                                               using_list = new string [using_clauses.Count];
+                                               for (int i = 0; i < using_clauses.Count; i++)
+                                                       using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
+                                       }
+
+                                       symfile_id = CodeGen.SymbolWriter.DefineNamespace (ns.Name, file.SourceFileEntry, using_list, parent_id);
+                               }
                                return symfile_id;
                        }
                }
@@ -607,16 +938,16 @@ namespace Mono.CSharp {
                {
                        Console.WriteLine ("    Try using -r:" + s);
                }
-               
+
                static void MsgtryPkg (string s)
                {
                        Console.WriteLine ("    Try using -pkg:" + s);
                }
 
-               protected void error246 (Location loc, string name)
+               public static void Error_NamespaceNotFound (Location loc, string name)
                {
-                       Report.Error (246, loc, "The namespace `" + name +
-                                     "' can not be found (missing assembly reference?)");
+                       Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
+                               name);
 
                        switch (name) {
                        case "Gtk": case "GtkSharp":
@@ -645,40 +976,42 @@ namespace Mono.CSharp {
                ///   Used to validate that all the using clauses are correct
                ///   after we are finished parsing all the files.  
                /// </summary>
-               public void VerifyUsing ()
+               void VerifyUsing ()
                {
-                       if (using_clauses != null){
-                               foreach (UsingEntry ue in using_clauses){
-                                       if (ue.Resolve () != null)
-                                               continue;
-
-                                       if (ue.resolved == null)
-                                               error246 (ue.Location, ue.Name.ToString ());
-                                       else
-                                               Report.Error (138, ue.Location, "The using keyword only lets you specify a namespace, " +
-                                                             "`" + ue.Name + "' is a class not a namespace.");
+                       if (extern_aliases != null) {
+                               foreach (DictionaryEntry de in extern_aliases)
+                                       ((AliasEntry) de.Value).Resolve ();
+                       }               
 
-                               }
+                       if (using_clauses != null) {
+                               foreach (UsingEntry ue in using_clauses)
+                                       ue.Resolve ();
                        }
 
-                       if (aliases != null){
-                               foreach (DictionaryEntry de in aliases){
-                                       AliasEntry alias = (AliasEntry) de.Value;
+                       if (aliases != null) {
+                               foreach (DictionaryEntry de in aliases)
+                                       ((AliasEntry) de.Value).Resolve ();
+                       }
+               }
 
-                                       if (alias.Resolve () != null)
-                                               continue;
+               /// <summary>
+               ///   Used to validate that all the using clauses are correct
+               ///   after we are finished parsing all the files.  
+               /// </summary>
+               static public void VerifyAllUsing ()
+               {
+                       foreach (NamespaceEntry entry in entries)
+                               entry.VerifyUsing ();
+               }
 
-                                       error246 (alias.Location, alias.Alias.ToString ());
-                               }
-                       }
+               public string GetSignatureForError ()
+               {
+                       return ns.GetSignatureForError ();
                }
 
                public override string ToString ()
                {
-                       if (NS == Namespace.Root)
-                               return "NamespaceEntry (<root>)";
-                       else
-                               return String.Format ("NamespaceEntry ({0},{1},{2})", ns.Name, IsImplicit, ID);
+                       return ns.ToString ();
                }
        }
 }