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