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