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