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