2008-09-15 Miguel de Icaza <miguel@novell.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 // 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                 public bool HasDefinition (string name)
425                 {
426                         return declspaces != null && declspaces [name] != null;
427                 }
428
429                 TypeExpr LookupType (string name, Location loc)
430                 {
431                         if (cached_types.Contains (name))
432                                 return cached_types [name] as TypeExpr;
433
434                         Type t = null;
435                         if (declspaces != null) {
436                                 DeclSpace tdecl = declspaces [name] as DeclSpace;
437                                 if (tdecl != null) {
438                                         //
439                                         // Note that this is not:
440                                         //
441                                         //   t = tdecl.DefineType ()
442                                         //
443                                         // This is to make it somewhat more useful when a DefineType
444                                         // fails due to problems in nested types (more useful in the sense
445                                         // of fewer misleading error messages)
446                                         //
447                                         tdecl.DefineType ();
448                                         t = tdecl.TypeBuilder;
449
450                                         if (RootContext.EvalMode){
451                                                 // Replace the TypeBuilder with a System.Type, as
452                                                 // Reflection.Emit fails otherwise (we end up pretty
453                                                 // much with Random type definitions later on).
454                                                 Type tt = t.Assembly.GetType (t.Name);
455                                                 if (tt != null)
456                                                         t = tt;
457                                         }
458                                 }
459                         }
460                         string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
461                         Type rt = root.LookupTypeReflection (lookup, loc);
462
463                         // HACK: loc.IsNull when the type is core type
464                         if (t == null || (rt != null && loc.IsNull))
465                                 t = rt;
466
467                         TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
468                         cached_types [name] = te;
469                         return te;
470                 }
471
472                 ///
473                 /// Used for better error reporting only
474                 /// 
475                 public Type LookForAnyGenericType (string typeName)
476                 {
477                         if (declspaces == null)
478                                 return null;
479
480                         typeName = SimpleName.RemoveGenericArity (typeName);
481
482                         foreach (DictionaryEntry de in declspaces) {
483                                 string type_item = (string) de.Key;
484                                 int pos = type_item.LastIndexOf ('`');
485                                 if (pos == typeName.Length && String.Compare (typeName, 0, type_item, 0, pos) == 0)
486                                         return ((DeclSpace) de.Value).TypeBuilder;
487                         }
488                         return null;
489                 }
490
491                 public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
492                 {
493                         if (namespaces.Contains (name))
494                                 return (Namespace) namespaces [name];
495
496                         return LookupType (name, loc);
497                 }
498
499                 public void RegisterExternalExtensionMethodClass (Type type)
500                 {
501                         if (external_exmethod_classes == null)
502                                 external_exmethod_classes = new ArrayList ();
503
504                         external_exmethod_classes.Add (type);
505                 }
506
507                 /// 
508                 /// Looks for extension method in this namespace
509                 /// 
510                 public ArrayList LookupExtensionMethod (Type extensionType, ClassOrStruct currentClass, string name)
511                 {
512                         ArrayList found = null;
513
514                         if (declspaces != null) {
515                                 IEnumerator e = declspaces.Values.GetEnumerator ();
516                                 e.Reset ();
517                                 while (e.MoveNext ()) {
518                                         Class c = e.Current as Class;
519                                         if (c == null)
520                                                 continue;
521
522                                         if (!c.IsStaticClass)
523                                                 continue;
524
525                                         ArrayList res = c.MemberCache.FindExtensionMethods (extensionType, name, c != currentClass);
526                                         if (res == null)
527                                                 continue;
528
529                                         if (found == null)
530                                                 found = res;
531                                         else
532                                                 found.AddRange (res);
533                                 }
534                         }
535
536                         if (external_exmethod_classes == null)
537                                 return found;
538
539                         foreach (Type t in external_exmethod_classes) {
540                                 MemberCache m = TypeHandle.GetMemberCache (t);
541                                 ArrayList res = m.FindExtensionMethods (extensionType, name, true);
542                                 if (res == null)
543                                         continue;
544
545                                 if (found == null)
546                                         found = res;
547                                 else
548                                         found.AddRange (res);
549                         }
550
551                         return found;
552                 }
553
554                 public void AddDeclSpace (string name, DeclSpace ds)
555                 {
556                         if (declspaces == null)
557                                 declspaces = new HybridDictionary ();
558                         declspaces.Add (name, ds);
559                 }
560
561                 public void RemoveDeclSpace (string name)
562                 {
563                         declspaces.Remove (name);
564                 }
565                 
566                 /// <summary>
567                 ///   The qualified name of the current namespace
568                 /// </summary>
569                 public string Name {
570                         get { return fullname; }
571                 }
572
573                 /// <summary>
574                 ///   The parent of this namespace, used by the parser to "Pop"
575                 ///   the current namespace declaration
576                 /// </summary>
577                 public Namespace Parent {
578                         get { return parent; }
579                 }
580         }
581
582         //
583         // Namespace container as created by the parser
584         //
585         public class NamespaceEntry : IResolveContext {
586
587                 class UsingEntry {
588                         readonly MemberName name;
589                         Namespace resolved;
590                         
591                         public UsingEntry (MemberName name)
592                         {
593                                 this.name = name;
594                         }
595
596                         public string GetSignatureForError ()
597                         {
598                                 return name.GetSignatureForError ();
599                         }
600
601                         public Location Location {
602                                 get { return name.Location; }
603                         }
604
605                         public MemberName MemberName {
606                                 get { return name; }
607                         }
608                         
609                         public string Name {
610                                 get { return GetSignatureForError (); }
611                         }
612
613                         public Namespace Resolve (IResolveContext rc)
614                         {
615                                 if (resolved != null)
616                                         return resolved;
617
618                                 FullNamedExpression fne = name.GetTypeExpression ().ResolveAsTypeStep (rc, false);
619                                 if (fne == null)
620                                         return null;
621
622                                 resolved = fne as Namespace;
623                                 if (resolved == null) {
624                                         Report.SymbolRelatedToPreviousError (fne.Type);
625                                         Report.Error (138, Location,
626                                                 "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
627                                                 GetSignatureForError ());
628                                 }
629                                 return resolved;
630                         }
631
632                         public override string ToString ()
633                         {
634                                 return Name;
635                         }
636                 }
637
638                 class UsingAliasEntry {
639                         public readonly string Alias;
640                         public Location Location;
641
642                         public UsingAliasEntry (string alias, Location loc)
643                         {
644                                 this.Alias = alias;
645                                 this.Location = loc;
646                         }
647
648                         public virtual FullNamedExpression Resolve (IResolveContext rc)
649                         {
650                                 FullNamedExpression fne = RootNamespace.GetRootNamespace (Alias);
651                                 if (fne == null) {
652                                         Report.Error (430, Location,
653                                                 "The extern alias `{0}' was not specified in -reference option",
654                                                 Alias);
655                                 }
656
657                                 return fne;
658                         }
659
660                         public override string ToString ()
661                         {
662                                 return Alias;
663                         }
664                         
665                 }
666
667                 class LocalUsingAliasEntry : UsingAliasEntry {
668                         Expression resolved;
669                         MemberName value;
670
671                         public LocalUsingAliasEntry (string alias, MemberName name, Location loc)
672                                 : base (alias, loc)
673                         {
674                                 this.value = name;
675                         }
676
677                         public override FullNamedExpression Resolve (IResolveContext rc)
678                         {
679                                 if (resolved != null)
680                                         return (FullNamedExpression)resolved;
681
682                                 resolved = value.GetTypeExpression ().ResolveAsTypeStep (rc, false);
683                                 if (resolved == null)
684                                         return null;
685
686                                 // FIXME: This is quite wrong, the accessibility is not global
687                                 if (resolved.Type != null) {
688                                         TypeAttributes attr = resolved.Type.Attributes & TypeAttributes.VisibilityMask;
689                                         if (attr == TypeAttributes.NestedPrivate || attr == TypeAttributes.NestedFamily ||
690                                                 ((attr == TypeAttributes.NestedFamORAssem || attr == TypeAttributes.NestedAssembly) && 
691                                                 TypeManager.LookupDeclSpace (resolved.Type) == null)) {
692                                                 Expression.ErrorIsInaccesible (resolved.Location, resolved.GetSignatureForError ());
693                                                 return null;
694                                         }
695                                 }
696
697                                 return (FullNamedExpression)resolved;
698                         }
699
700                         public override string ToString ()
701                         {
702                                 return String.Format ("{0} = {1}", Alias, value.GetSignatureForError ());
703                         }
704                 }
705
706                 Namespace ns;
707                 NamespaceEntry parent, implicit_parent;
708                 CompilationUnit file;
709                 int symfile_id;
710
711                 // Namespace using import block
712                 ArrayList using_aliases;
713                 ArrayList using_clauses;
714                 public bool DeclarationFound = false;
715                 // End
716
717                 public readonly bool IsImplicit;
718                 public readonly DeclSpace SlaveDeclSpace;
719                 static readonly Namespace [] empty_namespaces = new Namespace [0];
720                 Namespace [] namespace_using_table;
721
722                 static ArrayList entries = new ArrayList ();
723
724                 public static void Reset ()
725                 {
726                         entries = new ArrayList ();
727                 }
728
729                 public NamespaceEntry (NamespaceEntry parent, CompilationUnit file, string name)
730                 {
731                         this.parent = parent;
732                         this.file = file;
733                         entries.Add (this);
734
735                         if (parent != null)
736                                 ns = parent.NS.GetNamespace (name, true);
737                         else if (name != null)
738                                 ns = RootNamespace.Global.GetNamespace (name, true);
739                         else
740                                 ns = RootNamespace.Global;
741                         SlaveDeclSpace = new RootDeclSpace (this);
742                 }
743
744                 private NamespaceEntry (NamespaceEntry parent, CompilationUnit file, Namespace ns, bool slave)
745                 {
746                         this.parent = parent;
747                         this.file = file;
748                         this.IsImplicit = true;
749                         this.ns = ns;
750                         this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
751                 }
752
753                 //
754                 // Populates the Namespace with some using declarations, used by the
755                 // eval mode. 
756                 //
757                 public void Populate (ArrayList source_using_aliases, ArrayList source_using_clauses)
758                 {
759                         foreach (UsingAliasEntry uae in source_using_aliases){
760                                 if (using_aliases == null)
761                                         using_aliases = new ArrayList ();
762                                 
763                                 using_aliases.Add (uae);
764                         }
765
766                         foreach (UsingEntry ue in source_using_clauses){
767                                 if (using_clauses == null)
768                                         using_clauses = new ArrayList ();
769                                 
770                                 using_clauses.Add (ue);
771                         }
772                 }
773
774                 //
775                 // Extracts the using alises and using clauses into a couple of
776                 // arrays that might already have the same information;  Used by the
777                 // C# Eval mode.
778                 //
779                 public void Extract (ArrayList out_using_aliases, ArrayList out_using_clauses)
780                 {
781                         if (using_aliases != null){
782                                 foreach (UsingAliasEntry uae in using_aliases){
783                                         bool replaced = false;
784                                         
785                                         for (int i = 0; i < out_using_aliases.Count; i++){
786                                                 UsingAliasEntry out_uea = (UsingAliasEntry) out_using_aliases [i];
787                                                 
788                                                 if (out_uea.Alias == uae.Alias){
789                                                         out_using_aliases [i] = uae;
790                                                         replaced = true;
791                                                         break;
792                                                 }
793                                         }
794                                         if (!replaced)
795                                                 out_using_aliases.Add (uae);
796                                 }
797                         }
798
799                         if (using_clauses != null){
800                                 foreach (UsingEntry ue in using_clauses){
801                                         bool found = false;
802                                         
803                                         foreach (UsingEntry out_ue in out_using_clauses)
804                                                 if (out_ue.Name == ue.Name){
805                                                         found = true;
806                                                         break;
807                                                 }
808                                         if (!found)
809                                                 out_using_clauses.Add (ue);
810                                 }
811                         }
812                 }
813                 
814                 //
815                 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
816                 // resolved as if the immediately containing namespace body has no using-directives.
817                 //
818                 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
819                 // in the using-namespace-directive.
820                 //
821                 // To implement these rules, the expressions in the using directives are resolved using 
822                 // the "doppelganger" (ghostly bodiless duplicate).
823                 //
824                 NamespaceEntry doppelganger;
825                 NamespaceEntry Doppelganger {
826                         get {
827                                 if (!IsImplicit && doppelganger == null) {
828                                         doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
829                                         doppelganger.using_aliases = using_aliases;
830                                 }
831                                 return doppelganger;
832                         }
833                 }
834
835                 public Namespace NS {
836                         get { return ns; }
837                 }
838
839                 public NamespaceEntry Parent {
840                         get { return parent; }
841                 }
842
843                 public NamespaceEntry ImplicitParent {
844                         get {
845                                 if (parent == null)
846                                         return null;
847                                 if (implicit_parent == null) {
848                                         implicit_parent = (parent.NS == ns.Parent)
849                                                 ? parent
850                                                 : new NamespaceEntry (parent, file, ns.Parent, false);
851                                 }
852                                 return implicit_parent;
853                         }
854                 }
855
856                 /// <summary>
857                 ///   Records a new namespace for resolving name references
858                 /// </summary>
859                 public void AddUsing (MemberName name, Location loc)
860                 {
861                         if (DeclarationFound){
862                                 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
863                         }
864
865                         if (using_clauses == null) {
866                                 using_clauses = new ArrayList ();
867                         } else {
868                                 foreach (UsingEntry old_entry in using_clauses) {
869                                         if (name.Equals (old_entry.MemberName)) {
870                                                 Report.SymbolRelatedToPreviousError (old_entry.Location, old_entry.GetSignatureForError ());
871                                                 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetSignatureForError ());
872                                                 return;
873                                         }
874                                 }
875                         }
876
877                         using_clauses.Add (new UsingEntry (name));
878                 }
879
880                 public void AddUsingAlias (string alias, MemberName name, Location loc)
881                 {
882                         // TODO: This is parser bussines
883                         if (DeclarationFound){
884                                 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
885                         }
886
887                         if (RootContext.Version != LanguageVersion.ISO_1 && alias == "global")
888                                 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
889                                         " the global namespace will be used instead");
890
891                         AddUsingAlias (new LocalUsingAliasEntry (alias, name, loc));
892                 }
893
894                 public void AddUsingExternalAlias (string alias, Location loc)
895                 {
896                         // TODO: Do this in parser
897                         bool not_first = using_clauses != null || DeclarationFound;
898                         if (using_aliases != null && !not_first) {
899                                 foreach (UsingAliasEntry uae in using_aliases) {
900                                         if (uae is LocalUsingAliasEntry) {
901                                                 not_first = true;
902                                                 break;
903                                         }
904                                 }
905                         }
906
907                         if (not_first)
908                                 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
909
910                         if (alias == "global") {
911                                 Error_GlobalNamespaceRedefined (loc);
912                                 return;
913                         }
914
915                         AddUsingAlias (new UsingAliasEntry (alias, loc));
916                 }
917
918                 void AddUsingAlias (UsingAliasEntry uae)
919                 {
920                         if (using_aliases == null) {
921                                 using_aliases = new ArrayList ();
922                         } else {
923                                 foreach (UsingAliasEntry entry in using_aliases) {
924                                         if (uae.Alias == entry.Alias) {
925                                                 Report.SymbolRelatedToPreviousError (uae.Location, uae.Alias);
926                                                 Report.Error (1537, entry.Location, "The using alias `{0}' appeared previously in this namespace",
927                                                         entry.Alias);
928                                                 return;
929                                         }
930                                 }
931                         }
932
933                         using_aliases.Add (uae);
934                 }
935
936                 ///
937                 /// Does extension methods look up to find a method which matches name and extensionType.
938                 /// Search starts from this namespace and continues hierarchically up to top level.
939                 ///
940                 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, ClassOrStruct currentClass, string name, Location loc)
941                 {
942                         ArrayList candidates = null;
943                         if (currentClass != null) {
944                                 candidates = ns.LookupExtensionMethod (extensionType, currentClass, name);
945                                 if (candidates != null)
946                                         return new ExtensionMethodGroupExpr (candidates, this, extensionType, loc);
947                         }
948
949                         foreach (Namespace n in GetUsingTable ()) {
950                                 ArrayList a = n.LookupExtensionMethod (extensionType, null, name);
951                                 if (a == null)
952                                         continue;
953
954                                 if (candidates == null)
955                                         candidates = a;
956                                 else
957                                         candidates.AddRange (a);
958                         }
959
960                         if (candidates != null)
961                                 return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
962
963                         if (parent == null)
964                                 return null;
965
966                         //
967                         // Inspect parent namespaces in namespace expression
968                         //
969                         Namespace parent_ns = ns.Parent;
970                         do {
971                                 candidates = parent_ns.LookupExtensionMethod (extensionType, null, name);
972                                 if (candidates != null)
973                                         return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
974
975                                 parent_ns = parent_ns.Parent;
976                         } while (parent_ns != null);
977
978                         //
979                         // Continue in parent scope
980                         //
981                         return parent.LookupExtensionMethod (extensionType, currentClass, name, loc);
982                 }
983
984                 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
985                 {
986                         // Precondition: Only simple names (no dots) will be looked up with this function.
987                         FullNamedExpression resolved = null;
988                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
989                                 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
990                                         break;
991                         }
992                         return resolved;
993                 }
994
995                 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
996                 {
997                         Report.SymbolRelatedToPreviousError (t1.Type);
998                         Report.SymbolRelatedToPreviousError (t2.Type);
999                         Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
1000                                 name, t1.GetSignatureForError (), t2.GetSignatureForError ());
1001                 }
1002
1003                 // Looks-up a alias named @name in this and surrounding namespace declarations
1004                 public FullNamedExpression LookupAlias (string name)
1005                 {
1006                         for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
1007                                 if (n.using_aliases == null)
1008                                         continue;
1009
1010                                 foreach (UsingAliasEntry ue in n.using_aliases) {
1011                                         if (ue.Alias == name)
1012                                                 return ue.Resolve (Doppelganger);
1013                                 }
1014                         }
1015
1016                         return null;
1017                 }
1018
1019                 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
1020                 {
1021                         //
1022                         // Check whether it's in the namespace.
1023                         //
1024                         FullNamedExpression fne = ns.Lookup (ds, name, loc);
1025
1026                         //
1027                         // Check aliases. 
1028                         //
1029                         if (using_aliases != null) {
1030                                 foreach (UsingAliasEntry ue in using_aliases) {
1031                                         if (ue.Alias == name) {
1032                                                 if (fne != null) {
1033                                                         if (Doppelganger != null) {
1034                                                                 // TODO: Namespace has broken location
1035                                                                 //Report.SymbolRelatedToPreviousError (fne.Location, null);
1036                                                                 Report.SymbolRelatedToPreviousError (ue.Location, null);
1037                                                                 Report.Error (576, loc,
1038                                                                         "Namespace `{0}' contains a definition with same name as alias `{1}'",
1039                                                                         GetSignatureForError (), name);
1040                                                         } else {
1041                                                                 return fne;
1042                                                         }
1043                                                 }
1044
1045                                                 return ue.Resolve (Doppelganger);
1046                                         }
1047                                 }
1048                         }
1049
1050                         if (fne != null)
1051                                 return fne;
1052
1053                         if (IsImplicit)
1054                                 return null;
1055
1056                         //
1057                         // Check using entries.
1058                         //
1059                         FullNamedExpression match = null;
1060                         foreach (Namespace using_ns in GetUsingTable ()) {
1061                                 match = using_ns.Lookup (ds, name, loc);
1062                                 if (match == null || !(match is TypeExpr))
1063                                         continue;
1064                                 if (fne != null) {
1065                                         if (!ignore_cs0104)
1066                                                 Error_AmbiguousTypeReference (loc, name, fne, match);
1067                                         return null;
1068                                 }
1069                                 fne = match;
1070                         }
1071
1072                         return fne;
1073                 }
1074
1075                 Namespace [] GetUsingTable ()
1076                 {
1077                         if (namespace_using_table != null)
1078                                 return namespace_using_table;
1079
1080                         if (using_clauses == null) {
1081                                 namespace_using_table = empty_namespaces;
1082                                 return namespace_using_table;
1083                         }
1084
1085                         ArrayList list = new ArrayList (using_clauses.Count);
1086
1087                         foreach (UsingEntry ue in using_clauses) {
1088                                 Namespace using_ns = ue.Resolve (Doppelganger);
1089                                 if (using_ns == null)
1090                                         continue;
1091
1092                                 list.Add (using_ns);
1093                         }
1094
1095                         namespace_using_table = (Namespace[])list.ToArray (typeof (Namespace));
1096                         return namespace_using_table;
1097                 }
1098
1099                 static readonly string [] empty_using_list = new string [0];
1100
1101                 public int SymbolFileID {
1102                         get {
1103                                 if (symfile_id == 0 && file.SourceFileEntry != null) {
1104                                         int parent_id = parent == null ? 0 : parent.SymbolFileID;
1105
1106                                         string [] using_list = empty_using_list;
1107                                         if (using_clauses != null) {
1108                                                 using_list = new string [using_clauses.Count];
1109                                                 for (int i = 0; i < using_clauses.Count; i++)
1110                                                         using_list [i] = ((UsingEntry) using_clauses [i]).MemberName.GetTypeName ();
1111                                         }
1112
1113                                         symfile_id = SymbolWriter.DefineNamespace (ns.Name, file.CompileUnitEntry, using_list, parent_id);
1114                                 }
1115                                 return symfile_id;
1116                         }
1117                 }
1118
1119                 static void MsgtryRef (string s)
1120                 {
1121                         Console.WriteLine ("    Try using -r:" + s);
1122                 }
1123
1124                 static void MsgtryPkg (string s)
1125                 {
1126                         Console.WriteLine ("    Try using -pkg:" + s);
1127                 }
1128
1129                 public static void Error_GlobalNamespaceRedefined (Location loc)
1130                 {
1131                         Report.Error (1681, loc, "You cannot redefine the global extern alias");
1132                 }
1133
1134                 public static void Error_NamespaceNotFound (Location loc, string name)
1135                 {
1136                         if (RootContext.EvalMode){
1137                                 // Do not report this, it might be an error on the eval side, and we are lax there.
1138                                 return;
1139                         }
1140                         
1141                         Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
1142                                 name);
1143
1144                         switch (name) {
1145                         case "Gtk": case "GtkSharp":
1146                                 MsgtryPkg ("gtk-sharp");
1147                                 break;
1148
1149                         case "Gdk": case "GdkSharp":
1150                                 MsgtryPkg ("gdk-sharp");
1151                                 break;
1152
1153                         case "Glade": case "GladeSharp":
1154                                 MsgtryPkg ("glade-sharp");
1155                                 break;
1156
1157                         case "System.Drawing":
1158                         case "System.Web.Services":
1159                         case "System.Web":
1160                         case "System.Data":
1161                         case "System.Windows.Forms":
1162                                 MsgtryRef (name);
1163                                 break;
1164                         }
1165                 }
1166
1167                 /// <summary>
1168                 ///   Used to validate that all the using clauses are correct
1169                 ///   after we are finished parsing all the files.  
1170                 /// </summary>
1171                 void VerifyUsing ()
1172                 {
1173                         if (using_aliases != null) {
1174                                 foreach (UsingAliasEntry ue in using_aliases)
1175                                         ue.Resolve (Doppelganger);
1176                         }
1177
1178                         if (using_clauses != null) {
1179                                 foreach (UsingEntry ue in using_clauses)
1180                                         ue.Resolve (Doppelganger);
1181                         }
1182                 }
1183
1184                 /// <summary>
1185                 ///   Used to validate that all the using clauses are correct
1186                 ///   after we are finished parsing all the files.  
1187                 /// </summary>
1188                 static public void VerifyAllUsing ()
1189                 {
1190                         foreach (NamespaceEntry entry in entries)
1191                                 entry.VerifyUsing ();
1192                 }
1193
1194                 public string GetSignatureForError ()
1195                 {
1196                         return ns.GetSignatureForError ();
1197                 }
1198
1199                 public override string ToString ()
1200                 {
1201                         return ns.ToString ();
1202                 }
1203
1204                 #region IResolveContext Members
1205
1206                 public DeclSpace DeclContainer {
1207                         get { return SlaveDeclSpace; }
1208                 }
1209
1210                 public bool IsInObsoleteScope {
1211                         get { return SlaveDeclSpace.IsInObsoleteScope; }
1212                 }
1213
1214                 public bool IsInUnsafeScope {
1215                         get { return SlaveDeclSpace.IsInUnsafeScope; }
1216                 }
1217
1218                 public DeclSpace GenericDeclContainer {
1219                         get { return SlaveDeclSpace; }
1220                 }
1221
1222                 #endregion
1223         }
1224 }