2008-11-18 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         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                         // How to test whether attribute exists without loading the assembly :-(
66 #if NET_2_1
67                         const string SystemCore = "System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"; 
68 #else
69                         const string SystemCore = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; 
70 #endif
71                         if (TypeManager.extension_attribute_type == null &&
72                                 a.FullName == SystemCore) {
73                                 TypeManager.extension_attribute_type = a.GetType("System.Runtime.CompilerServices.ExtensionAttribute");
74                         }
75
76                         int top = referenced_assemblies.Length;
77                         Assembly [] n = new Assembly [top + 1];
78                         referenced_assemblies.CopyTo (n, 0);
79                         n [top] = a;
80                         referenced_assemblies = n;
81                 }
82
83                 public static void DefineRootNamespace (string alias, Assembly assembly)
84                 {
85                         if (alias == "global") {
86                                 NamespaceEntry.Error_GlobalNamespaceRedefined (Location.Null);
87                                 return;
88                         }
89
90                         RootNamespace retval = GetRootNamespace (alias);
91                         if (retval == null) {
92                                 retval = new RootNamespace (alias);
93                                 root_namespaces.Add (alias, retval);
94                         }
95
96                         retval.AddAssemblyReference (assembly);
97                 }
98
99                 public static RootNamespace GetRootNamespace (string name)
100                 {
101                         return (RootNamespace) root_namespaces [name];
102                 }
103
104                 public static void ComputeNamespaces ()
105                 {
106                         foreach (RootNamespace rn in root_namespaces.Values) {
107                                 foreach (Assembly a in rn.referenced_assemblies) {
108                                         try {
109                                                 rn.ComputeNamespaces (a);
110                                         } catch (TypeLoadException e) {
111                                                 Report.Error (11, Location.Null, e.Message);
112                                         } catch (System.IO.FileNotFoundException) {
113                                                 Report.Error (12, Location.Null, "An assembly `{0}' is used without being referenced",
114                                                         a.FullName);
115                                         }
116                                 }
117                         }
118                 }
119
120                 public virtual Type LookupTypeReflection (string name, Location loc)
121                 {
122                         Type found_type = null;
123
124                         foreach (Assembly a in referenced_assemblies) {
125                                 Type t = GetTypeInAssembly (a, name);
126                                 if (t == null)
127                                         continue;
128
129                                 if (found_type == null) {
130                                         found_type = t;
131                                         continue;
132                                 }
133
134                                 Report.SymbolRelatedToPreviousError (found_type);
135                                 Report.SymbolRelatedToPreviousError (t);
136                                 Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
137
138                                 return found_type;
139                         }
140
141                         return found_type;
142                 }
143
144                 public void RegisterNamespace (Namespace child)
145                 {
146                         if (child != this)
147                                 all_namespaces.Add (child.Name, child);
148                 }
149
150                 public bool IsNamespace (string name)
151                 {
152                         return all_namespaces.Contains (name);
153                 }
154
155                 protected void RegisterNamespace (string dotted_name)
156                 {
157                         if (dotted_name != null && dotted_name.Length != 0 && ! IsNamespace (dotted_name))
158                                 GetNamespace (dotted_name, true);
159                 }
160
161                 void RegisterExtensionMethodClass (Type t)
162                 {
163                         string n = t.Namespace;
164                         Namespace ns = n == null ? Global : (Namespace)all_namespaces [n];
165                         if (ns == null)
166                                 ns = GetNamespace (n, true);
167  
168                         ns.RegisterExternalExtensionMethodClass (t);
169                 }
170
171                 protected void ComputeNamespaces (Assembly assembly)
172                 {
173                         bool contains_extension_methods = TypeManager.extension_attribute_type != null &&
174                                         assembly.IsDefined(TypeManager.extension_attribute_type, false);
175  
176                         if (get_namespaces_method != null && !contains_extension_methods) {
177                                 string [] namespaces = (string []) get_namespaces_method.Invoke (assembly, null);
178                                 foreach (string ns in namespaces)
179                                         RegisterNamespace (ns);
180                                 return;
181                         }
182   
183                         foreach (Type t in assembly.GetExportedTypes ()) {
184                                 if ((t.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute &&
185                                         contains_extension_methods && t.IsDefined (TypeManager.extension_attribute_type, false))
186                                         RegisterExtensionMethodClass (t);
187                                 else
188                                         RegisterNamespace (t.Namespace);
189                         }
190                 }
191
192                 protected static Type GetTypeInAssembly (Assembly assembly, string name)
193                 {
194                         Type t = assembly.GetType (name);
195                         if (t == null)
196                                 return null;
197
198                         if (t.IsPointer)
199                                 throw new InternalErrorException ("Use GetPointerType() to get a pointer");
200
201                         TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
202                         if (ta == TypeAttributes.NestedPrivate)
203                                 return null;
204
205                         if ((ta == TypeAttributes.NotPublic ||
206                              ta == TypeAttributes.NestedAssembly ||
207                              ta == TypeAttributes.NestedFamANDAssem) &&
208                             !TypeManager.IsThisOrFriendAssembly (t.Assembly))
209                                 return null;
210
211                         return t;
212                 }
213
214                 public override string ToString ()
215                 {
216                         return String.Format ("RootNamespace ({0}::)", alias_name);
217                 }
218
219                 public override string GetSignatureForError ()
220                 {
221                         return alias_name + "::";
222                 }
223         }
224
225         public class GlobalRootNamespace : RootNamespace {
226                 Module [] modules;
227
228                 public GlobalRootNamespace ()
229                         : base ("global")
230                 {
231                 }
232
233                 public Assembly [] Assemblies {
234                     get { return referenced_assemblies; }
235                 }
236
237                 public Module [] Modules {
238                         get { return modules; }
239                 }
240
241                 public void AddModuleReference (Module m)
242                 {
243                         int top = modules != null ? modules.Length : 0;
244                         Module [] n = new Module [top + 1];
245                         if (modules != null)
246                                 modules.CopyTo (n, 0);
247                         n [top] = m;
248                         modules = n;
249
250                         if (m == CodeGen.Module.Builder)
251                                 return;
252
253                         foreach (Type t in m.GetTypes ())
254                                 RegisterNamespace (t.Namespace);
255                 }
256
257                 public override void Error_NamespaceDoesNotExist(DeclSpace ds, Location loc, string name)
258                 {
259                         Report.Error (400, loc, "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
260                                 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                         if (external_exmethod_classes == null)
522                                 external_exmethod_classes = new ArrayList ();
523
524                         external_exmethod_classes.Add (type);
525                 }
526
527                 /// 
528                 /// Looks for extension method in this namespace
529                 /// 
530                 public ArrayList LookupExtensionMethod (Type extensionType, ClassOrStruct currentClass, string name)
531                 {
532                         ArrayList found = null;
533
534                         if (declspaces != null) {
535                                 IEnumerator e = declspaces.Values.GetEnumerator ();
536                                 e.Reset ();
537                                 while (e.MoveNext ()) {
538                                         Class c = e.Current as Class;
539                                         if (c == null)
540                                                 continue;
541
542                                         if (!c.IsStaticClass)
543                                                 continue;
544
545                                         ArrayList res = c.MemberCache.FindExtensionMethods (extensionType, name, c != currentClass);
546                                         if (res == null)
547                                                 continue;
548
549                                         if (found == null)
550                                                 found = res;
551                                         else
552                                                 found.AddRange (res);
553                                 }
554                         }
555
556                         if (external_exmethod_classes == null)
557                                 return found;
558
559                         foreach (Type t in external_exmethod_classes) {
560                                 MemberCache m = TypeHandle.GetMemberCache (t);
561                                 ArrayList res = m.FindExtensionMethods (extensionType, name, true);
562                                 if (res == null)
563                                         continue;
564
565                                 if (found == null)
566                                         found = res;
567                                 else
568                                         found.AddRange (res);
569                         }
570
571                         return found;
572                 }
573
574                 public void AddDeclSpace (string name, DeclSpace ds)
575                 {
576                         if (declspaces == null)
577                                 declspaces = new HybridDictionary ();
578                         declspaces.Add (name, ds);
579                 }
580
581                 public void RemoveDeclSpace (string name)
582                 {
583                         declspaces.Remove (name);
584                 }
585                 
586                 /// <summary>
587                 ///   The qualified name of the current namespace
588                 /// </summary>
589                 public string Name {
590                         get { return fullname; }
591                 }
592
593                 /// <summary>
594                 ///   The parent of this namespace, used by the parser to "Pop"
595                 ///   the current namespace declaration
596                 /// </summary>
597                 public Namespace Parent {
598                         get { return parent; }
599                 }
600         }
601
602         //
603         // Namespace container as created by the parser
604         //
605         public class NamespaceEntry : IResolveContext {
606
607                 class UsingEntry {
608                         readonly MemberName name;
609                         Namespace resolved;
610                         
611                         public UsingEntry (MemberName name)
612                         {
613                                 this.name = name;
614                         }
615
616                         public string GetSignatureForError ()
617                         {
618                                 return name.GetSignatureForError ();
619                         }
620
621                         public Location Location {
622                                 get { return name.Location; }
623                         }
624
625                         public MemberName MemberName {
626                                 get { return name; }
627                         }
628                         
629                         public string Name {
630                                 get { return GetSignatureForError (); }
631                         }
632
633                         public Namespace Resolve (IResolveContext rc)
634                         {
635                                 if (resolved != null)
636                                         return resolved;
637
638                                 FullNamedExpression fne = name.GetTypeExpression ().ResolveAsTypeStep (rc, false);
639                                 if (fne == null)
640                                         return null;
641
642                                 resolved = fne as Namespace;
643                                 if (resolved == null) {
644                                         Report.SymbolRelatedToPreviousError (fne.Type);
645                                         Report.Error (138, Location,
646                                                 "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
647                                                 GetSignatureForError ());
648                                 }
649                                 return resolved;
650                         }
651
652                         public override string ToString ()
653                         {
654                                 return Name;
655                         }
656                 }
657
658                 class UsingAliasEntry {
659                         public readonly string Alias;
660                         public Location Location;
661
662                         public UsingAliasEntry (string alias, Location loc)
663                         {
664                                 this.Alias = alias;
665                                 this.Location = loc;
666                         }
667
668                         public virtual FullNamedExpression Resolve (IResolveContext rc)
669                         {
670                                 FullNamedExpression fne = RootNamespace.GetRootNamespace (Alias);
671                                 if (fne == null) {
672                                         Report.Error (430, Location,
673                                                 "The extern alias `{0}' was not specified in -reference option",
674                                                 Alias);
675                                 }
676
677                                 return fne;
678                         }
679
680                         public override string ToString ()
681                         {
682                                 return Alias;
683                         }
684                         
685                 }
686
687                 class LocalUsingAliasEntry : UsingAliasEntry {
688                         Expression resolved;
689                         MemberName value;
690
691                         public LocalUsingAliasEntry (string alias, MemberName name, Location loc)
692                                 : base (alias, loc)
693                         {
694                                 this.value = name;
695                         }
696
697                         public override FullNamedExpression Resolve (IResolveContext rc)
698                         {
699                                 if (resolved != null || value == null)
700                                         return (FullNamedExpression)resolved;
701
702                                 resolved = value.GetTypeExpression ().ResolveAsTypeStep (rc, false);
703                                 if (resolved == null) {
704                                         value = null;
705                                         return null;
706                                 }
707
708                                 // FIXME: This is quite wrong, the accessibility is not global
709                                 if (resolved.Type != null) {
710                                         TypeAttributes attr = resolved.Type.Attributes & TypeAttributes.VisibilityMask;
711                                         if (attr == TypeAttributes.NestedPrivate || attr == TypeAttributes.NestedFamily ||
712                                                 ((attr == TypeAttributes.NestedFamORAssem || attr == TypeAttributes.NestedAssembly) && 
713                                                 TypeManager.LookupDeclSpace (resolved.Type) == null)) {
714                                                 Expression.ErrorIsInaccesible (resolved.Location, resolved.GetSignatureForError ());
715                                                 return null;
716                                         }
717                                 }
718
719                                 return (FullNamedExpression)resolved;
720                         }
721
722                         public override string ToString ()
723                         {
724                                 return String.Format ("{0} = {1}", Alias, value.GetSignatureForError ());
725                         }
726                 }
727
728                 Namespace ns;
729                 NamespaceEntry parent, implicit_parent;
730                 CompilationUnit file;
731                 int symfile_id;
732
733                 // Namespace using import block
734                 ArrayList using_aliases;
735                 ArrayList using_clauses;
736                 public bool DeclarationFound = false;
737                 // End
738
739                 public readonly bool IsImplicit;
740                 public readonly DeclSpace SlaveDeclSpace;
741                 static readonly Namespace [] empty_namespaces = new Namespace [0];
742                 Namespace [] namespace_using_table;
743
744                 static ArrayList entries = new ArrayList ();
745
746                 public static void Reset ()
747                 {
748                         entries = new ArrayList ();
749                 }
750
751                 public NamespaceEntry (NamespaceEntry parent, CompilationUnit file, string name)
752                 {
753                         this.parent = parent;
754                         this.file = file;
755                         entries.Add (this);
756
757                         if (parent != null)
758                                 ns = parent.NS.GetNamespace (name, true);
759                         else if (name != null)
760                                 ns = RootNamespace.Global.GetNamespace (name, true);
761                         else
762                                 ns = RootNamespace.Global;
763                         SlaveDeclSpace = new RootDeclSpace (this);
764                 }
765
766                 private NamespaceEntry (NamespaceEntry parent, CompilationUnit file, Namespace ns, bool slave)
767                 {
768                         this.parent = parent;
769                         this.file = file;
770                         this.IsImplicit = true;
771                         this.ns = ns;
772                         this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
773                 }
774
775                 //
776                 // Populates the Namespace with some using declarations, used by the
777                 // eval mode. 
778                 //
779                 public void Populate (ArrayList source_using_aliases, ArrayList source_using_clauses)
780                 {
781                         foreach (UsingAliasEntry uae in source_using_aliases){
782                                 if (using_aliases == null)
783                                         using_aliases = new ArrayList ();
784                                 
785                                 using_aliases.Add (uae);
786                         }
787
788                         foreach (UsingEntry ue in source_using_clauses){
789                                 if (using_clauses == null)
790                                         using_clauses = new ArrayList ();
791                                 
792                                 using_clauses.Add (ue);
793                         }
794                 }
795
796                 //
797                 // Extracts the using alises and using clauses into a couple of
798                 // arrays that might already have the same information;  Used by the
799                 // C# Eval mode.
800                 //
801                 public void Extract (ArrayList out_using_aliases, ArrayList out_using_clauses)
802                 {
803                         if (using_aliases != null){
804                                 foreach (UsingAliasEntry uae in using_aliases){
805                                         bool replaced = false;
806                                         
807                                         for (int i = 0; i < out_using_aliases.Count; i++){
808                                                 UsingAliasEntry out_uea = (UsingAliasEntry) out_using_aliases [i];
809                                                 
810                                                 if (out_uea.Alias == uae.Alias){
811                                                         out_using_aliases [i] = uae;
812                                                         replaced = true;
813                                                         break;
814                                                 }
815                                         }
816                                         if (!replaced)
817                                                 out_using_aliases.Add (uae);
818                                 }
819                         }
820
821                         if (using_clauses != null){
822                                 foreach (UsingEntry ue in using_clauses){
823                                         bool found = false;
824                                         
825                                         foreach (UsingEntry out_ue in out_using_clauses)
826                                                 if (out_ue.Name == ue.Name){
827                                                         found = true;
828                                                         break;
829                                                 }
830                                         if (!found)
831                                                 out_using_clauses.Add (ue);
832                                 }
833                         }
834                 }
835                 
836                 //
837                 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
838                 // resolved as if the immediately containing namespace body has no using-directives.
839                 //
840                 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
841                 // in the using-namespace-directive.
842                 //
843                 // To implement these rules, the expressions in the using directives are resolved using 
844                 // the "doppelganger" (ghostly bodiless duplicate).
845                 //
846                 NamespaceEntry doppelganger;
847                 NamespaceEntry Doppelganger {
848                         get {
849                                 if (!IsImplicit && doppelganger == null) {
850                                         doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
851                                         doppelganger.using_aliases = using_aliases;
852                                 }
853                                 return doppelganger;
854                         }
855                 }
856
857                 public Namespace NS {
858                         get { return ns; }
859                 }
860
861                 public NamespaceEntry Parent {
862                         get { return parent; }
863                 }
864
865                 public NamespaceEntry ImplicitParent {
866                         get {
867                                 if (parent == null)
868                                         return null;
869                                 if (implicit_parent == null) {
870                                         implicit_parent = (parent.NS == ns.Parent)
871                                                 ? parent
872                                                 : new NamespaceEntry (parent, file, ns.Parent, false);
873                                 }
874                                 return implicit_parent;
875                         }
876                 }
877
878                 /// <summary>
879                 ///   Records a new namespace for resolving name references
880                 /// </summary>
881                 public void AddUsing (MemberName name, Location loc)
882                 {
883                         if (DeclarationFound){
884                                 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
885                         }
886
887                         if (using_clauses == null) {
888                                 using_clauses = new ArrayList ();
889                         } else {
890                                 foreach (UsingEntry old_entry in using_clauses) {
891                                         if (name.Equals (old_entry.MemberName)) {
892                                                 Report.SymbolRelatedToPreviousError (old_entry.Location, old_entry.GetSignatureForError ());
893                                                 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetSignatureForError ());
894                                                 return;
895                                         }
896                                 }
897                         }
898
899                         using_clauses.Add (new UsingEntry (name));
900                 }
901
902                 public void AddUsingAlias (string alias, MemberName name, Location loc)
903                 {
904                         // TODO: This is parser bussines
905                         if (DeclarationFound){
906                                 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
907                         }
908
909                         if (RootContext.Version != LanguageVersion.ISO_1 && alias == "global")
910                                 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
911                                         " the global namespace will be used instead");
912
913                         AddUsingAlias (new LocalUsingAliasEntry (alias, name, loc));
914                 }
915
916                 public void AddUsingExternalAlias (string alias, Location loc)
917                 {
918                         // TODO: Do this in parser
919                         bool not_first = using_clauses != null || DeclarationFound;
920                         if (using_aliases != null && !not_first) {
921                                 foreach (UsingAliasEntry uae in using_aliases) {
922                                         if (uae is LocalUsingAliasEntry) {
923                                                 not_first = true;
924                                                 break;
925                                         }
926                                 }
927                         }
928
929                         if (not_first)
930                                 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
931
932                         if (alias == "global") {
933                                 Error_GlobalNamespaceRedefined (loc);
934                                 return;
935                         }
936
937                         AddUsingAlias (new UsingAliasEntry (alias, loc));
938                 }
939
940                 void AddUsingAlias (UsingAliasEntry uae)
941                 {
942                         if (using_aliases == null) {
943                                 using_aliases = new ArrayList ();
944                         } else {
945                                 foreach (UsingAliasEntry entry in using_aliases) {
946                                         if (uae.Alias == entry.Alias) {
947                                                 Report.SymbolRelatedToPreviousError (uae.Location, uae.Alias);
948                                                 Report.Error (1537, entry.Location, "The using alias `{0}' appeared previously in this namespace",
949                                                         entry.Alias);
950                                                 return;
951                                         }
952                                 }
953                         }
954
955                         using_aliases.Add (uae);
956                 }
957
958                 ///
959                 /// Does extension methods look up to find a method which matches name and extensionType.
960                 /// Search starts from this namespace and continues hierarchically up to top level.
961                 ///
962                 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, ClassOrStruct currentClass, string name, Location loc)
963                 {
964                         ArrayList candidates = null;
965                         if (currentClass != null) {
966                                 candidates = ns.LookupExtensionMethod (extensionType, currentClass, name);
967                                 if (candidates != null)
968                                         return new ExtensionMethodGroupExpr (candidates, this, extensionType, loc);
969                         }
970
971                         foreach (Namespace n in GetUsingTable ()) {
972                                 ArrayList a = n.LookupExtensionMethod (extensionType, null, name);
973                                 if (a == null)
974                                         continue;
975
976                                 if (candidates == null)
977                                         candidates = a;
978                                 else
979                                         candidates.AddRange (a);
980                         }
981
982                         if (candidates != null)
983                                 return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
984
985                         if (parent == null)
986                                 return null;
987
988                         //
989                         // Inspect parent namespaces in namespace expression
990                         //
991                         Namespace parent_ns = ns.Parent;
992                         do {
993                                 candidates = parent_ns.LookupExtensionMethod (extensionType, null, name);
994                                 if (candidates != null)
995                                         return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
996
997                                 parent_ns = parent_ns.Parent;
998                         } while (parent_ns != null);
999
1000                         //
1001                         // Continue in parent scope
1002                         //
1003                         return parent.LookupExtensionMethod (extensionType, currentClass, name, loc);
1004                 }
1005
1006                 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
1007                 {
1008                         // Precondition: Only simple names (no dots) will be looked up with this function.
1009                         FullNamedExpression resolved = null;
1010                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
1011                                 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
1012                                         break;
1013                         }
1014                         return resolved;
1015                 }
1016
1017                 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
1018                 {
1019                         Report.SymbolRelatedToPreviousError (t1.Type);
1020                         Report.SymbolRelatedToPreviousError (t2.Type);
1021                         Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
1022                                 name, t1.GetSignatureForError (), t2.GetSignatureForError ());
1023                 }
1024
1025                 // Looks-up a alias named @name in this and surrounding namespace declarations
1026                 public FullNamedExpression LookupAlias (string name)
1027                 {
1028                         for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
1029                                 if (n.using_aliases == null)
1030                                         continue;
1031
1032                                 foreach (UsingAliasEntry ue in n.using_aliases) {
1033                                         if (ue.Alias == name)
1034                                                 return ue.Resolve (Doppelganger);
1035                                 }
1036                         }
1037
1038                         return null;
1039                 }
1040
1041                 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
1042                 {
1043                         //
1044                         // Check whether it's in the namespace.
1045                         //
1046                         FullNamedExpression fne = ns.Lookup (ds, name, loc);
1047
1048                         //
1049                         // Check aliases. 
1050                         //
1051                         if (using_aliases != null) {
1052                                 foreach (UsingAliasEntry ue in using_aliases) {
1053                                         if (ue.Alias == name) {
1054                                                 if (fne != null) {
1055                                                         if (Doppelganger != null) {
1056                                                                 // TODO: Namespace has broken location
1057                                                                 //Report.SymbolRelatedToPreviousError (fne.Location, null);
1058                                                                 Report.SymbolRelatedToPreviousError (ue.Location, null);
1059                                                                 Report.Error (576, loc,
1060                                                                         "Namespace `{0}' contains a definition with same name as alias `{1}'",
1061                                                                         GetSignatureForError (), name);
1062                                                         } else {
1063                                                                 return fne;
1064                                                         }
1065                                                 }
1066
1067                                                 return ue.Resolve (Doppelganger);
1068                                         }
1069                                 }
1070                         }
1071
1072                         if (fne != null)
1073                                 return fne;
1074
1075                         if (IsImplicit)
1076                                 return null;
1077
1078                         //
1079                         // Check using entries.
1080                         //
1081                         FullNamedExpression match = null;
1082                         foreach (Namespace using_ns in GetUsingTable ()) {
1083                                 match = using_ns.Lookup (ds, name, loc);
1084                                 if (match == null || !(match is TypeExpr))
1085                                         continue;
1086                                 if (fne != null) {
1087                                         if (!ignore_cs0104)
1088                                                 Error_AmbiguousTypeReference (loc, name, fne, match);
1089                                         return null;
1090                                 }
1091                                 fne = match;
1092                         }
1093
1094                         return fne;
1095                 }
1096
1097                 Namespace [] GetUsingTable ()
1098                 {
1099                         if (namespace_using_table != null)
1100                                 return namespace_using_table;
1101
1102                         if (using_clauses == null) {
1103                                 namespace_using_table = empty_namespaces;
1104                                 return namespace_using_table;
1105                         }
1106
1107                         ArrayList list = new ArrayList (using_clauses.Count);
1108
1109                         foreach (UsingEntry ue in using_clauses) {
1110                                 Namespace using_ns = ue.Resolve (Doppelganger);
1111                                 if (using_ns == null)
1112                                         continue;
1113
1114                                 list.Add (using_ns);
1115                         }
1116
1117                         namespace_using_table = (Namespace[])list.ToArray (typeof (Namespace));
1118                         return namespace_using_table;
1119                 }
1120
1121                 static readonly string [] empty_using_list = new string [0];
1122
1123                 public int SymbolFileID {
1124                         get {
1125                                 if (symfile_id == 0 && file.SourceFileEntry != null) {
1126                                         int parent_id = parent == null ? 0 : parent.SymbolFileID;
1127
1128                                         string [] using_list = empty_using_list;
1129                                         if (using_clauses != null) {
1130                                                 using_list = new string [using_clauses.Count];
1131                                                 for (int i = 0; i < using_clauses.Count; i++)
1132                                                         using_list [i] = ((UsingEntry) using_clauses [i]).MemberName.GetName ();
1133                                         }
1134
1135                                         symfile_id = SymbolWriter.DefineNamespace (ns.Name, file.CompileUnitEntry, using_list, parent_id);
1136                                 }
1137                                 return symfile_id;
1138                         }
1139                 }
1140
1141                 static void MsgtryRef (string s)
1142                 {
1143                         Console.WriteLine ("    Try using -r:" + s);
1144                 }
1145
1146                 static void MsgtryPkg (string s)
1147                 {
1148                         Console.WriteLine ("    Try using -pkg:" + s);
1149                 }
1150
1151                 public static void Error_GlobalNamespaceRedefined (Location loc)
1152                 {
1153                         Report.Error (1681, loc, "You cannot redefine the global extern alias");
1154                 }
1155
1156                 public static void Error_NamespaceNotFound (Location loc, string name)
1157                 {
1158                         Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
1159                                 name);
1160
1161                         switch (name) {
1162                         case "Gtk": case "GtkSharp":
1163                                 MsgtryPkg ("gtk-sharp");
1164                                 break;
1165
1166                         case "Gdk": case "GdkSharp":
1167                                 MsgtryPkg ("gdk-sharp");
1168                                 break;
1169
1170                         case "Glade": case "GladeSharp":
1171                                 MsgtryPkg ("glade-sharp");
1172                                 break;
1173
1174                         case "System.Drawing":
1175                         case "System.Web.Services":
1176                         case "System.Web":
1177                         case "System.Data":
1178                         case "System.Windows.Forms":
1179                                 MsgtryRef (name);
1180                                 break;
1181                         }
1182                 }
1183
1184                 /// <summary>
1185                 ///   Used to validate that all the using clauses are correct
1186                 ///   after we are finished parsing all the files.  
1187                 /// </summary>
1188                 void VerifyUsing ()
1189                 {
1190                         if (using_aliases != null) {
1191                                 foreach (UsingAliasEntry ue in using_aliases)
1192                                         ue.Resolve (Doppelganger);
1193                         }
1194
1195                         if (using_clauses != null) {
1196                                 foreach (UsingEntry ue in using_clauses)
1197                                         ue.Resolve (Doppelganger);
1198                         }
1199                 }
1200
1201                 /// <summary>
1202                 ///   Used to validate that all the using clauses are correct
1203                 ///   after we are finished parsing all the files.  
1204                 /// </summary>
1205                 static public void VerifyAllUsing ()
1206                 {
1207                         foreach (NamespaceEntry entry in entries)
1208                                 entry.VerifyUsing ();
1209                 }
1210
1211                 public string GetSignatureForError ()
1212                 {
1213                         return ns.GetSignatureForError ();
1214                 }
1215
1216                 public override string ToString ()
1217                 {
1218                         return ns.ToString ();
1219                 }
1220
1221                 #region IResolveContext Members
1222
1223                 public DeclSpace DeclContainer {
1224                         get { return SlaveDeclSpace; }
1225                 }
1226
1227                 public bool IsInObsoleteScope {
1228                         get { return SlaveDeclSpace.IsInObsoleteScope; }
1229                 }
1230
1231                 public bool IsInUnsafeScope {
1232                         get { return SlaveDeclSpace.IsInUnsafeScope; }
1233                 }
1234
1235                 public DeclSpace GenericDeclContainer {
1236                         get { return SlaveDeclSpace; }
1237                 }
1238
1239                 #endregion
1240         }
1241 }