Rename lookup method for consistency
[mono.git] / mcs / mcs / namespace.cs
index 2e3fb5ed13e210e85fb5e7c977eec657cc15f3dc..a19f5938a784baa4eccbcf7faffd5e8a04aa3a80 100644 (file)
 // Copyright 2003-2008 Novell, Inc.
 //
 using System;
-using System.Collections;
 using System.Collections.Generic;
-using System.Reflection;
+using System.Linq;
 
 namespace Mono.CSharp {
 
        public class RootNamespace : Namespace {
-               //
-               // Points to Mono's GetNamespaces method, an
-               // optimization when running on Mono to fetch all the
-               // namespaces in an assembly
-               //
-               static MethodInfo get_namespaces_method;
 
-               protected readonly string alias_name;
-               protected Assembly [] referenced_assemblies;
-
-               Dictionary<string, Namespace> all_namespaces;
-
-               static RootNamespace ()
-               {
-                       get_namespaces_method = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance | BindingFlags.NonPublic);
-               }
+               readonly string alias_name;
+               readonly Dictionary<string, Namespace> all_namespaces;
 
                public RootNamespace (string alias_name)
                        : base (null, String.Empty)
                {
                        this.alias_name = alias_name;
-                       referenced_assemblies = new Assembly [0];
 
                        all_namespaces = new Dictionary<string, Namespace> ();
                        all_namespaces.Add ("", this);
                }
 
-               public void AddAssemblyReference (Assembly a)
-               {
-                       foreach (Assembly assembly in referenced_assemblies) {
-                               if (a == assembly)
-                                       return;
-                       }
-
-                       int top = referenced_assemblies.Length;
-                       Assembly [] n = new Assembly [top + 1];
-                       referenced_assemblies.CopyTo (n, 0);
-                       n [top] = a;
-                       referenced_assemblies = n;
-               }
-
-               public void ComputeNamespace (CompilerContext ctx, Type extensionType)
-               {
-                       foreach (Assembly a in referenced_assemblies) {
-                               try {
-                                       ComputeNamespaces (a, extensionType);
-                               } catch (TypeLoadException e) {
-                                       ctx.Report.Error (11, Location.Null, e.Message);
-                               } catch (System.IO.FileNotFoundException) {
-                                       ctx.Report.Error (12, Location.Null, "An assembly `{0}' is used without being referenced",
-                                               a.FullName);
-                               }
-                       }
-               }
-
-               public virtual Type LookupTypeReflection (CompilerContext ctx, string name, Location loc, bool must_be_unique)
-               {
-                       // FIXME: Breaks dynamic
-                       Assembly invocation_assembly = CodeGen.Assembly.Builder;
-
-                       Type found_type = null;
-                       foreach (Assembly a in referenced_assemblies) {
-                               Type t = GetTypeInAssembly (invocation_assembly, a, name);
-                               if (t == null)
-                                       continue;
-
-                               if (!must_be_unique)
-                                       return t;
-
-                               if (found_type == null) {
-                                       found_type = t;
-                                       continue;
-                               }
-
-                               // When type is forwarded
-                               if (t.Assembly == found_type.Assembly)
-                                       continue;                                       
-
-                               ctx.Report.SymbolRelatedToPreviousError (found_type);
-                               ctx.Report.SymbolRelatedToPreviousError (t);
-                               if (loc.IsNull) {
-                                       Error_AmbiguousPredefinedType (ctx, loc, name, found_type);
-                               } else {
-                                       ctx.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
-                               }
-
-                               return found_type;
-                       }
-
-                       return found_type;
-               }
-
-               //
-               // Returns the types starting with the given prefix
-               //
-               public ICollection CompletionGetTypesStartingWith (string prefix)
-               {
-                       Hashtable result = null;
-
-                       foreach (Assembly a in referenced_assemblies){
-                               Type [] mtypes = a.GetTypes ();
-
-                               foreach (Type t in mtypes){
-                                       string f = t.FullName;
-
-                                       if (f.StartsWith (prefix) && (result == null || !result.Contains (f))){
-                                               if (result == null)
-                                                       result = new Hashtable ();
-
-                                               result [f] = f;
-                                       }
-                               }
+               public string Alias {
+                       get {
+                               return alias_name;
                        }
-                       return result == null ? result : result.Keys;
-               }
-               
-               protected static void Error_AmbiguousPredefinedType (CompilerContext ctx, Location loc, string name, Type type)
-               {
-                       ctx.Report.Warning (1685, 1, loc,
-                               "The predefined type `{0}' is ambiguous. Using definition from `{1}'",
-                               name, type.Assembly.FullName);
                }
 
                public void RegisterNamespace (Namespace child)
@@ -156,215 +51,42 @@ namespace Mono.CSharp {
                                GetNamespace (dotted_name, true);
                }
 
-               void RegisterExtensionMethodClass (Type t)
-               {
-                       string n = t.Namespace;
-                       Namespace ns = null;
-                       if (n == null)
-                               ns = GlobalRootNamespace.Instance;
-                       else
-                               all_namespaces.TryGetValue (n, out ns);
-
-                       if (ns == null)
-                               ns = GetNamespace (n, true);
-                       ns.RegisterExternalExtensionMethodClass (t);
-               }
-
-               void ComputeNamespaces (Assembly assembly, Type extensionType)
-               {
-                       bool contains_extension_methods = extensionType != null && assembly.IsDefined (extensionType, false);
-                       if (get_namespaces_method != null) {
-                               string [] namespaces = (string []) get_namespaces_method.Invoke (assembly, null);
-                               foreach (string ns in namespaces)
-                                       RegisterNamespace (ns);
-
-                               if (!contains_extension_methods)
-                                       return;
-                       }
-
-                       foreach (Type t in assembly.GetTypes ()) {
-                               if ((t.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute &&
-                                       contains_extension_methods && t.IsDefined (extensionType, false))
-                                       RegisterExtensionMethodClass (t);
-
-                               if (get_namespaces_method == null)
-                                       RegisterNamespace (t.Namespace);
-                       }
-               }
-
-               protected static Type GetTypeInAssembly (Assembly invocation, Assembly assembly, string name)
-               {
-                       if (assembly == null)
-                               throw new ArgumentNullException ("assembly");
-                       if (name == null)
-                               throw new ArgumentNullException ("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.IsThisOrFriendAssembly (invocation, 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 {
-               Module [] modules;
-               Dictionary<string, RootNamespace> root_namespaces;
-
-               public static GlobalRootNamespace Instance = new GlobalRootNamespace ();
-
-               GlobalRootNamespace ()
+       public class GlobalRootNamespace : RootNamespace
+       {
+               public GlobalRootNamespace ()
                        : base ("global")
                {
-                       root_namespaces = new Dictionary<string, RootNamespace> ();
-                       root_namespaces.Add (alias_name, this);
-               }
-
-               public static void Reset ()
-               {
-                       Instance = new GlobalRootNamespace ();
                }
 
-               public Assembly [] Assemblies {
-                   get { return referenced_assemblies; }
-               }
-
-               public Module [] Modules {
-                       get { return modules; }
-               }
-
-               public void AddModuleReference (Module m)
+               public override void Error_NamespaceDoesNotExist (Location loc, string name, int arity, IMemberContext ctx)
                {
-                       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 == RootContext.ToplevelTypes.Builder)
-                               return;
-
-                       foreach (Type t in m.GetTypes ())
-                               RegisterNamespace (t.Namespace);
-               }
-
-               public void ComputeNamespaces (CompilerContext ctx)
-               {
-                       //
-                       // Do very early lookup because type is required when we cache
-                       // imported extension types in ComputeNamespaces
-                       //
-                       Type extension_attribute_type = TypeManager.CoreLookupType (ctx, "System.Runtime.CompilerServices", "ExtensionAttribute", Kind.Class, false);
-
-                       foreach (RootNamespace rn in root_namespaces.Values) {
-                               rn.ComputeNamespace (ctx, extension_attribute_type);
-                       }
-               }
-
-               public void DefineRootNamespace (string alias, Assembly assembly, CompilerContext ctx)
-               {
-                       if (alias == alias_name) {
-                               NamespaceEntry.Error_GlobalNamespaceRedefined (Location.Null, ctx.Report);
-                               return;
-                       }
-
-                       RootNamespace retval = GetRootNamespace (alias);
-                       if (retval == null) {
-                               retval = new RootNamespace (alias);
-                               root_namespaces.Add (alias, retval);
-                       }
-
-                       retval.AddAssemblyReference (assembly);
-               }
-
-               public override void Error_NamespaceDoesNotExist (Location loc, string name, IMemberContext ctx)
-               {
-                       ctx.Compiler.Report.Error (400, loc,
+                       ctx.Module.Compiler.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 RootNamespace GetRootNamespace (string name)
-               {
-                       RootNamespace rn;
-                       if (!root_namespaces.TryGetValue (name, out rn))
-                               return null;
-
-                       return rn;
-               }
-
-               public override Type LookupTypeReflection (CompilerContext ctx, string name, Location loc, bool must_be_unique)
-               {
-                       Type found_type = base.LookupTypeReflection (ctx, name, loc, must_be_unique);
-
-                       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;
-                                       }
-
-                                       ctx.Report.SymbolRelatedToPreviousError (found_type);
-                                       if (loc.IsNull) {
-                                               DeclSpace ds = TypeManager.LookupDeclSpace (t);
-                                               Error_AmbiguousPredefinedType (ctx, ds.Location, name, found_type);
-                                               return found_type;
-                                       }
-                                       ctx.Report.SymbolRelatedToPreviousError (t);
-                                       ctx.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 {
-               
+       //
+       // Namespace cache for imported and compiled namespaces
+       //
+       // This is an Expression to allow it to be referenced in the
+       // compiler parse/intermediate tree during name resolution.
+       //
+       public class Namespace : FullNamedExpression
+       {
                Namespace parent;
                string fullname;
-               Dictionary<string, Namespace> namespaces;
-               Dictionary<string, DeclSpace> declspaces;
-               Hashtable cached_types;
+               protected Dictionary<string, Namespace> namespaces;
+               protected Dictionary<string, IList<TypeSpec>> types;
+               Dictionary<string, TypeExpr> cached_types;
                RootNamespace root;
-               ArrayList external_exmethod_classes;
+               bool cls_checked;
 
                public readonly MemberName MemberName;
 
@@ -377,7 +99,7 @@ namespace Mono.CSharp {
                {
                        // Expression members.
                        this.eclass = ExprClass.Namespace;
-                       this.Type = typeof (Namespace);
+                       this.Type = InternalType.Namespace;
                        this.loc = Location.Null;
 
                        this.parent = parent;
@@ -408,44 +130,54 @@ namespace Mono.CSharp {
                                MemberName = new MemberName (name);
 
                        namespaces = new Dictionary<string, Namespace> ();
-                       cached_types = new Hashtable ();
+                       cached_types = new Dictionary<string, TypeExpr> ();
 
                        root.RegisterNamespace (this);
                }
 
+               #region Properties
+
+               /// <summary>
+               ///   The qualified name of the current namespace
+               /// </summary>
+               public string Name {
+                       get { return fullname; }
+               }
+
+               /// <summary>
+               ///   The parent of this namespace, used by the parser to "Pop"
+               ///   the current namespace declaration
+               /// </summary>
+               public Namespace Parent {
+                       get { return parent; }
+               }
+
+               #endregion
+
                protected override Expression DoResolve (ResolveContext ec)
                {
                        return this;
                }
 
-               public virtual void Error_NamespaceDoesNotExist (Location loc, string name, IMemberContext ctx)
+               public virtual void Error_NamespaceDoesNotExist (Location loc, string name, int arity, IMemberContext ctx)
                {
-                       if (name.IndexOf ('`') > 0) {
-                               FullNamedExpression retval = Lookup (ctx.Compiler, SimpleName.RemoveGenericArity (name), loc);
-                               if (retval != null) {
-                                       retval.Error_TypeArgumentsCannotBeUsed (ctx.Compiler.Report, loc);
-                                       return;
-                               }
-                       } else {
-                               Type t = LookForAnyGenericType (name);
-                               if (t != null) {
-                                       Error_InvalidNumberOfTypeArguments (ctx.Compiler.Report, t, loc);
-                                       return;
-                               }
+                       var retval = LookupType (ctx, name, -System.Math.Max (1, arity), loc);
+                       if (retval != null) {
+                               Error_TypeArgumentsCannotBeUsed (ctx, retval.Type, arity, loc);
+                               return;
                        }
 
-                       ctx.Compiler.Report.Error (234, loc,
+                       Namespace ns;
+                       if (arity > 0 && namespaces.TryGetValue (name, out ns)) {
+                               ns.Error_TypeArgumentsCannotBeUsed (ctx, null, arity, loc);
+                               return;
+                       }
+
+                       ctx.Module.Compiler.Report.Error (234, loc,
                                "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
                                name, GetSignatureForError ());
                }
 
-               public static void Error_InvalidNumberOfTypeArguments (Report report, 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 override string GetSignatureForError ()
                {
                        return fullname;
@@ -476,409 +208,435 @@ namespace Mono.CSharp {
                        return ns;
                }
 
-               public bool HasDefinition (string name)
+               public IList<TypeSpec> GetAllTypes (string name)
                {
-                       return declspaces != null && declspaces [name] != null;
+                       IList<TypeSpec> found;
+                       if (types == null || !types.TryGetValue (name, out found))
+                               return null;
+
+                       return found;
                }
 
-               TypeExpr LookupType (CompilerContext ctx, string name, Location loc)
+               public TypeExpr LookupType (IMemberContext ctx, string name, int arity, Location loc)
                {
-                       if (cached_types.Contains (name))
-                               return cached_types [name] as TypeExpr;
+                       if (types == null)
+                               return null;
 
-                       Type t = null;
-                       if (declspaces != null) {
-                               DeclSpace tdecl;
-                               if (declspaces.TryGetValue (name, out tdecl)) {
-                                       //
-                                       // Note that this is not:
-                                       //
-                                       //   t = tdecl.DefineType ()
-                                       //
-                                       // This is to make it somewhat more useful when a DefineType
-                                       // fails due to problems in nested types (more useful in the sense
-                                       // of fewer misleading error messages)
-                                       //
-                                       tdecl.DefineType ();
-                                       t = tdecl.TypeBuilder;
-
-                                       if (RootContext.EvalMode){
-                                               // Replace the TypeBuilder with a System.Type, as
-                                               // Reflection.Emit fails otherwise (we end up pretty
-                                               // much with Random type definitions later on).
-                                               Type tt = t.Assembly.GetType (t.Name);
-                                               if (tt != null)
-                                                       t = tt;
+                       TypeExpr te;
+                       if (arity == 0 && cached_types.TryGetValue (name, out te))
+                               return te;
+
+                       IList<TypeSpec> found;
+                       if (!types.TryGetValue (name, out found))
+                               return null;
+
+                       TypeSpec best = null;
+                       foreach (var ts in found) {
+                               if (ts.Arity == arity) {
+                                       if (best == null) {
+                                               best = ts;
+                                               continue;
+                                       }
+
+                                       if (best.MemberDefinition.IsImported && ts.MemberDefinition.IsImported) {
+                                               ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (best);
+                                               ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
+                                               ctx.Module.Compiler.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", ts.GetSignatureForError ());
+                                               break;
+                                       }
+
+                                       if (best.MemberDefinition.IsImported)
+                                               best = ts;
+
+                                       if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !best.MemberDefinition.IsInternalAsPublic (ctx.Module.DeclaringAssembly))
+                                               continue;
+
+                                       if (ts.MemberDefinition.IsImported)
+                                               ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
+
+                                       ctx.Module.Compiler.Report.Warning (436, 2, loc,
+                                               "The type `{0}' conflicts with the imported type of same name'. Ignoring the imported type definition",
+                                               best.GetSignatureForError ());
+                               }
+
+                               //
+                               // Lookup for the best candidate with closest arity match
+                               //
+                               if (arity < 0) {
+                                       if (best == null) {
+                                               best = ts;
+                                       } else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (best.Arity + arity)) {
+                                               best = ts;
                                        }
                                }
                        }
-                       string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
-                       Type rt = root.LookupTypeReflection (ctx, lookup, loc, t == null);
 
-                       // HACK: loc.IsNull when the type is core type
-                       if (t == null || (rt != null && loc.IsNull))
-                               t = rt;
+                       if (best == null)
+                               return null;
+
+                       if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !best.MemberDefinition.IsInternalAsPublic (ctx.Module.DeclaringAssembly))
+                               return null;
+
+                       te = new TypeExpression (best, Location.Null);
+
+                       // TODO MemberCache: Cache more
+                       if (arity == 0)
+                               cached_types.Add (name, te);
 
-                       TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
-                       cached_types [name] = te;
                        return te;
                }
 
-               ///
-               /// Used for better error reporting only
-               /// 
-               public Type LookForAnyGenericType (string typeName)
+               TypeSpec LookupType (string name, int arity)
                {
-                       if (declspaces == null)
+                       if (types == null)
                                return null;
 
-                       typeName = SimpleName.RemoveGenericArity (typeName);
+                       IList<TypeSpec> found;
+                       if (types.TryGetValue (name, out found)) {
+                               TypeSpec best = null;
+
+                               foreach (var ts in found) {
+                                       if (ts.Arity == arity)
+                                               return ts;
 
-                       foreach (var de in declspaces) {
-                               string type_item = de.Key;
-                               int pos = type_item.LastIndexOf ('`');
-                               if (pos == typeName.Length && String.Compare (typeName, 0, type_item, 0, pos) == 0)
-                                       return de.Value.TypeBuilder;
+                                       //
+                                       // Lookup for the best candidate with closest arity match
+                                       //
+                                       if (arity < 0) {
+                                               if (best == null) {
+                                                       best = ts;
+                                               } else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (best.Arity + arity)) {
+                                                       best = ts;
+                                               }
+                                       }
+                               }
+                               
+                               return best;
                        }
+
                        return null;
                }
 
-               public FullNamedExpression Lookup (CompilerContext ctx, string name, Location loc)
+               public FullNamedExpression LookupTypeOrNamespace (IMemberContext ctx, string name, int arity, Location loc)
                {
-                       if (namespaces.ContainsKey (name))
-                               return namespaces [name];
+                       var texpr = LookupType (ctx, name, arity, loc);
+
+                       Namespace ns;
+                       if (arity == 0 && namespaces.TryGetValue (name, out ns)) {
+                               if (texpr == null)
+                                       return ns;
+
+                               ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (texpr.Type);
+                               // ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ns.loc, "");
+                               ctx.Module.Compiler.Report.Warning (437, 2, loc,
+                                       "The type `{0}' conflicts with the imported namespace `{1}'. Using the definition found in the source file",
+                                       texpr.GetSignatureForError (), ns.GetSignatureForError ());
+
+                               if (texpr.Type.MemberDefinition.IsImported)
+                                       return ns;
+                       }
 
-                       return LookupType (ctx, name, loc);
+                       return texpr;
                }
 
                //
-               // Completes types with the given `prefix' and stores the results in `result'
+               // Completes types with the given `prefix'
                //
-               public void CompletionGetTypesStartingWith (string prefix, Hashtable result)
+               public IEnumerable<string> CompletionGetTypesStartingWith (string prefix)
                {
-                       int l = fullname.Length + 1;
-                       ICollection res = root.CompletionGetTypesStartingWith (fullname + "." + prefix);
-
-                       if (res == null)
-                               return;
-                       
-                       foreach (string match in res){
-                               string x = match.Substring (l);
+                       if (types == null)
+                               return Enumerable.Empty<string> ();
 
-                               // Turn reflection nested classes foo+bar into foo.bar
-                               x = x.Replace ('+', '.');
+                       var res = from item in types
+                                         where item.Key.StartsWith (prefix) && item.Value.Any (l => (l.Modifiers & Modifiers.PUBLIC) != 0)
+                                         select item.Key;
 
-                               // Only get the first name element, no point in adding anything beyond the first dot.
-                               int p = x.IndexOf ('.');
-                               if (p != -1)
-                                       x = x.Substring (0, p);
+                       if (namespaces != null)
+                               res = res.Concat (from item in namespaces where item.Key.StartsWith (prefix) select item.Key);
 
-                               // Turn Foo`N into Foo<
-                               p = x.IndexOf ('`');
-                               if (p != -1)
-                                       x = x.Substring (0, p) + "<";
-
-                               if (!result.Contains (x))
-                                       result [x] = x;
-                       }
-               }
-
-               public void RegisterExternalExtensionMethodClass (Type type)
-               {
-                       // Ignore, extension methods cannot be nested
-                       if (type.DeclaringType != null)
-                               return;
-
-                       // TODO: CodeGen.Assembly.Builder is global
-                       if (type.IsNotPublic && !TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, type.Assembly))
-                               return;
-
-                       if (external_exmethod_classes == null)
-                               external_exmethod_classes = new ArrayList ();
-
-                       external_exmethod_classes.Add (type);
+                       return res;
                }
 
                /// 
                /// Looks for extension method in this namespace
                /// 
-               public ArrayList LookupExtensionMethod (Type extensionType, ClassOrStruct currentClass, string name)
+               public List<MethodSpec> LookupExtensionMethod (IMemberContext invocationContext, TypeSpec extensionType, string name, int arity)
                {
-                       ArrayList found = null;
+                       if (types == null)
+                               return null;
 
-                       // TODO: problematic
-                       var invocation_assembly = CodeGen.Assembly.Builder;
+                       List<MethodSpec> found = null;
 
-                       if (declspaces != null) {
-                               IEnumerator e = declspaces.Values.GetEnumerator ();
-                               e.Reset ();
-                               while (e.MoveNext ()) {
-                                       Class c = e.Current as Class;
-                                       if (c == null)
-                                               continue;
+                       // TODO: Add per namespace flag when at least 1 type has extension
 
-                                       if ((c.ModFlags & Modifiers.METHOD_EXTENSION) == 0)
+                       foreach (var tgroup in types.Values) {
+                               foreach (var ts in tgroup) {
+                                       if ((ts.Modifiers & Modifiers.METHOD_EXTENSION) == 0)
                                                continue;
 
-                                       ArrayList res = c.MemberCache.FindExtensionMethods (invocation_assembly, extensionType, name, c != currentClass);
+                                       var res = ts.MemberCache.FindExtensionMethods (invocationContext, extensionType, name, arity);
                                        if (res == null)
                                                continue;
 
-                                       if (found == null)
+                                       if (found == null) {
                                                found = res;
-                                       else
+                                       } else {
                                                found.AddRange (res);
+                                       }
                                }
                        }
 
-                       if (external_exmethod_classes == null)
-                               return found;
-
-                       foreach (Type t in external_exmethod_classes) {
-                               MemberCache m = TypeHandle.GetMemberCache (t);
-                               ArrayList res = m.FindExtensionMethods (invocation_assembly, extensionType, name, true);
-                               if (res == null)
-                                       continue;
+                       return found;
+               }
 
-                               if (found == null)
-                                       found = res;
-                               else
-                                       found.AddRange (res);
+               public void AddType (ModuleContainer module, TypeSpec ts)
+               {
+                       if (types == null) {
+                               types = new Dictionary<string, IList<TypeSpec>> (64);
                        }
 
-                       return found;
+                       var name = ts.Name;
+                       IList<TypeSpec> existing;
+                       if (types.TryGetValue (name, out existing)) {
+                               TypeSpec better_type;
+                               TypeSpec found;
+                               if (existing.Count == 1) {
+                                       found = existing[0];
+                                       if (ts.Arity == found.Arity) {
+                                               better_type = IsImportedTypeOverride (module, ts, found);
+                                               if (better_type == found)
+                                                       return;
+
+                                               if (better_type != null) {
+                                                       existing [0] = better_type;
+                                                       return;
+                                               }
+                                       }
+
+                                       existing = new List<TypeSpec> ();
+                                       existing.Add (found);
+                                       types[name] = existing;
+                               } else {
+                                       for (int i = 0; i < existing.Count; ++i) {
+                                               found = existing[i];
+                                               if (ts.Arity != found.Arity)
+                                                       continue;
+
+                                               better_type = IsImportedTypeOverride (module, ts, found);
+                                               if (better_type == found)
+                                                       return;
+
+                                               if (better_type != null) {
+                                                       existing.RemoveAt (i);
+                                                       --i;
+                                                       continue;
+                                               }
+                                       }
+                               }
+
+                               existing.Add (ts);
+                       } else {
+                               types.Add (name, new TypeSpec[] { ts });
+                       }
                }
 
-               public void AddDeclSpace (string name, DeclSpace ds)
+               //
+               // We import any types but in the situation there are same types
+               // but one has better visibility (either public or internal with friend)
+               // the less visible type is removed from the namespace cache
+               //
+               public static TypeSpec IsImportedTypeOverride (ModuleContainer module, TypeSpec ts, TypeSpec found)
                {
-                       if (declspaces == null)
-                               declspaces = new Dictionary<string, DeclSpace> ();
-                       declspaces.Add (name, ds);
+                       var ts_accessible = (ts.Modifiers & Modifiers.PUBLIC) != 0 || ts.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
+                       var found_accessible = (found.Modifiers & Modifiers.PUBLIC) != 0 || found.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
+
+                       if (ts_accessible && !found_accessible)
+                               return ts;
+
+                       // found is better always better for accessible or inaccessible ts
+                       if (!ts_accessible)
+                               return found;
+
+                       return null;
                }
 
                public void RemoveDeclSpace (string name)
                {
-                       declspaces.Remove (name);
-               }
-               
-               /// <summary>
-               ///   The qualified name of the current namespace
-               /// </summary>
-               public string Name {
-                       get { return fullname; }
+                       types.Remove (name);
+                       cached_types.Remove (name);
                }
 
-               /// <summary>
-               ///   The parent of this namespace, used by the parser to "Pop"
-               ///   the current namespace declaration
-               /// </summary>
-               public Namespace Parent {
-                       get { return parent; }
+               public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc)
+               {
+                       return this;
                }
-       }
 
-       //
-       // Namespace container as created by the parser
-       //
-       public class NamespaceEntry : IMemberContext {
-
-               class UsingEntry {
-                       readonly MemberName name;
-                       Namespace resolved;
-                       
-                       public UsingEntry (MemberName name)
-                       {
-                               this.name = name;
+               public void SetBuiltinType (BuiltinTypeSpec pts)
+               {
+                       var found = types[pts.Name];
+                       cached_types.Remove (pts.Name);
+                       if (found.Count == 1) {
+                               types[pts.Name][0] = pts;
+                       } else {
+                               throw new NotImplementedException ();
                        }
+               }
 
-                       public string GetSignatureForError ()
-                       {
-                               return name.GetSignatureForError ();
-                       }
+               public void VerifyClsCompliance ()
+               {
+                       if (types == null || cls_checked)
+                               return;
 
-                       public Location Location {
-                               get { return name.Location; }
-                       }
+                       cls_checked = true;
 
-                       public MemberName MemberName {
-                               get { return name; }
-                       }
-                       
-                       public string Name {
-                               get { return GetSignatureForError (); }
-                       }
+                       // TODO: This is quite ugly way to check for CLS compliance at namespace level
 
-                       public Namespace Resolve (IMemberContext rc)
-                       {
-                               if (resolved != null)
-                                       return resolved;
+                       var locase_types = new Dictionary<string, List<TypeSpec>> (StringComparer.OrdinalIgnoreCase);
+                       foreach (var tgroup in types.Values) {
+                               foreach (var tm in tgroup) {
+                                       if ((tm.Modifiers & Modifiers.PUBLIC) == 0 || !tm.IsCLSCompliant ())
+                                               continue;
 
-                               FullNamedExpression fne = name.GetTypeExpression ().ResolveAsTypeStep (rc, false);
-                               if (fne == null)
-                                       return null;
+                                       List<TypeSpec> found;
+                                       if (!locase_types.TryGetValue (tm.Name, out found)) {
+                                               found = new List<TypeSpec> ();
+                                               locase_types.Add (tm.Name, found);
+                                       }
 
-                               resolved = fne as Namespace;
-                               if (resolved == null) {
-                                       rc.Compiler.Report.SymbolRelatedToPreviousError (fne.Type);
-                                       rc.Compiler.Report.Error (138, Location,
-                                               "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
-                                               GetSignatureForError ());
+                                       found.Add (tm);
                                }
-                               return resolved;
-                       }
-
-                       public override string ToString ()
-                       {
-                               return Name;
                        }
-               }
 
-               class UsingAliasEntry {
-                       public readonly string Alias;
-                       public Location Location;
-
-                       public UsingAliasEntry (string alias, Location loc)
-                       {
-                               this.Alias = alias;
-                               this.Location = loc;
-                       }
+                       foreach (var locase in locase_types.Values) {
+                               if (locase.Count < 2)
+                                       continue;
 
-                       public virtual FullNamedExpression Resolve (IMemberContext rc)
-                       {
-                               FullNamedExpression fne = GlobalRootNamespace.Instance.GetRootNamespace (Alias);
-                               if (fne == null) {
-                                       rc.Compiler.Report.Error (430, Location,
-                                               "The extern alias `{0}' was not specified in -reference option",
-                                               Alias);
+                               bool all_same = true;
+                               foreach (var notcompliant in locase) {
+                                       all_same = notcompliant.Name == locase[0].Name;
+                                       if (!all_same)
+                                               break;
                                }
 
-                               return fne;
-                       }
-
-                       public override string ToString ()
-                       {
-                               return Alias;
-                       }
-                       
-               }
-
-               class LocalUsingAliasEntry : UsingAliasEntry {
-                       FullNamedExpression resolved;
-                       MemberName value;
-
-                       public LocalUsingAliasEntry (string alias, MemberName name, Location loc)
-                               : base (alias, loc)
-                       {
-                               this.value = name;
-                       }
-
-                       public override FullNamedExpression Resolve (IMemberContext rc)
-                       {
-                               if (resolved != null || value == null)
-                                       return resolved;
+                               if (all_same)
+                                       continue;
 
-                               if (rc == null)
-                                       return null;
+                               TypeContainer compiled = null;
+                               foreach (var notcompliant in locase) {
+                                       if (!notcompliant.MemberDefinition.IsImported) {
+                                               if (compiled != null)
+                                                       compiled.Compiler.Report.SymbolRelatedToPreviousError (compiled);
 
-                               resolved = value.GetTypeExpression ().ResolveAsTypeStep (rc, false);
-                               if (resolved == null) {
-                                       value = null;
-                                       return null;
+                                               compiled = notcompliant.MemberDefinition as TypeContainer;
+                                       } else {
+                                               compiled.Compiler.Report.SymbolRelatedToPreviousError (notcompliant);
+                                       }
                                }
 
-                               if (resolved is TypeExpr)
-                                       resolved = resolved.ResolveAsBaseTerminal (rc, false);
-
-                               return resolved;
-                       }
-
-                       public override string ToString ()
-                       {
-                               return String.Format ("{0} = {1}", Alias, value.GetSignatureForError ());
+                               compiled.Compiler.Report.Warning (3005, 1, compiled.Location,
+                                       "Identifier `{0}' differing only in case is not CLS-compliant", compiled.GetSignatureForError ());
                        }
                }
+       }
 
+       //
+       // Namespace block as created by the parser
+       //
+       public class NamespaceContainer : IMemberContext, ITypesContainer
+       {
                Namespace ns;
-               NamespaceEntry parent, implicit_parent;
-               CompilationUnit file;
+
+               readonly ModuleContainer module;
+               readonly NamespaceContainer parent;
+               readonly CompilationSourceFile file;
+               readonly Location loc;
+
+               NamespaceContainer implicit_parent;
                int symfile_id;
 
                // Namespace using import block
-               ArrayList using_aliases;
-               ArrayList using_clauses;
-               public bool DeclarationFound = false;
+               List<NamespaceUsingAlias> using_aliases;
+               List<NamespaceUsing> using_clauses;
+               public bool DeclarationFound;
                // End
 
+               bool resolved;
+
                public readonly bool IsImplicit;
-               public readonly DeclSpace SlaveDeclSpace;
+               public readonly TypeContainer SlaveDeclSpace;
                static readonly Namespace [] empty_namespaces = new Namespace [0];
-               Namespace [] namespace_using_table;
-
-               static ArrayList entries = new ArrayList ();
+               static readonly string[] empty_using_list = new string[0];
 
-               public static void Reset ()
-               {
-                       entries = new ArrayList ();
-               }
+               Namespace [] namespace_using_table;
 
-               public NamespaceEntry (NamespaceEntry parent, CompilationUnit file, string name)
+               public NamespaceContainer (MemberName name, ModuleContainer module, NamespaceContainer parent, CompilationSourceFile sourceFile)
                {
+                       this.module = module;
                        this.parent = parent;
-                       this.file = file;
-                       entries.Add (this);
+                       this.file = sourceFile;
+                       this.loc = name == null ? Location.Null : name.Location;
 
                        if (parent != null)
-                               ns = parent.NS.GetNamespace (name, true);
+                               ns = parent.NS.GetNamespace (name.GetName (), true);
                        else if (name != null)
-                               ns = GlobalRootNamespace.Instance.GetNamespace (name, true);
+                               ns = module.GlobalRootNamespace.GetNamespace (name.GetName (), true);
                        else
-                               ns = GlobalRootNamespace.Instance;
-                       SlaveDeclSpace = new RootDeclSpace (this);
+                               ns = module.GlobalRootNamespace;
+
+                       SlaveDeclSpace = new RootDeclSpace (module, this);
                }
 
-               private NamespaceEntry (NamespaceEntry parent, CompilationUnit file, Namespace ns, bool slave)
+               private NamespaceContainer (ModuleContainer module, NamespaceContainer parent, CompilationSourceFile file, Namespace ns, bool slave)
                {
+                       this.module = module;
                        this.parent = parent;
                        this.file = file;
                        this.IsImplicit = true;
                        this.ns = ns;
-                       this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
+                       this.SlaveDeclSpace = slave ? new RootDeclSpace (module, this) : null;
                }
 
-               //
-               // Populates the Namespace with some using declarations, used by the
-               // eval mode. 
-               //
-               public void Populate (ArrayList source_using_aliases, ArrayList source_using_clauses)
-               {
-                       foreach (UsingAliasEntry uae in source_using_aliases){
-                               if (using_aliases == null)
-                                       using_aliases = new ArrayList ();
-                               
-                               using_aliases.Add (uae);
+               #region Properties
+
+               public Location Location {
+                       get {
+                               return loc;
+                       }
+               }
+
+               public MemberName MemberName {
+                       get {
+                               return ns.MemberName;
                        }
+               }
 
-                       foreach (UsingEntry ue in source_using_clauses){
-                               if (using_clauses == null)
-                                       using_clauses = new ArrayList ();
-                               
-                               using_clauses.Add (ue);
+               public CompilationSourceFile SourceFile {
+                       get {
+                               return file;
                        }
                }
 
+               public List<NamespaceUsing> Usings {
+                       get {
+                               return using_clauses;
+                       }
+               }
+
+               #endregion
+
                //
                // Extracts the using alises and using clauses into a couple of
                // arrays that might already have the same information;  Used by the
                // C# Eval mode.
                //
-               public void Extract (ArrayList out_using_aliases, ArrayList out_using_clauses)
+               public void Extract (List<NamespaceUsingAlias> out_using_aliases, List<NamespaceUsing> out_using_clauses)
                {
                        if (using_aliases != null){
-                               foreach (UsingAliasEntry uae in using_aliases){
+                               foreach (NamespaceUsingAlias uae in using_aliases){
                                        bool replaced = false;
                                        
                                        for (int i = 0; i < out_using_aliases.Count; i++){
-                                               UsingAliasEntry out_uea = (UsingAliasEntry) out_using_aliases [i];
+                                               NamespaceUsingAlias out_uea = (NamespaceUsingAlias) out_using_aliases [i];
                                                
                                                if (out_uea.Alias == uae.Alias){
                                                        out_using_aliases [i] = uae;
@@ -892,10 +650,10 @@ namespace Mono.CSharp {
                        }
 
                        if (using_clauses != null){
-                               foreach (UsingEntry ue in using_clauses){
+                               foreach (NamespaceUsing ue in using_clauses){
                                        bool found = false;
                                        
-                                       foreach (UsingEntry out_ue in out_using_clauses)
+                                       foreach (NamespaceUsing out_ue in out_using_clauses)
                                                if (out_ue.Name == ue.Name){
                                                        found = true;
                                                        break;
@@ -916,11 +674,11 @@ namespace Mono.CSharp {
                // To implement these rules, the expressions in the using directives are resolved using 
                // the "doppelganger" (ghostly bodiless duplicate).
                //
-               NamespaceEntry doppelganger;
-               NamespaceEntry Doppelganger {
+               NamespaceContainer doppelganger;
+               NamespaceContainer Doppelganger {
                        get {
                                if (!IsImplicit && doppelganger == null) {
-                                       doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
+                                       doppelganger = new NamespaceContainer (module, ImplicitParent, file, ns, true);
                                        doppelganger.using_aliases = using_aliases;
                                }
                                return doppelganger;
@@ -931,18 +689,18 @@ namespace Mono.CSharp {
                        get { return ns; }
                }
 
-               public NamespaceEntry Parent {
+               public NamespaceContainer Parent {
                        get { return parent; }
                }
 
-               public NamespaceEntry ImplicitParent {
+               public NamespaceContainer ImplicitParent {
                        get {
                                if (parent == null)
                                        return null;
                                if (implicit_parent == null) {
                                        implicit_parent = (parent.NS == ns.Parent)
                                                ? parent
-                                               : new NamespaceEntry (parent, file, ns.Parent, false);
+                                               : new NamespaceContainer (module, parent, file, ns.Parent, false);
                                }
                                return implicit_parent;
                        }
@@ -958,9 +716,9 @@ namespace Mono.CSharp {
                        }
 
                        if (using_clauses == null) {
-                               using_clauses = new ArrayList ();
+                               using_clauses = new List<NamespaceUsing> ();
                        } else {
-                               foreach (UsingEntry old_entry in using_clauses) {
+                               foreach (NamespaceUsing old_entry in using_clauses) {
                                        if (name.Equals (old_entry.MemberName)) {
                                                Compiler.Report.SymbolRelatedToPreviousError (old_entry.Location, old_entry.GetSignatureForError ());
                                                Compiler.Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetSignatureForError ());
@@ -969,29 +727,23 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       using_clauses.Add (new UsingEntry (name));
+                       using_clauses.Add (new NamespaceUsing (name));
                }
 
                public void AddUsingAlias (string alias, MemberName name, Location loc)
                {
-                       // TODO: This is parser bussines
                        if (DeclarationFound){
                                Compiler.Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
                        }
 
-                       if (RootContext.Version != LanguageVersion.ISO_1 && alias == "global")
-                               Compiler.Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
-                                       " the global namespace will be used instead");
-
                        AddUsingAlias (new LocalUsingAliasEntry (alias, name, loc));
                }
 
                public void AddUsingExternalAlias (string alias, Location loc, Report Report)
                {
-                       // TODO: Do this in parser
                        bool not_first = using_clauses != null || DeclarationFound;
                        if (using_aliases != null && !not_first) {
-                               foreach (UsingAliasEntry uae in using_aliases) {
+                               foreach (NamespaceUsingAlias uae in using_aliases) {
                                        if (uae is LocalUsingAliasEntry) {
                                                not_first = true;
                                                break;
@@ -1007,15 +759,15 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       AddUsingAlias (new UsingAliasEntry (alias, loc));
+                       AddUsingAlias (new NamespaceUsingAlias (alias, loc));
                }
 
-               void AddUsingAlias (UsingAliasEntry uae)
+               void AddUsingAlias (NamespaceUsingAlias uae)
                {
                        if (using_aliases == null) {
-                               using_aliases = new ArrayList ();
+                               using_aliases = new List<NamespaceUsingAlias> ();
                        } else {
-                               foreach (UsingAliasEntry entry in using_aliases) {
+                               foreach (NamespaceUsingAlias entry in using_aliases) {
                                        if (uae.Alias == entry.Alias) {
                                                Compiler.Report.SymbolRelatedToPreviousError (uae.Location, uae.Alias);
                                                Compiler.Report.Error (1537, entry.Location, "The using alias `{0}' appeared previously in this namespace",
@@ -1028,15 +780,15 @@ namespace Mono.CSharp {
                        using_aliases.Add (uae);
                }
 
-               ///
-               /// Does extension methods look up to find a method which matches name and extensionType.
-               /// Search starts from this namespace and continues hierarchically up to top level.
-               ///
-               public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
+               //
+               // Does extension methods look up to find a method which matches name and extensionType.
+               // Search starts from this namespace and continues hierarchically up to top level.
+               //
+               public IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceContainer scope)
                {
-                       ArrayList candidates = null;
+                       List<MethodSpec> candidates = null;
                        foreach (Namespace n in GetUsingTable ()) {
-                               ArrayList a = n.LookupExtensionMethod (extensionType, null, name);
+                               var a = n.LookupExtensionMethod (this, extensionType, name, arity);
                                if (a == null)
                                        continue;
 
@@ -1046,8 +798,9 @@ namespace Mono.CSharp {
                                        candidates.AddRange (a);
                        }
 
+                       scope = parent;
                        if (candidates != null)
-                               return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
+                               return candidates;
 
                        if (parent == null)
                                return null;
@@ -1057,9 +810,9 @@ namespace Mono.CSharp {
                        //
                        Namespace parent_ns = ns.Parent;
                        do {
-                               candidates = parent_ns.LookupExtensionMethod (extensionType, null, name);
+                               candidates = parent_ns.LookupExtensionMethod (this, extensionType, name, arity);
                                if (candidates != null)
-                                       return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
+                                       return candidates;
 
                                parent_ns = parent_ns.Parent;
                        } while (parent_ns != null);
@@ -1067,77 +820,70 @@ namespace Mono.CSharp {
                        //
                        // Continue in parent scope
                        //
-                       return parent.LookupExtensionMethod (extensionType, name, loc);
+                       return parent.LookupExtensionMethod (extensionType, name, arity, ref scope);
                }
 
-               public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+               public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
                {
                        // Precondition: Only simple names (no dots) will be looked up with this function.
                        FullNamedExpression resolved = null;
-                       for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
-                               if ((resolved = curr_ns.Lookup (name, loc, ignore_cs0104)) != null)
+                       for (NamespaceContainer curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
+                               if ((resolved = curr_ns.Lookup (name, arity, loc, ignore_cs0104)) != null)
                                        break;
                        }
+
                        return resolved;
                }
 
-               public ICollection CompletionGetTypesStartingWith (string prefix)
+               public IList<string> CompletionGetTypesStartingWith (string prefix)
                {
-                       Hashtable result = new Hashtable ();
+                       IEnumerable<string> all = Enumerable.Empty<string> ();
                        
-                       for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent){
+                       for (NamespaceContainer curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent){
                                foreach (Namespace using_ns in GetUsingTable ()){
                                        if (prefix.StartsWith (using_ns.Name)){
                                                int ld = prefix.LastIndexOf ('.');
                                                if (ld != -1){
                                                        string rest = prefix.Substring (ld+1);
 
-                                                       using_ns.CompletionGetTypesStartingWith (rest, result);
+                                                       all = all.Concat (using_ns.CompletionGetTypesStartingWith (rest));
                                                }
                                        }
-                                       using_ns.CompletionGetTypesStartingWith (prefix, result);
+                                       all = all.Concat (using_ns.CompletionGetTypesStartingWith (prefix));
                                }
                        }
 
-                       return result.Keys;
+                       return all.Distinct ().ToList ();
                }
                
-               void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
-               {
-                       Compiler.Report.SymbolRelatedToPreviousError (t1.Type);
-                       Compiler.Report.SymbolRelatedToPreviousError (t2.Type);
-                       Compiler.Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
-                               name, t1.GetSignatureForError (), t2.GetSignatureForError ());
-               }
-
                // Looks-up a alias named @name in this and surrounding namespace declarations
                public FullNamedExpression LookupNamespaceAlias (string name)
                {
-                       for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
+                       for (NamespaceContainer n = this; n != null; n = n.ImplicitParent) {
                                if (n.using_aliases == null)
                                        continue;
 
-                               foreach (UsingAliasEntry ue in n.using_aliases) {
+                               foreach (NamespaceUsingAlias ue in n.using_aliases) {
                                        if (ue.Alias == name)
-                                               return ue.Resolve (Doppelganger);
+                                               return ue.Resolve (Doppelganger ?? this, Doppelganger == null);
                                }
                        }
 
                        return null;
                }
 
-               private FullNamedExpression Lookup (string name, Location loc, bool ignore_cs0104)
+               private FullNamedExpression Lookup (string name, int arity, Location loc, bool ignore_cs0104)
                {
                        //
                        // Check whether it's in the namespace.
                        //
-                       FullNamedExpression fne = ns.Lookup (Compiler, name, loc);
+                       FullNamedExpression fne = ns.LookupTypeOrNamespace (this, name, arity, loc);
 
                        //
                        // Check aliases. 
                        //
-                       if (using_aliases != null) {
-                               foreach (UsingAliasEntry ue in using_aliases) {
+                       if (using_aliases != null && arity == 0) {
+                               foreach (NamespaceUsingAlias ue in using_aliases) {
                                        if (ue.Alias == name) {
                                                if (fne != null) {
                                                        if (Doppelganger != null) {
@@ -1152,13 +898,15 @@ namespace Mono.CSharp {
                                                        }
                                                }
 
-                                               return ue.Resolve (Doppelganger);
+                                               return ue.Resolve (Doppelganger ?? this, Doppelganger == null);
                                        }
                                }
                        }
 
-                       if (fne != null)
-                               return fne;
+                       if (fne != null) {
+                               if (!((fne.Type.Modifiers & Modifiers.INTERNAL) != 0 && !fne.Type.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly)))
+                                       return fne;
+                       }
 
                        if (IsImplicit)
                                return null;
@@ -1168,18 +916,45 @@ namespace Mono.CSharp {
                        //
                        FullNamedExpression match = null;
                        foreach (Namespace using_ns in GetUsingTable ()) {
-                               match = using_ns.Lookup (Compiler, name, loc);
-                               if (match == null || !(match is TypeExpr))
+                               // A using directive imports only types contained in the namespace, it
+                               // does not import any nested namespaces
+                               fne = using_ns.LookupType (this, name, arity, loc);
+                               if (fne == null)
+                                       continue;
+
+                               if (match == null) {
+                                       match = fne;
                                        continue;
-                               if (fne != null) {
-                                       if (!ignore_cs0104)
-                                               Error_AmbiguousTypeReference (loc, name, fne, match);
-                                       return null;
                                }
-                               fne = match;
+
+                               // Prefer types over namespaces
+                               var texpr_fne = fne as TypeExpr;
+                               var texpr_match = match as TypeExpr;
+                               if (texpr_fne != null && texpr_match == null) {
+                                       match = fne;
+                                       continue;
+                               } else if (texpr_fne == null) {
+                                       continue;
+                               }
+
+                               if (ignore_cs0104)
+                                       return match;
+
+                               // It can be top level accessibility only
+                               var better = Namespace.IsImportedTypeOverride (module, texpr_match.Type, texpr_fne.Type);
+                               if (better == null) {
+                                       Compiler.Report.SymbolRelatedToPreviousError (texpr_match.Type);
+                                       Compiler.Report.SymbolRelatedToPreviousError (texpr_fne.Type);
+                                       Compiler.Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
+                                               name, texpr_match.GetSignatureForError (), texpr_fne.GetSignatureForError ());
+                                       return match;
+                               }
+
+                               if (better == texpr_fne.Type)
+                                       match = texpr_fne;
                        }
 
-                       return fne;
+                       return match;
                }
 
                Namespace [] GetUsingTable ()
@@ -1192,9 +967,9 @@ namespace Mono.CSharp {
                                return namespace_using_table;
                        }
 
-                       ArrayList list = new ArrayList (using_clauses.Count);
+                       var list = new List<Namespace> (using_clauses.Count);
 
-                       foreach (UsingEntry ue in using_clauses) {
+                       foreach (NamespaceUsing ue in using_clauses) {
                                Namespace using_ns = ue.Resolve (Doppelganger);
                                if (using_ns == null)
                                        continue;
@@ -1202,12 +977,10 @@ namespace Mono.CSharp {
                                list.Add (using_ns);
                        }
 
-                       namespace_using_table = (Namespace[])list.ToArray (typeof (Namespace));
+                       namespace_using_table = list.ToArray ();
                        return namespace_using_table;
                }
 
-               static readonly string [] empty_using_list = new string [0];
-
                public int SymbolFileID {
                        get {
                                if (symfile_id == 0 && file.SourceFileEntry != null) {
@@ -1217,7 +990,7 @@ namespace Mono.CSharp {
                                        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]).MemberName.GetName ();
+                                                       using_list [i] = ((NamespaceUsing) using_clauses [i]).MemberName.GetName ();
                                        }
 
                                        symfile_id = SymbolWriter.DefineNamespace (ns.Name, file.CompileUnitEntry, using_list, parent_id);
@@ -1238,7 +1011,7 @@ namespace Mono.CSharp {
 
                public static void Error_GlobalNamespaceRedefined (Location loc, Report Report)
                {
-                       Report.Error (1681, loc, "You cannot redefine the global extern alias");
+                       Report.Error (1681, loc, "The global extern alias cannot be redefined");
                }
 
                public static void Error_NamespaceNotFound (Location loc, string name, Report Report)
@@ -1248,15 +1021,15 @@ namespace Mono.CSharp {
 
                        switch (name) {
                        case "Gtk": case "GtkSharp":
-                               MsgtryPkg ("gtk-sharp");
+                               MsgtryPkg ("gtk-sharp-2.0");
                                break;
 
                        case "Gdk": case "GdkSharp":
-                               MsgtryPkg ("gdk-sharp");
+                               MsgtryPkg ("gdk-sharp-2.0");
                                break;
 
                        case "Glade": case "GladeSharp":
-                               MsgtryPkg ("glade-sharp");
+                               MsgtryPkg ("glade-sharp-2.0");
                                break;
 
                        case "System.Drawing":
@@ -1273,27 +1046,25 @@ namespace Mono.CSharp {
                ///   Used to validate that all the using clauses are correct
                ///   after we are finished parsing all the files.  
                /// </summary>
-               void VerifyUsing ()
+               public void Resolve ()
                {
+                       if (resolved)
+                               return;
+
+                       resolved = true;
+
                        if (using_aliases != null) {
-                               foreach (UsingAliasEntry ue in using_aliases)
-                                       ue.Resolve (Doppelganger);
+                               foreach (NamespaceUsingAlias ue in using_aliases)
+                                       ue.Resolve (Doppelganger, Doppelganger == null);
                        }
 
                        if (using_clauses != null) {
-                               foreach (UsingEntry ue in using_clauses)
+                               foreach (NamespaceUsing ue in using_clauses)
                                        ue.Resolve (Doppelganger);
                        }
-               }
 
-               /// <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 ();
+                       if (parent != null)
+                               parent.Resolve ();
                }
 
                public string GetSignatureForError ()
@@ -1301,29 +1072,29 @@ namespace Mono.CSharp {
                        return ns.GetSignatureForError ();
                }
 
-               public override string ToString ()
-               {
-                       return ns.ToString ();
-               }
-
                #region IMemberContext Members
 
-               public CompilerContext Compiler {
-                       get { return RootContext.ToplevelTypes.Compiler; }
+               CompilerContext Compiler {
+                       get { return module.Compiler; }
                }
 
-               public Type CurrentType {
+               public TypeSpec CurrentType {
                        get { return SlaveDeclSpace.CurrentType; }
                }
 
-               public TypeContainer CurrentTypeDefinition {
-                       get { return SlaveDeclSpace.CurrentTypeDefinition; }
+               public MemberCore CurrentMemberDefinition {
+                       get { return SlaveDeclSpace.CurrentMemberDefinition; }
                }
 
                public TypeParameter[] CurrentTypeParameters {
                        get { return SlaveDeclSpace.CurrentTypeParameters; }
                }
 
+               // FIXME: It's false for expression types
+               public bool HasUnresolvedConstraints {
+                       get { return true; }
+               }
+
                public bool IsObsolete {
                        get { return SlaveDeclSpace.IsObsolete; }
                }
@@ -1336,6 +1107,116 @@ namespace Mono.CSharp {
                        get { return SlaveDeclSpace.IsStatic; }
                }
 
+               public ModuleContainer Module {
+                       get { return module; }
+               }
+
                #endregion
        }
+
+       public class NamespaceUsing
+       {
+               readonly MemberName name;
+               Namespace resolved;
+
+               public NamespaceUsing (MemberName name)
+               {
+                       this.name = name;
+               }
+
+               public string GetSignatureForError ()
+               {
+                       return name.GetSignatureForError ();
+               }
+
+               public Location Location
+               {
+                       get { return name.Location; }
+               }
+
+               public MemberName MemberName
+               {
+                       get { return name; }
+               }
+
+               public string Name
+               {
+                       get { return GetSignatureForError (); }
+               }
+
+               public Namespace Resolve (IMemberContext rc)
+               {
+                       if (resolved != null)
+                               return resolved;
+
+                       FullNamedExpression fne = name.GetTypeExpression ().ResolveAsTypeOrNamespace (rc);
+                       if (fne == null)
+                               return null;
+
+                       resolved = fne as Namespace;
+                       if (resolved == null) {
+                               rc.Module.Compiler.Report.SymbolRelatedToPreviousError (fne.Type);
+                               rc.Module.Compiler.Report.Error (138, Location,
+                                       "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
+                                       GetSignatureForError ());
+                       }
+                       return resolved;
+               }
+       }
+
+       public class NamespaceUsingAlias
+       {
+               public readonly string Alias;
+               public Location Location;
+
+               public NamespaceUsingAlias (string alias, Location loc)
+               {
+                       this.Alias = alias;
+                       this.Location = loc;
+               }
+
+               public virtual FullNamedExpression Resolve (IMemberContext rc, bool local)
+               {
+                       FullNamedExpression fne = rc.Module.GetRootNamespace (Alias);
+                       if (fne == null) {
+                               rc.Module.Compiler.Report.Error (430, Location,
+                                       "The extern alias `{0}' was not specified in -reference option",
+                                       Alias);
+                       }
+
+                       return fne;
+               }
+       }
+
+       class LocalUsingAliasEntry : NamespaceUsingAlias
+       {
+               FullNamedExpression resolved;
+               MemberName value;
+
+               public LocalUsingAliasEntry (string alias, MemberName name, Location loc)
+                       : base (alias, loc)
+               {
+                       this.value = name;
+               }
+
+               public override FullNamedExpression Resolve (IMemberContext rc, bool local)
+               {
+                       if (resolved != null || value == null)
+                               return resolved;
+
+                       if (local)
+                               return null;
+
+                       resolved = value.GetTypeExpression ().ResolveAsTypeOrNamespace (rc);
+                       if (resolved == null) {
+                               value = null;
+                               return null;
+                       }
+
+                       if (resolved is TypeExpr)
+                               resolved = resolved.ResolveAsType (rc);
+
+                       return resolved;
+               }
+       }
 }