2010-05-27 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / namespace.cs
index f40d3ba2837ad0fcef427a52bf770427e0608da9..3e9140e9649e3927b8d9a298f22a787f0c927cbd 100644 (file)
 using System;
 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);
-               }
-
                public RootNamespace (string alias_name)
                        : base (null, String.Empty)
                {
@@ -56,11 +46,11 @@ namespace Mono.CSharp {
                        referenced_assemblies = n;
                }
 
-               public void ComputeNamespace (CompilerContext ctx, Type extensionType)
+               public void ImportTypes (CompilerContext ctx)
                {
                        foreach (Assembly a in referenced_assemblies) {
                                try {
-                                       ComputeNamespaces (a, extensionType);
+                                       ImportAssembly (a);
                                } catch (TypeLoadException e) {
                                        ctx.Report.Error (11, Location.Null, e.Message);
                                } catch (System.IO.FileNotFoundException) {
@@ -70,77 +60,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               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<string> CompletionGetTypesStartingWith (string prefix)
-               {
-                       Dictionary<string, string> result = null;
-
-                       foreach (Assembly a in referenced_assemblies){
-                               Type [] mtypes = a.GetTypes ();
-
-                               foreach (Type t in mtypes){
-                                       if (t.IsNotPublic)
-                                               continue;
-                                       
-                                       string f = t.FullName;
-
-                                       if (f.StartsWith (prefix) && (result == null || !result.ContainsKey (f))){
-                                               if (result == null)
-                                                       result = new Dictionary<string, string> ();
-
-                                               result [f] = f;
-                                       }
-                               }
-                       }
-                       return result == null ? null : 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)
                {
                        if (child != this)
@@ -158,74 +77,43 @@ 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)
+               public void ImportAssembly (Assembly assembly)
                {
-                       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);
-                       }
-               }
+                       Type extension_type = null;
+                       var all_attributes = CustomAttributeData.GetCustomAttributes (assembly);
+                       foreach (var attr in all_attributes) {
+                               var dt = attr.Constructor.DeclaringType;
+                               if (dt.Name == "ExtensionAttribute" && dt.Namespace == "System.Runtime.CompilerServices") {
+                                       extension_type = dt;
+                                       break;
+                               }
+                       }
 
-               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;
+                       Namespace ns = this;
+                       string prev_namespace = null;
+                       foreach (var t in assembly.GetTypes ()) {
+                               if (t.IsNested)
+                                       continue;
 
-                       if (t.IsPointer)
-                               throw new InternalErrorException ("Use GetPointerType() to get a pointer");
+                               if (t.Name[0] == '<')
+                                       continue;
 
-                       TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
-                       if (ta == TypeAttributes.NestedPrivate)
-                               return null;
+                               var it = Import.CreateType (t);
+                               if (it == null)
+                                       continue;
 
-                       if ((ta == TypeAttributes.NotPublic ||
-                            ta == TypeAttributes.NestedAssembly ||
-                            ta == TypeAttributes.NestedFamANDAssem) &&
-                           !TypeManager.IsThisOrFriendAssembly (invocation, t.Assembly))
-                               return null;
+                               if (prev_namespace != t.Namespace) {
+                                       ns = t.Namespace == null ? this : GetNamespace (t.Namespace, true);
+                                       prev_namespace = t.Namespace;
+                               }
 
-                       return t;
-               }
+                               ns.AddType (it);
 
-               public override string ToString ()
-               {
-                       return String.Format ("RootNamespace ({0}::)", alias_name);
-               }
+                               if (it.IsStatic && extension_type != null && t.IsDefined (extension_type, false)) {
+                                       it.SetExtensionMethodContainer ();
+                               }
+                       }
+               }
 
                public override string GetSignatureForError ()
                {
@@ -271,20 +159,14 @@ namespace Mono.CSharp {
                        if (m == RootContext.ToplevelTypes.Builder)
                                return;
 
-                       foreach (Type t in m.GetTypes ())
+                       foreach (var 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", MemberKind.Class, false);
-
                        foreach (RootNamespace rn in root_namespaces.Values) {
-                               rn.ComputeNamespace (ctx, extension_attribute_type);
+                               rn.ImportTypes (ctx);
                        }
                }
 
@@ -304,7 +186,7 @@ namespace Mono.CSharp {
                        retval.AddAssemblyReference (assembly);
                }
 
-               public override void Error_NamespaceDoesNotExist (Location loc, string name, IMemberContext ctx)
+               public override void Error_NamespaceDoesNotExist (Location loc, string name, int arity, IMemberContext ctx)
                {
                        ctx.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?)",
@@ -319,37 +201,6 @@ namespace Mono.CSharp {
 
                        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>
@@ -362,11 +213,11 @@ namespace Mono.CSharp {
                
                Namespace parent;
                string fullname;
-               Dictionary<string, Namespace> namespaces;
-               Dictionary<string, DeclSpace> declspaces;
+               protected Dictionary<string, Namespace> namespaces;
+               protected Dictionary<string, IList<TypeSpec>> types;
                Dictionary<string, TypeExpr> cached_types;
                RootNamespace root;
-               List<Type> external_exmethod_classes;
+               bool cls_checked;
 
                public readonly MemberName MemberName;
 
@@ -379,7 +230,7 @@ namespace Mono.CSharp {
                {
                        // Expression members.
                        this.eclass = ExprClass.Namespace;
-                       this.Type = typeof (Namespace);
+                       this.Type = InternalType.FakeInternalType;
                        this.loc = Location.Null;
 
                        this.parent = parent;
@@ -415,25 +266,42 @@ namespace Mono.CSharp {
                        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;
-                               }
+                       FullNamedExpression retval = Lookup (ctx.Compiler, name, -System.Math.Max (1, arity), loc);
+                       if (retval != null) {
+                               Error_TypeArgumentsCannotBeUsed (ctx.Compiler.Report, loc, retval.Type, arity);
+                               return;
+                       }
+
+                       Namespace ns;
+                       if (arity > 0 && namespaces.TryGetValue (name, out ns)) {
+                               ns.Error_TypeArgumentsCannotBeUsed (ctx.Compiler.Report, loc, null, arity);
+                               return;
                        }
 
                        ctx.Compiler.Report.Error (234, loc,
@@ -441,13 +309,6 @@ namespace Mono.CSharp {
                                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;
@@ -478,204 +339,318 @@ namespace Mono.CSharp {
                        return ns;
                }
 
-               public bool HasDefinition (string name)
+               TypeExpr LookupType (CompilerContext ctx, string name, int arity, Location loc)
                {
-                       return declspaces != null && declspaces.ContainsKey (name);
-               }
+                       if (types == null)
+                               return null;
 
-               TypeExpr LookupType (CompilerContext ctx, string name, Location loc)
-               {
                        TypeExpr te;
-                       if (cached_types.TryGetValue (name, out te))
+                       if (arity == 0 && cached_types.TryGetValue (name, out te))
                                return te;
 
-                       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;
+                       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.Report.SymbolRelatedToPreviousError (best);
+                                               ctx.Report.SymbolRelatedToPreviousError (ts);
+                                               ctx.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", ts.GetSignatureForError ());
+                                               break;
+                                       }
+
+                                       var pts = best as PredefinedTypeSpec;
+                                       if (pts == null)
+                                               pts = ts as PredefinedTypeSpec;
+
+                                       if (pts != null) {
+                                               ctx.Report.SymbolRelatedToPreviousError (best);
+                                               ctx.Report.SymbolRelatedToPreviousError (ts);
+                                               ctx.Report.Warning (1685, 1, loc,
+                                                       "The predefined type `{0}.{1}' is redefined in the source code. Ignoring the local type definition",
+                                                       pts.Namespace, pts.Name);
+                                               best = pts;
+                                               continue;
+                                       }
+
+                                       if (best.MemberDefinition.IsImported)
+                                               best = ts;
+
+                                       if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, best.MemberDefinition.Assembly))
+                                               continue;
+
+                                       if (ts.MemberDefinition.IsImported)
+                                               ctx.Report.SymbolRelatedToPreviousError (ts);
+
+                                       ctx.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;
+
+                       te = new TypeExpression (best, Location.Null);
+
+                       // TODO MemberCache: Cache more
+                       if (arity == 0)
+                               cached_types.Add (name, te);
 
-                       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 Lookup (CompilerContext ctx, string name, int arity, Location loc)
                {
-                       if (namespaces.ContainsKey (name))
+                       if (arity == 0 && namespaces.ContainsKey (name))
                                return namespaces [name];
 
-                       return LookupType (ctx, name, loc);
+                       return LookupType (ctx, name, arity, loc);
                }
 
                //
-               // Completes types with the given `prefix' and stores the results in `result'
+               // Completes types with the given `prefix'
                //
-               public void CompletionGetTypesStartingWith (string prefix, Dictionary<string, string> result)
+               public IEnumerable<string> CompletionGetTypesStartingWith (string prefix)
                {
-                       int l = fullname.Length + 1;
-                       var 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.ContainsKey (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 List<Type> ();
-
-                       external_exmethod_classes.Add (type);
+                       return res;
                }
 
                /// 
                /// Looks for extension method in this namespace
                /// 
-               public List<MethodSpec> LookupExtensionMethod (Type extensionType, ClassOrStruct currentClass, string name)
+               public List<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, ClassOrStruct currentClass, string name, int arity)
                {
+                       if (types == null)
+                               return null;
+
                        List<MethodSpec> found = null;
 
-                       // TODO: problematic
-                       var invocation_assembly = CodeGen.Assembly.Builder;
+                       var invocation_type = currentClass == null ? InternalType.FakeInternalType : currentClass.CurrentType;
 
-                       if (declspaces != null) {
-                               var e = declspaces.Values.GetEnumerator ();
-                               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;
 
-                                       var res = c.MemberCache.FindExtensionMethods (invocation_assembly, extensionType, name, c != currentClass);
+                                       var res = ts.MemberCache.FindExtensionMethods (invocation_type, 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);
-                               var 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 (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 (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 (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 (TypeSpec ts, TypeSpec found)
                {
-                       if (declspaces == null)
-                               declspaces = new Dictionary<string, DeclSpace> ();
-                       declspaces.Add (name, ds);
+                       var ts_accessible = (ts.Modifiers & Modifiers.PUBLIC) != 0 || TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, ts.MemberDefinition.Assembly);
+                       var found_accessible = (found.Modifiers & Modifiers.PUBLIC) != 0 || TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, found.MemberDefinition.Assembly);
+
+                       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);
+                       types.Remove (name);
                }
-               
-               /// <summary>
-               ///   The qualified name of the current namespace
-               /// </summary>
-               public string Name {
-                       get { return fullname; }
+
+               public void ReplaceTypeWithPredefined (TypeSpec ts, PredefinedTypeSpec pts)
+               {
+                       var found = types [ts.Name];
+                       cached_types.Remove (ts.Name);
+                       if (found.Count == 1) {
+                               types[ts.Name][0] = pts;
+                       } else {
+                               throw new NotImplementedException ();
+                       }
                }
 
-               /// <summary>
-               ///   The parent of this namespace, used by the parser to "Pop"
-               ///   the current namespace declaration
-               /// </summary>
-               public Namespace Parent {
-                       get { return parent; }
+               public void VerifyClsCompliance ()
+               {
+                       if (types == null || cls_checked)
+                               return;
+
+                       cls_checked = true;
+
+                       // TODO: This is quite ugly way to check for CLS compliance at namespace level
+
+                       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;
+
+                                       List<TypeSpec> found;
+                                       if (!locase_types.TryGetValue (tm.Name, out found)) {
+                                               found = new List<TypeSpec> ();
+                                               locase_types.Add (tm.Name, found);
+                                       }
+
+                                       found.Add (tm);
+                               }
+                       }
+
+                       foreach (var locase in locase_types.Values) {
+                               if (locase.Count < 2)
+                                       continue;
+
+                               bool all_same = true;
+                               foreach (var notcompliant in locase) {
+                                       all_same = notcompliant.Name == locase[0].Name;
+                                       if (!all_same)
+                                               break;
+                               }
+
+                               if (all_same)
+                                       continue;
+
+                               TypeContainer compiled = null;
+                               foreach (var notcompliant in locase) {
+                                       if (!notcompliant.MemberDefinition.IsImported) {
+                                               if (compiled != null)
+                                                       compiled.Compiler.Report.SymbolRelatedToPreviousError (compiled);
+
+                                               compiled = notcompliant.MemberDefinition as TypeContainer;
+                                       } else {
+                                               compiled.Compiler.Report.SymbolRelatedToPreviousError (notcompliant);
+                                       }
+                               }
+
+                               compiled.Compiler.Report.Warning (3005, 1, compiled.Location,
+                                       "Identifier `{0}' differing only in case is not CLS-compliant", compiled.GetSignatureForError ());
+                       }
                }
        }
 
@@ -789,7 +764,7 @@ namespace Mono.CSharp {
                                }
 
                                if (resolved is TypeExpr)
-                                       resolved = resolved.ResolveAsBaseTerminal (rc, false);
+                                       resolved = resolved.ResolveAsTypeTerminal (rc, false);
 
                                return resolved;
                        }
@@ -1034,11 +1009,11 @@ namespace Mono.CSharp {
                /// 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)
+               public ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
                {
                        List<MethodSpec> candidates = null;
                        foreach (Namespace n in GetUsingTable ()) {
-                               var a = n.LookupExtensionMethod (extensionType, null, name);
+                               var a = n.LookupExtensionMethod (extensionType, null, name, arity);
                                if (a == null)
                                        continue;
 
@@ -1059,7 +1034,7 @@ namespace Mono.CSharp {
                        //
                        Namespace parent_ns = ns.Parent;
                        do {
-                               candidates = parent_ns.LookupExtensionMethod (extensionType, null, name);
+                               candidates = parent_ns.LookupExtensionMethod (extensionType, null, name, arity);
                                if (candidates != null)
                                        return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
 
@@ -1069,23 +1044,24 @@ namespace Mono.CSharp {
                        //
                        // Continue in parent scope
                        //
-                       return parent.LookupExtensionMethod (extensionType, name, loc);
+                       return parent.LookupExtensionMethod (extensionType, name, arity, loc);
                }
 
-               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)
+                               if ((resolved = curr_ns.Lookup (name, arity, loc, ignore_cs0104)) != null)
                                        break;
                        }
+
                        return resolved;
                }
 
-               public ICollection<string> CompletionGetTypesStartingWith (string prefix)
+               public IList<string> CompletionGetTypesStartingWith (string prefix)
                {
-                       var result = new Dictionary<string, string> ();
+                       IEnumerable<string> all = Enumerable.Empty<string> ();
                        
                        for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent){
                                foreach (Namespace using_ns in GetUsingTable ()){
@@ -1094,24 +1070,16 @@ namespace Mono.CSharp {
                                                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)
                {
@@ -1128,17 +1096,17 @@ namespace Mono.CSharp {
                        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.Lookup (Compiler, name, arity, loc);
 
                        //
                        // Check aliases. 
                        //
-                       if (using_aliases != null) {
+                       if (using_aliases != null && arity == 0) {
                                foreach (UsingAliasEntry ue in using_aliases) {
                                        if (ue.Alias == name) {
                                                if (fne != null) {
@@ -1159,8 +1127,10 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       if (fne != null)
-                               return fne;
+                       if (fne != null) {
+                               if (!((fne.Type.Modifiers & Modifiers.INTERNAL) != 0 && !TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, fne.Type.Assembly)))
+                                       return fne;
+                       }
 
                        if (IsImplicit)
                                return null;
@@ -1170,18 +1140,43 @@ 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))
+                               fne = using_ns.Lookup (Compiler, 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 && texpr_match != null) {
+                                       continue;
+                               }
+
+                               if (ignore_cs0104)
+                                       return match;
+
+                               // It can be top level accessibility only
+                               var better = Namespace.IsImportedTypeOverride (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 ()
@@ -1314,18 +1309,22 @@ namespace Mono.CSharp {
                        get { return RootContext.ToplevelTypes.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; }
                }
 
+               public bool HasUnresolvedConstraints {
+                       get { return false; }
+               }
+
                public bool IsObsolete {
                        get { return SlaveDeclSpace.IsObsolete; }
                }