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