2008-08-04 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / namespace.cs
1 //
2 // namespace.cs: Tracks namespaces
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Marek Safar (marek.safar@seznam.cz)
7 //
8 // Copyright 2001 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
10 //
11 using System;
12 using System.Collections;
13 using System.Collections.Specialized;
14 using System.Reflection;
15
16 namespace Mono.CSharp {
17
18         public class RootNamespace : Namespace {
19                 //
20                 // Points to Mono's GetNamespaces method, an
21                 // optimization when running on Mono to fetch all the
22                 // namespaces in an assembly
23                 //
24                 static MethodInfo get_namespaces_method;
25
26                 string alias_name;
27                 Assembly referenced_assembly;
28
29                 Hashtable all_namespaces;
30
31                 static Hashtable root_namespaces;
32                 public static GlobalRootNamespace Global;
33                 
34                 static RootNamespace ()
35                 {
36                         get_namespaces_method = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance | BindingFlags.NonPublic);
37
38                         Reset ();
39                 }
40
41                 public static void Reset ()
42                 {
43                         root_namespaces = new Hashtable ();
44                         Global = new GlobalRootNamespace ();
45                         root_namespaces ["global"] = Global;
46                 }
47
48                 protected RootNamespace (string alias_name, Assembly assembly)
49                         : base (null, String.Empty)
50                 {
51                         this.alias_name = alias_name;
52                         referenced_assembly = assembly;
53
54                         all_namespaces = new Hashtable ();
55                         all_namespaces.Add ("", this);
56
57                         if (referenced_assembly != null)
58                                 ComputeNamespaces (this.referenced_assembly);
59                 }
60
61                 public static void DefineRootNamespace (string name, Assembly assembly)
62                 {
63                         if (name == "global") {
64                                 NamespaceEntry.Error_GlobalNamespaceRedefined (Location.Null);
65                                 return;
66                         }
67                         RootNamespace retval = GetRootNamespace (name);
68                         if (retval == null || retval.referenced_assembly != assembly)
69                                 root_namespaces [name] = new RootNamespace (name, assembly);
70                 }
71
72                 public static RootNamespace GetRootNamespace (string name)
73                 {
74                         return (RootNamespace) root_namespaces [name];
75                 }
76
77                 public virtual Type LookupTypeReflection (string name, Location loc)
78                 {
79                         return GetTypeInAssembly (referenced_assembly, name);
80                 }
81
82                 public void RegisterNamespace (Namespace child)
83                 {
84                         if (child != this)
85                                 all_namespaces.Add (child.Name, child);
86                 }
87
88                 public bool IsNamespace (string name)
89                 {
90                         return all_namespaces.Contains (name);
91                 }
92
93                 protected void RegisterNamespace (string dotted_name)
94                 {
95                         if (dotted_name != null && dotted_name.Length != 0 && ! IsNamespace (dotted_name))
96                                 GetNamespace (dotted_name, true);
97                 }
98
99                 void RegisterExtensionMethodClass (Type t)
100                 {
101                         string n = t.Namespace;
102                         Namespace ns = n == null ? Global : (Namespace)all_namespaces [n];
103                         if (ns == null)
104                                 ns = GetNamespace (n, true);
105  
106                         ns.RegisterExternalExtensionMethodClass (t);
107                 }
108
109                 protected void ComputeNamespaces (Assembly assembly)
110                 {
111                         // How to test whether attribute exists without loading the assembly :-(
112 #if NET_2_1
113                         const string SystemCore = "System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"; 
114 #else
115                         const string SystemCore = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; 
116 #endif
117                         if (TypeManager.extension_attribute_type == null &&
118                                 assembly.FullName == SystemCore) {
119                                 TypeManager.extension_attribute_type = assembly.GetType("System.Runtime.CompilerServices.ExtensionAttribute");
120                         }
121  
122                         bool contains_extension_methods = TypeManager.extension_attribute_type != null &&
123                                         assembly.IsDefined(TypeManager.extension_attribute_type, false);
124  
125                         if (get_namespaces_method != null && !contains_extension_methods) {
126                                 string [] namespaces = (string []) get_namespaces_method.Invoke (assembly, null);
127                                 foreach (string ns in namespaces)
128                                         RegisterNamespace (ns);
129                                 return;
130                         }
131   
132                         foreach (Type t in assembly.GetExportedTypes ()) {
133                                 if ((t.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute &&
134                                         contains_extension_methods && t.IsDefined (TypeManager.extension_attribute_type, false))
135                                         RegisterExtensionMethodClass (t);
136                                 else
137                                         RegisterNamespace (t.Namespace);
138                         }
139                 }
140
141                 protected static Type GetTypeInAssembly (Assembly assembly, string name)
142                 {
143                         Type t = assembly.GetType (name);
144                         if (t == null)
145                                 return null;
146
147                         if (t.IsPointer)
148                                 throw new InternalErrorException ("Use GetPointerType() to get a pointer");
149
150                         TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
151                         if (ta == TypeAttributes.NestedPrivate)
152                                 return null;
153
154                         if ((ta == TypeAttributes.NotPublic ||
155                              ta == TypeAttributes.NestedAssembly ||
156                              ta == TypeAttributes.NestedFamANDAssem) &&
157                             !TypeManager.IsThisOrFriendAssembly (t.Assembly))
158                                 return null;
159
160                         return t;
161                 }
162
163                 public override string ToString ()
164                 {
165                         return String.Format ("RootNamespace ({0}::)", alias_name);
166                 }
167
168                 public override string GetSignatureForError ()
169                 {
170                         return alias_name + "::";
171                 }
172         }
173
174         public class GlobalRootNamespace : RootNamespace {
175                 Assembly [] assemblies;
176                 Module [] modules;
177
178                 public GlobalRootNamespace ()
179                         : base ("global", null)
180                 {
181                         assemblies = new Assembly [0];
182                 }
183
184                 public Assembly [] Assemblies {
185                         get { return assemblies; }
186                 }
187
188                 public Module [] Modules {
189                         get { return modules; }
190                 }
191
192                 public void AddAssemblyReference (Assembly a)
193                 {
194                         foreach (Assembly assembly in assemblies) {
195                                 if (a == assembly)
196                                         return;
197                         }
198
199                         int top = assemblies.Length;
200                         Assembly [] n = new Assembly [top + 1];
201                         assemblies.CopyTo (n, 0);
202                         n [top] = a;
203                         assemblies = n;
204
205                         ComputeNamespaces (a);
206                 }
207
208                 public void AddModuleReference (Module m)
209                 {
210                         int top = modules != null ? modules.Length : 0;
211                         Module [] n = new Module [top + 1];
212                         if (modules != null)
213                                 modules.CopyTo (n, 0);
214                         n [top] = m;
215                         modules = n;
216
217                         if (m == CodeGen.Module.Builder)
218                                 return;
219
220                         foreach (Type t in m.GetTypes ())
221                                 RegisterNamespace (t.Namespace);
222                 }
223
224                 public override void Error_NamespaceDoesNotExist(DeclSpace ds, Location loc, string name)
225                 {
226                         Report.Error (400, loc, "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
227                                 name);
228                 }
229
230                 public override Type LookupTypeReflection (string name, Location loc)
231                 {
232                         Type found_type = null;
233                 
234                         foreach (Assembly a in assemblies) {
235                                 Type t = GetTypeInAssembly (a, name);
236                                 if (t == null)
237                                         continue;
238                                         
239                                 if (found_type == null) {
240                                         found_type = t;
241                                         continue;
242                                 }
243
244                                 Report.SymbolRelatedToPreviousError (found_type);
245                                 Report.SymbolRelatedToPreviousError (t);
246                                 Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
247                                         
248                                 return found_type;
249                         }
250
251                         if (modules != null) {
252                                 foreach (Module module in modules) {
253                                         Type t = module.GetType (name);
254                                         if (t == null)
255                                                 continue;
256
257                                         if (found_type == null) {
258                                                 found_type = t;
259                                                 continue;
260                                         }
261
262                                         Report.SymbolRelatedToPreviousError (found_type);
263                                         if (loc.IsNull) {
264                                                 DeclSpace ds = TypeManager.LookupDeclSpace (t);
265                                                 Report.Warning (1685, 1, ds.Location, "The type `{0}' conflicts with the predefined type `{1}' and will be ignored",
266                                                         ds.GetSignatureForError (), TypeManager.CSharpName (found_type));
267                                                 return found_type;
268                                         }
269                                         Report.SymbolRelatedToPreviousError (t);
270                                         Report.Warning (436, 2, loc, "The type `{0}' conflicts with the imported type `{1}'. Ignoring the imported type definition",
271                                                 TypeManager.CSharpName (t), TypeManager.CSharpName (found_type));
272                                         return t;
273                                 }
274                         }
275
276                         return found_type;
277                 }
278         }
279
280         /// <summary>
281         ///   Keeps track of the namespaces defined in the C# code.
282         ///
283         ///   This is an Expression to allow it to be referenced in the
284         ///   compiler parse/intermediate tree during name resolution.
285         /// </summary>
286         public class Namespace : FullNamedExpression {
287                 
288                 Namespace parent;
289                 string fullname;
290                 IDictionary namespaces;
291                 IDictionary declspaces;
292                 Hashtable cached_types;
293                 RootNamespace root;
294                 ArrayList external_exmethod_classes;
295
296                 public readonly MemberName MemberName;
297
298                 /// <summary>
299                 ///   Constructor Takes the current namespace and the
300                 ///   name.  This is bootstrapped with parent == null
301                 ///   and name = ""
302                 /// </summary>
303                 public Namespace (Namespace parent, string name)
304                 {
305                         // Expression members.
306                         this.eclass = ExprClass.Namespace;
307                         this.Type = typeof (Namespace);
308                         this.loc = Location.Null;
309
310                         this.parent = parent;
311
312                         if (parent != null)
313                                 this.root = parent.root;
314                         else
315                                 this.root = this as RootNamespace;
316
317                         if (this.root == null)
318                                 throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
319                         
320                         string pname = parent != null ? parent.fullname : "";
321                                 
322                         if (pname == "")
323                                 fullname = name;
324                         else
325                                 fullname = parent.fullname + "." + name;
326
327                         if (fullname == null)
328                                 throw new InternalErrorException ("Namespace has a null fullname");
329
330                         if (parent != null && parent.MemberName != MemberName.Null)
331                                 MemberName = new MemberName (parent.MemberName, name);
332                         else if (name.Length == 0)
333                                 MemberName = MemberName.Null;
334                         else
335                                 MemberName = new MemberName (name);
336
337                         namespaces = new HybridDictionary ();
338                         cached_types = new Hashtable ();
339
340                         root.RegisterNamespace (this);
341                 }
342
343                 public override Expression DoResolve (EmitContext ec)
344                 {
345                         return this;
346                 }
347
348                 public virtual void Error_NamespaceDoesNotExist (DeclSpace ds, Location loc, string name)
349                 {
350                         if (name.IndexOf ('`') > 0) {
351                                 FullNamedExpression retval = Lookup (ds, SimpleName.RemoveGenericArity (name), loc);
352                                 if (retval != null) {
353                                         Error_TypeArgumentsCannotBeUsed (retval.Type, loc);
354                                         return;
355                                 }
356                         } else {
357                                 Type t = LookForAnyGenericType (name);
358                                 if (t != null) {
359                                         Error_InvalidNumberOfTypeArguments (t, loc);
360                                         return;
361                                 }
362                         }
363
364                         Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
365                                 name, GetSignatureForError ());
366                 }
367
368                 public static void Error_InvalidNumberOfTypeArguments (Type t, Location loc)
369                 {
370                         Report.SymbolRelatedToPreviousError (t);
371                         Report.Error (305, loc, "Using the generic type `{0}' requires `{1}' type argument(s)",
372                                 TypeManager.CSharpName(t), TypeManager.GetNumberOfTypeArguments(t).ToString());
373                 }
374
375                 public static void Error_TypeArgumentsCannotBeUsed (Type t, Location loc)
376                 {
377                         Report.SymbolRelatedToPreviousError (t);
378                         Error_TypeArgumentsCannotBeUsed (loc, "type", TypeManager.CSharpName (t));
379                 }
380
381                 public static void Error_TypeArgumentsCannotBeUsed (MethodBase mi, Location loc)
382                 {
383                         Report.SymbolRelatedToPreviousError (mi);
384                         Error_TypeArgumentsCannotBeUsed (loc, "method", TypeManager.CSharpSignature (mi));
385                 }
386
387                 static void Error_TypeArgumentsCannotBeUsed (Location loc, string type, string name)
388                 {
389                         Report.Error(308, loc, "The non-generic {0} `{1}' cannot be used with the type arguments",
390                                 type, name);
391                 }
392
393                 public override string GetSignatureForError ()
394                 {
395                         return fullname;
396                 }
397                 
398                 public Namespace GetNamespace (string name, bool create)
399                 {
400                         int pos = name.IndexOf ('.');
401
402                         Namespace ns;
403                         string first;
404                         if (pos >= 0)
405                                 first = name.Substring (0, pos);
406                         else
407                                 first = name;
408
409                         ns = (Namespace) namespaces [first];
410                         if (ns == null) {
411                                 if (!create)
412                                         return null;
413
414                                 ns = new Namespace (this, first);
415                                 namespaces.Add (first, ns);
416                         }
417
418                         if (pos >= 0)
419                                 ns = ns.GetNamespace (name.Substring (pos + 1), create);
420
421                         return ns;
422                 }
423
424                 TypeExpr LookupType (string name, Location loc)
425                 {
426                         if (cached_types.Contains (name))
427                                 return cached_types [name] as TypeExpr;
428
429                         Type t = null;
430                         if (declspaces != null) {
431                                 DeclSpace tdecl = declspaces [name] as DeclSpace;
432                                 if (tdecl != null) {
433                                         //
434                                         // Note that this is not:
435                                         //
436                                         //   t = tdecl.DefineType ()
437                                         //
438                                         // This is to make it somewhat more useful when a DefineType
439                                         // fails due to problems in nested types (more useful in the sense
440                                         // of fewer misleading error messages)
441                                         //
442                                         tdecl.DefineType ();
443                                         t = tdecl.TypeBuilder;
444                                 }
445                         }
446                         string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
447                         Type rt = root.LookupTypeReflection (lookup, loc);
448
449                         // HACK: loc.IsNull when the type is core type
450                         if (t == null || (rt != null && loc.IsNull))
451                                 t = rt;
452
453                         TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
454                         cached_types [name] = te;
455                         return te;
456                 }
457
458                 ///
459                 /// Used for better error reporting only
460                 /// 
461                 public Type LookForAnyGenericType (string typeName)
462                 {
463                         if (declspaces == null)
464                                 return null;
465
466                         typeName = SimpleName.RemoveGenericArity (typeName);
467
468                         foreach (DictionaryEntry de in declspaces) {
469                                 string type_item = (string) de.Key;
470                                 int pos = type_item.LastIndexOf ('`');
471                                 if (pos == typeName.Length && String.Compare (typeName, 0, type_item, 0, pos) == 0)
472                                         return ((DeclSpace) de.Value).TypeBuilder;
473                         }
474                         return null;
475                 }
476
477                 public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
478                 {
479                         if (namespaces.Contains (name))
480                                 return (Namespace) namespaces [name];
481
482                         return LookupType (name, loc);
483                 }
484
485                 public void RegisterExternalExtensionMethodClass (Type type)
486                 {
487                         if (external_exmethod_classes == null)
488                                 external_exmethod_classes = new ArrayList ();
489
490                         external_exmethod_classes.Add (type);
491                 }
492
493                 /// 
494                 /// Looks for extension method in this namespace
495                 /// 
496                 public ArrayList LookupExtensionMethod (Type extensionType, ClassOrStruct currentClass, string name)
497                 {
498                         ArrayList found = null;
499
500                         if (declspaces != null) {
501                                 IEnumerator e = declspaces.Values.GetEnumerator ();
502                                 e.Reset ();
503                                 while (e.MoveNext ()) {
504                                         Class c = e.Current as Class;
505                                         if (c == null)
506                                                 continue;
507
508                                         if (!c.IsStaticClass)
509                                                 continue;
510
511                                         ArrayList res = c.MemberCache.FindExtensionMethods (extensionType, name, c != currentClass);
512                                         if (res == null)
513                                                 continue;
514
515                                         if (found == null)
516                                                 found = res;
517                                         else
518                                                 found.AddRange (res);
519                                 }
520                         }
521
522                         if (external_exmethod_classes == null)
523                                 return found;
524
525                         foreach (Type t in external_exmethod_classes) {
526                                 MemberCache m = TypeHandle.GetMemberCache (t);
527                                 ArrayList res = m.FindExtensionMethods (extensionType, name, true);
528                                 if (res == null)
529                                         continue;
530
531                                 if (found == null)
532                                         found = res;
533                                 else
534                                         found.AddRange (res);
535                         }
536
537                         return found;
538                 }
539
540                 public void AddDeclSpace (string name, DeclSpace ds)
541                 {
542                         if (declspaces == null)
543                                 declspaces = new HybridDictionary ();
544                         declspaces.Add (name, ds);
545                 }
546
547                 /// <summary>
548                 ///   The qualified name of the current namespace
549                 /// </summary>
550                 public string Name {
551                         get { return fullname; }
552                 }
553
554                 /// <summary>
555                 ///   The parent of this namespace, used by the parser to "Pop"
556                 ///   the current namespace declaration
557                 /// </summary>
558                 public Namespace Parent {
559                         get { return parent; }
560                 }
561         }
562
563         //
564         // Namespace container as created by the parser
565         //
566         public class NamespaceEntry : IResolveContext {
567
568                 class UsingEntry {
569                         readonly MemberName name;
570                         Namespace resolved;
571                         
572                         public UsingEntry (MemberName name)
573                         {
574                                 this.name = name;
575                         }
576
577                         public string GetSignatureForError ()
578                         {
579                                 return name.GetSignatureForError ();
580                         }
581
582                         public Location Location {
583                                 get { return name.Location; }
584                         }
585
586                         public MemberName MemberName {
587                                 get { return name; }
588                         }
589                         
590                         public string Name {
591                                 get { return GetSignatureForError (); }
592                         }
593
594                         public Namespace Resolve (IResolveContext rc)
595                         {
596                                 if (resolved != null)
597                                         return resolved;
598
599                                 FullNamedExpression fne = name.GetTypeExpression ().ResolveAsTypeStep (rc, false);
600                                 if (fne == null)
601                                         return null;
602
603                                 resolved = fne as Namespace;
604                                 if (resolved == null) {
605                                         Report.SymbolRelatedToPreviousError (fne.Type);
606                                         Report.Error (138, Location,
607                                                 "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
608                                                 GetSignatureForError ());
609                                 }
610                                 return resolved;
611                         }
612                 }
613
614                 class UsingAliasEntry {
615                         public readonly string Alias;
616                         public Location Location;
617
618                         public UsingAliasEntry (string alias, Location loc)
619                         {
620                                 this.Alias = alias;
621                                 this.Location = loc;
622                         }
623
624                         public virtual FullNamedExpression Resolve (IResolveContext rc)
625                         {
626                                 FullNamedExpression fne = RootNamespace.GetRootNamespace (Alias);
627                                 if (fne == null) {
628                                         Report.Error (430, Location,
629                                                 "The extern alias `{0}' was not specified in -reference option",
630                                                 Alias);
631                                 }
632
633                                 return fne;
634                         }
635                 }
636
637                 class LocalUsingAliasEntry : UsingAliasEntry {
638                         Expression resolved;
639                         MemberName value;
640
641                         public LocalUsingAliasEntry (string alias, MemberName name, Location loc)
642                                 : base (alias, loc)
643                         {
644                                 this.value = name;
645                         }
646
647                         public override FullNamedExpression Resolve (IResolveContext rc)
648                         {
649                                 if (resolved != null)
650                                         return (FullNamedExpression)resolved;
651
652                                 resolved = value.GetTypeExpression ().ResolveAsTypeStep (rc, false);
653                                 if (resolved == null)
654                                         return null;
655
656                                 // FIXME: This is quite wrong, the accessibility is not global
657                                 if (resolved.Type != null) {
658                                         TypeAttributes attr = resolved.Type.Attributes & TypeAttributes.VisibilityMask;
659                                         if (attr == TypeAttributes.NestedPrivate || attr == TypeAttributes.NestedFamily ||
660                                                 ((attr == TypeAttributes.NestedFamORAssem || attr == TypeAttributes.NestedAssembly) && 
661                                                 TypeManager.LookupDeclSpace (resolved.Type) == null)) {
662                                                 Expression.ErrorIsInaccesible (resolved.Location, resolved.GetSignatureForError ());
663                                                 return null;
664                                         }
665                                 }
666
667                                 return (FullNamedExpression)resolved;
668                         }
669                 }
670
671                 Namespace ns;
672                 NamespaceEntry parent, implicit_parent;
673                 CompilationUnit file;
674                 int symfile_id;
675
676                 // Namespace using import block
677                 ArrayList using_aliases;
678                 ArrayList using_clauses;
679                 public bool DeclarationFound = false;
680                 // End
681
682                 public readonly bool IsImplicit;
683                 public readonly DeclSpace SlaveDeclSpace;
684                 static readonly Namespace [] empty_namespaces = new Namespace [0];
685                 Namespace [] namespace_using_table;
686
687                 static ArrayList entries = new ArrayList ();
688
689                 public static void Reset ()
690                 {
691                         entries = new ArrayList ();
692                 }
693
694                 public NamespaceEntry (NamespaceEntry parent, CompilationUnit file, string name)
695                 {
696                         this.parent = parent;
697                         this.file = file;
698                         entries.Add (this);
699
700                         if (parent != null)
701                                 ns = parent.NS.GetNamespace (name, true);
702                         else if (name != null)
703                                 ns = RootNamespace.Global.GetNamespace (name, true);
704                         else
705                                 ns = RootNamespace.Global;
706                         SlaveDeclSpace = new RootDeclSpace (this);
707                 }
708
709                 private NamespaceEntry (NamespaceEntry parent, CompilationUnit file, Namespace ns, bool slave)
710                 {
711                         this.parent = parent;
712                         this.file = file;
713                         this.IsImplicit = true;
714                         this.ns = ns;
715                         this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
716                 }
717
718                 //
719                 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
720                 // resolved as if the immediately containing namespace body has no using-directives.
721                 //
722                 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
723                 // in the using-namespace-directive.
724                 //
725                 // To implement these rules, the expressions in the using directives are resolved using 
726                 // the "doppelganger" (ghostly bodiless duplicate).
727                 //
728                 NamespaceEntry doppelganger;
729                 NamespaceEntry Doppelganger {
730                         get {
731                                 if (!IsImplicit && doppelganger == null) {
732                                         doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
733                                         doppelganger.using_aliases = using_aliases;
734                                 }
735                                 return doppelganger;
736                         }
737                 }
738
739                 public Namespace NS {
740                         get { return ns; }
741                 }
742
743                 public NamespaceEntry Parent {
744                         get { return parent; }
745                 }
746
747                 public NamespaceEntry ImplicitParent {
748                         get {
749                                 if (parent == null)
750                                         return null;
751                                 if (implicit_parent == null) {
752                                         implicit_parent = (parent.NS == ns.Parent)
753                                                 ? parent
754                                                 : new NamespaceEntry (parent, file, ns.Parent, false);
755                                 }
756                                 return implicit_parent;
757                         }
758                 }
759
760                 /// <summary>
761                 ///   Records a new namespace for resolving name references
762                 /// </summary>
763                 public void AddUsing (MemberName name, Location loc)
764                 {
765                         if (DeclarationFound){
766                                 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
767                         }
768
769                         if (using_clauses == null) {
770                                 using_clauses = new ArrayList ();
771                         } else {
772                                 foreach (UsingEntry old_entry in using_clauses) {
773                                         if (name.Equals (old_entry.MemberName)) {
774                                                 Report.SymbolRelatedToPreviousError (old_entry.Location, old_entry.GetSignatureForError ());
775                                                 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetSignatureForError ());
776                                                 return;
777                                         }
778                                 }
779                         }
780
781                         using_clauses.Add (new UsingEntry (name));
782                 }
783
784                 public void AddUsingAlias (string alias, MemberName name, Location loc)
785                 {
786                         // TODO: This is parser bussines
787                         if (DeclarationFound){
788                                 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
789                         }
790
791                         if (RootContext.Version != LanguageVersion.ISO_1 && alias == "global")
792                                 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
793                                         " the global namespace will be used instead");
794
795                         AddUsingAlias (new LocalUsingAliasEntry (alias, name, loc));
796                 }
797
798                 public void AddUsingExternalAlias (string alias, Location loc)
799                 {
800                         // TODO: Do this in parser
801                         bool not_first = using_clauses != null || DeclarationFound;
802                         if (using_aliases != null && !not_first) {
803                                 foreach (UsingAliasEntry uae in using_aliases) {
804                                         if (uae is LocalUsingAliasEntry) {
805                                                 not_first = true;
806                                                 break;
807                                         }
808                                 }
809                         }
810
811                         if (not_first)
812                                 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
813
814                         if (alias == "global") {
815                                 Error_GlobalNamespaceRedefined (loc);
816                                 return;
817                         }
818
819                         AddUsingAlias (new UsingAliasEntry (alias, loc));
820                 }
821
822                 void AddUsingAlias (UsingAliasEntry uae)
823                 {
824                         if (using_aliases == null) {
825                                 using_aliases = new ArrayList ();
826                         } else {
827                                 foreach (UsingAliasEntry entry in using_aliases) {
828                                         if (uae.Alias == entry.Alias) {
829                                                 Report.SymbolRelatedToPreviousError (uae.Location, uae.Alias);
830                                                 Report.Error (1537, entry.Location, "The using alias `{0}' appeared previously in this namespace",
831                                                         entry.Alias);
832                                                 return;
833                                         }
834                                 }
835                         }
836
837                         using_aliases.Add (uae);
838                 }
839
840                 ///
841                 /// Does extension methods look up to find a method which matches name and extensionType.
842                 /// Search starts from this namespace and continues hierarchically up to top level.
843                 ///
844                 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, ClassOrStruct currentClass, string name, Location loc)
845                 {
846                         ArrayList candidates = null;
847                         if (currentClass != null) {
848                                 candidates = ns.LookupExtensionMethod (extensionType, currentClass, name);
849                                 if (candidates != null)
850                                         return new ExtensionMethodGroupExpr (candidates, this, extensionType, loc);
851                         }
852
853                         foreach (Namespace n in GetUsingTable ()) {
854                                 ArrayList a = n.LookupExtensionMethod (extensionType, null, name);
855                                 if (a == null)
856                                         continue;
857
858                                 if (candidates == null)
859                                         candidates = a;
860                                 else
861                                         candidates.AddRange (a);
862                         }
863
864                         if (candidates != null)
865                                 return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
866
867                         if (parent == null)
868                                 return null;
869
870                         //
871                         // Inspect parent namespaces in namespace expression
872                         //
873                         Namespace parent_ns = ns.Parent;
874                         do {
875                                 candidates = parent_ns.LookupExtensionMethod (extensionType, null, name);
876                                 if (candidates != null)
877                                         return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
878
879                                 parent_ns = parent_ns.Parent;
880                         } while (parent_ns != null);
881
882                         //
883                         // Continue in parent scope
884                         //
885                         return parent.LookupExtensionMethod (extensionType, currentClass, name, loc);
886                 }
887
888                 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
889                 {
890                         // Precondition: Only simple names (no dots) will be looked up with this function.
891                         FullNamedExpression resolved = null;
892                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
893                                 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
894                                         break;
895                         }
896                         return resolved;
897                 }
898
899                 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
900                 {
901                         Report.SymbolRelatedToPreviousError (t1.Type);
902                         Report.SymbolRelatedToPreviousError (t2.Type);
903                         Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
904                                 name, t1.GetSignatureForError (), t2.GetSignatureForError ());
905                 }
906
907                 // Looks-up a alias named @name in this and surrounding namespace declarations
908                 public FullNamedExpression LookupAlias (string name)
909                 {
910                         for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
911                                 if (n.using_aliases == null)
912                                         continue;
913
914                                 foreach (UsingAliasEntry ue in n.using_aliases) {
915                                         if (ue.Alias == name)
916                                                 return ue.Resolve (Doppelganger);
917                                 }
918                         }
919
920                         return null;
921                 }
922
923                 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
924                 {
925                         //
926                         // Check whether it's in the namespace.
927                         //
928                         FullNamedExpression fne = ns.Lookup (ds, name, loc);
929
930                         //
931                         // Check aliases. 
932                         //
933                         if (using_aliases != null) {
934                                 foreach (UsingAliasEntry ue in using_aliases) {
935                                         if (ue.Alias == name) {
936                                                 if (fne != null) {
937                                                         if (Doppelganger != null) {
938                                                                 // TODO: Namespace has broken location
939                                                                 //Report.SymbolRelatedToPreviousError (fne.Location, null);
940                                                                 Report.SymbolRelatedToPreviousError (ue.Location, null);
941                                                                 Report.Error (576, loc,
942                                                                         "Namespace `{0}' contains a definition with same name as alias `{1}'",
943                                                                         GetSignatureForError (), name);
944                                                         } else {
945                                                                 return fne;
946                                                         }
947                                                 }
948
949                                                 return ue.Resolve (Doppelganger);
950                                         }
951                                 }
952                         }
953
954                         if (fne != null)
955                                 return fne;
956
957                         if (IsImplicit)
958                                 return null;
959
960                         //
961                         // Check using entries.
962                         //
963                         FullNamedExpression match = null;
964                         foreach (Namespace using_ns in GetUsingTable ()) {
965                                 match = using_ns.Lookup (ds, name, loc);
966                                 if (match == null || !(match is TypeExpr))
967                                         continue;
968                                 if (fne != null) {
969                                         if (!ignore_cs0104)
970                                                 Error_AmbiguousTypeReference (loc, name, fne, match);
971                                         return null;
972                                 }
973                                 fne = match;
974                         }
975
976                         return fne;
977                 }
978
979                 Namespace [] GetUsingTable ()
980                 {
981                         if (namespace_using_table != null)
982                                 return namespace_using_table;
983
984                         if (using_clauses == null) {
985                                 namespace_using_table = empty_namespaces;
986                                 return namespace_using_table;
987                         }
988
989                         ArrayList list = new ArrayList (using_clauses.Count);
990
991                         foreach (UsingEntry ue in using_clauses) {
992                                 Namespace using_ns = ue.Resolve (Doppelganger);
993                                 if (using_ns == null)
994                                         continue;
995
996                                 list.Add (using_ns);
997                         }
998
999                         namespace_using_table = (Namespace[])list.ToArray (typeof (Namespace));
1000                         return namespace_using_table;
1001                 }
1002
1003                 static readonly string [] empty_using_list = new string [0];
1004
1005                 public int SymbolFileID {
1006                         get {
1007                                 if (symfile_id == 0 && file.SourceFileEntry != null) {
1008                                         int parent_id = parent == null ? 0 : parent.SymbolFileID;
1009
1010                                         string [] using_list = empty_using_list;
1011                                         if (using_clauses != null) {
1012                                                 using_list = new string [using_clauses.Count];
1013                                                 for (int i = 0; i < using_clauses.Count; i++)
1014                                                         using_list [i] = ((UsingEntry) using_clauses [i]).MemberName.GetTypeName ();
1015                                         }
1016
1017                                         symfile_id = SymbolWriter.DefineNamespace (ns.Name, file.CompileUnitEntry, using_list, parent_id);
1018                                 }
1019                                 return symfile_id;
1020                         }
1021                 }
1022
1023                 static void MsgtryRef (string s)
1024                 {
1025                         Console.WriteLine ("    Try using -r:" + s);
1026                 }
1027
1028                 static void MsgtryPkg (string s)
1029                 {
1030                         Console.WriteLine ("    Try using -pkg:" + s);
1031                 }
1032
1033                 public static void Error_GlobalNamespaceRedefined (Location loc)
1034                 {
1035                         Report.Error (1681, loc, "You cannot redefine the global extern alias");
1036                 }
1037
1038                 public static void Error_NamespaceNotFound (Location loc, string name)
1039                 {
1040                         Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
1041                                 name);
1042
1043                         switch (name) {
1044                         case "Gtk": case "GtkSharp":
1045                                 MsgtryPkg ("gtk-sharp");
1046                                 break;
1047
1048                         case "Gdk": case "GdkSharp":
1049                                 MsgtryPkg ("gdk-sharp");
1050                                 break;
1051
1052                         case "Glade": case "GladeSharp":
1053                                 MsgtryPkg ("glade-sharp");
1054                                 break;
1055
1056                         case "System.Drawing":
1057                         case "System.Web.Services":
1058                         case "System.Web":
1059                         case "System.Data":
1060                         case "System.Windows.Forms":
1061                                 MsgtryRef (name);
1062                                 break;
1063                         }
1064                 }
1065
1066                 /// <summary>
1067                 ///   Used to validate that all the using clauses are correct
1068                 ///   after we are finished parsing all the files.  
1069                 /// </summary>
1070                 void VerifyUsing ()
1071                 {
1072                         if (using_aliases != null) {
1073                                 foreach (UsingAliasEntry ue in using_aliases)
1074                                         ue.Resolve (Doppelganger);
1075                         }
1076
1077                         if (using_clauses != null) {
1078                                 foreach (UsingEntry ue in using_clauses)
1079                                         ue.Resolve (Doppelganger);
1080                         }
1081                 }
1082
1083                 /// <summary>
1084                 ///   Used to validate that all the using clauses are correct
1085                 ///   after we are finished parsing all the files.  
1086                 /// </summary>
1087                 static public void VerifyAllUsing ()
1088                 {
1089                         foreach (NamespaceEntry entry in entries)
1090                                 entry.VerifyUsing ();
1091                 }
1092
1093                 public string GetSignatureForError ()
1094                 {
1095                         return ns.GetSignatureForError ();
1096                 }
1097
1098                 public override string ToString ()
1099                 {
1100                         return ns.ToString ();
1101                 }
1102
1103                 #region IResolveContext Members
1104
1105                 public DeclSpace DeclContainer {
1106                         get { return SlaveDeclSpace; }
1107                 }
1108
1109                 public bool IsInObsoleteScope {
1110                         get { return SlaveDeclSpace.IsInObsoleteScope; }
1111                 }
1112
1113                 public bool IsInUnsafeScope {
1114                         get { return SlaveDeclSpace.IsInUnsafeScope; }
1115                 }
1116
1117                 public DeclSpace GenericDeclContainer {
1118                         get { return SlaveDeclSpace; }
1119                 }
1120
1121                 #endregion
1122         }
1123 }