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