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