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