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