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