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