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