2009-09-02 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 (ResolveContext 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 (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 : IMemberContext {
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 (IMemberContext 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 (IMemberContext 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 (IMemberContext rc)
782                         {
783                                 if (resolved != null || value == null)
784                                         return resolved;
785
786                                 if (rc == null)
787                                         return null;
788
789                                 resolved = value.GetTypeExpression ().ResolveAsTypeStep (rc, false);
790                                 if (resolved == null) {
791                                         value = null;
792                                         return null;
793                                 }
794
795                                 if (resolved is TypeExpr)
796                                         resolved = resolved.ResolveAsBaseTerminal (rc, false);
797
798                                 return resolved;
799                         }
800
801                         public override string ToString ()
802                         {
803                                 return String.Format ("{0} = {1}", Alias, value.GetSignatureForError ());
804                         }
805                 }
806
807                 Namespace ns;
808                 NamespaceEntry parent, implicit_parent;
809                 CompilationUnit file;
810                 int symfile_id;
811
812                 // Namespace using import block
813                 ArrayList using_aliases;
814                 ArrayList using_clauses;
815                 public bool DeclarationFound = false;
816                 // End
817
818                 public readonly bool IsImplicit;
819                 public readonly DeclSpace SlaveDeclSpace;
820                 static readonly Namespace [] empty_namespaces = new Namespace [0];
821                 Namespace [] namespace_using_table;
822
823                 static ArrayList entries = new ArrayList ();
824
825                 public static void Reset ()
826                 {
827                         entries = new ArrayList ();
828                 }
829
830                 public NamespaceEntry (NamespaceEntry parent, CompilationUnit file, string name)
831                 {
832                         this.parent = parent;
833                         this.file = file;
834                         entries.Add (this);
835
836                         if (parent != null)
837                                 ns = parent.NS.GetNamespace (name, true);
838                         else if (name != null)
839                                 ns = GlobalRootNamespace.Instance.GetNamespace (name, true);
840                         else
841                                 ns = GlobalRootNamespace.Instance;
842                         SlaveDeclSpace = new RootDeclSpace (this);
843                 }
844
845                 private NamespaceEntry (NamespaceEntry parent, CompilationUnit file, Namespace ns, bool slave)
846                 {
847                         this.parent = parent;
848                         this.file = file;
849                         this.IsImplicit = true;
850                         this.ns = ns;
851                         this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
852                 }
853
854                 //
855                 // Populates the Namespace with some using declarations, used by the
856                 // eval mode. 
857                 //
858                 public void Populate (ArrayList source_using_aliases, ArrayList source_using_clauses)
859                 {
860                         foreach (UsingAliasEntry uae in source_using_aliases){
861                                 if (using_aliases == null)
862                                         using_aliases = new ArrayList ();
863                                 
864                                 using_aliases.Add (uae);
865                         }
866
867                         foreach (UsingEntry ue in source_using_clauses){
868                                 if (using_clauses == null)
869                                         using_clauses = new ArrayList ();
870                                 
871                                 using_clauses.Add (ue);
872                         }
873                 }
874
875                 //
876                 // Extracts the using alises and using clauses into a couple of
877                 // arrays that might already have the same information;  Used by the
878                 // C# Eval mode.
879                 //
880                 public void Extract (ArrayList out_using_aliases, ArrayList out_using_clauses)
881                 {
882                         if (using_aliases != null){
883                                 foreach (UsingAliasEntry uae in using_aliases){
884                                         bool replaced = false;
885                                         
886                                         for (int i = 0; i < out_using_aliases.Count; i++){
887                                                 UsingAliasEntry out_uea = (UsingAliasEntry) out_using_aliases [i];
888                                                 
889                                                 if (out_uea.Alias == uae.Alias){
890                                                         out_using_aliases [i] = uae;
891                                                         replaced = true;
892                                                         break;
893                                                 }
894                                         }
895                                         if (!replaced)
896                                                 out_using_aliases.Add (uae);
897                                 }
898                         }
899
900                         if (using_clauses != null){
901                                 foreach (UsingEntry ue in using_clauses){
902                                         bool found = false;
903                                         
904                                         foreach (UsingEntry out_ue in out_using_clauses)
905                                                 if (out_ue.Name == ue.Name){
906                                                         found = true;
907                                                         break;
908                                                 }
909                                         if (!found)
910                                                 out_using_clauses.Add (ue);
911                                 }
912                         }
913                 }
914                 
915                 //
916                 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
917                 // resolved as if the immediately containing namespace body has no using-directives.
918                 //
919                 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
920                 // in the using-namespace-directive.
921                 //
922                 // To implement these rules, the expressions in the using directives are resolved using 
923                 // the "doppelganger" (ghostly bodiless duplicate).
924                 //
925                 NamespaceEntry doppelganger;
926                 NamespaceEntry Doppelganger {
927                         get {
928                                 if (!IsImplicit && doppelganger == null) {
929                                         doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
930                                         doppelganger.using_aliases = using_aliases;
931                                 }
932                                 return doppelganger;
933                         }
934                 }
935
936                 public Namespace NS {
937                         get { return ns; }
938                 }
939
940                 public NamespaceEntry Parent {
941                         get { return parent; }
942                 }
943
944                 public NamespaceEntry ImplicitParent {
945                         get {
946                                 if (parent == null)
947                                         return null;
948                                 if (implicit_parent == null) {
949                                         implicit_parent = (parent.NS == ns.Parent)
950                                                 ? parent
951                                                 : new NamespaceEntry (parent, file, ns.Parent, false);
952                                 }
953                                 return implicit_parent;
954                         }
955                 }
956
957                 /// <summary>
958                 ///   Records a new namespace for resolving name references
959                 /// </summary>
960                 public void AddUsing (MemberName name, Location loc)
961                 {
962                         if (DeclarationFound){
963                                 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
964                         }
965
966                         if (using_clauses == null) {
967                                 using_clauses = new ArrayList ();
968                         } else {
969                                 foreach (UsingEntry old_entry in using_clauses) {
970                                         if (name.Equals (old_entry.MemberName)) {
971                                                 Report.SymbolRelatedToPreviousError (old_entry.Location, old_entry.GetSignatureForError ());
972                                                 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetSignatureForError ());
973                                                 return;
974                                         }
975                                 }
976                         }
977
978                         using_clauses.Add (new UsingEntry (name));
979                 }
980
981                 public void AddUsingAlias (string alias, MemberName name, Location loc)
982                 {
983                         // TODO: This is parser bussines
984                         if (DeclarationFound){
985                                 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
986                         }
987
988                         if (RootContext.Version != LanguageVersion.ISO_1 && alias == "global")
989                                 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
990                                         " the global namespace will be used instead");
991
992                         AddUsingAlias (new LocalUsingAliasEntry (alias, name, loc));
993                 }
994
995                 public void AddUsingExternalAlias (string alias, Location loc)
996                 {
997                         // TODO: Do this in parser
998                         bool not_first = using_clauses != null || DeclarationFound;
999                         if (using_aliases != null && !not_first) {
1000                                 foreach (UsingAliasEntry uae in using_aliases) {
1001                                         if (uae is LocalUsingAliasEntry) {
1002                                                 not_first = true;
1003                                                 break;
1004                                         }
1005                                 }
1006                         }
1007
1008                         if (not_first)
1009                                 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
1010
1011                         if (alias == "global") {
1012                                 Error_GlobalNamespaceRedefined (loc);
1013                                 return;
1014                         }
1015
1016                         AddUsingAlias (new UsingAliasEntry (alias, loc));
1017                 }
1018
1019                 void AddUsingAlias (UsingAliasEntry uae)
1020                 {
1021                         if (using_aliases == null) {
1022                                 using_aliases = new ArrayList ();
1023                         } else {
1024                                 foreach (UsingAliasEntry entry in using_aliases) {
1025                                         if (uae.Alias == entry.Alias) {
1026                                                 Report.SymbolRelatedToPreviousError (uae.Location, uae.Alias);
1027                                                 Report.Error (1537, entry.Location, "The using alias `{0}' appeared previously in this namespace",
1028                                                         entry.Alias);
1029                                                 return;
1030                                         }
1031                                 }
1032                         }
1033
1034                         using_aliases.Add (uae);
1035                 }
1036
1037                 ///
1038                 /// Does extension methods look up to find a method which matches name and extensionType.
1039                 /// Search starts from this namespace and continues hierarchically up to top level.
1040                 ///
1041                 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
1042                 {
1043                         ArrayList candidates = null;
1044                         foreach (Namespace n in GetUsingTable ()) {
1045                                 ArrayList a = n.LookupExtensionMethod (extensionType, null, name);
1046                                 if (a == null)
1047                                         continue;
1048
1049                                 if (candidates == null)
1050                                         candidates = a;
1051                                 else
1052                                         candidates.AddRange (a);
1053                         }
1054
1055                         if (candidates != null)
1056                                 return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
1057
1058                         if (parent == null)
1059                                 return null;
1060
1061                         //
1062                         // Inspect parent namespaces in namespace expression
1063                         //
1064                         Namespace parent_ns = ns.Parent;
1065                         do {
1066                                 candidates = parent_ns.LookupExtensionMethod (extensionType, null, name);
1067                                 if (candidates != null)
1068                                         return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
1069
1070                                 parent_ns = parent_ns.Parent;
1071                         } while (parent_ns != null);
1072
1073                         //
1074                         // Continue in parent scope
1075                         //
1076                         return parent.LookupExtensionMethod (extensionType, name, loc);
1077                 }
1078
1079                 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
1080                 {
1081                         // Precondition: Only simple names (no dots) will be looked up with this function.
1082                         FullNamedExpression resolved = null;
1083                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
1084                                 if ((resolved = curr_ns.Lookup (name, loc, ignore_cs0104)) != null)
1085                                         break;
1086                         }
1087                         return resolved;
1088                 }
1089
1090                 public ICollection CompletionGetTypesStartingWith (string prefix)
1091                 {
1092                         Hashtable result = new Hashtable ();
1093                         
1094                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent){
1095                                 foreach (Namespace using_ns in GetUsingTable ()){
1096                                         if (prefix.StartsWith (using_ns.Name)){
1097                                                 int ld = prefix.LastIndexOf ('.');
1098                                                 if (ld != -1){
1099                                                         string rest = prefix.Substring (ld+1);
1100
1101                                                         using_ns.CompletionGetTypesStartingWith (rest, result);
1102                                                 }
1103                                         }
1104                                         using_ns.CompletionGetTypesStartingWith (prefix, result);
1105                                 }
1106                         }
1107
1108                         return result.Keys;
1109                 }
1110                 
1111                 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
1112                 {
1113                         Report.SymbolRelatedToPreviousError (t1.Type);
1114                         Report.SymbolRelatedToPreviousError (t2.Type);
1115                         Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
1116                                 name, t1.GetSignatureForError (), t2.GetSignatureForError ());
1117                 }
1118
1119                 // Looks-up a alias named @name in this and surrounding namespace declarations
1120                 public FullNamedExpression LookupNamespaceAlias (string name)
1121                 {
1122                         for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
1123                                 if (n.using_aliases == null)
1124                                         continue;
1125
1126                                 foreach (UsingAliasEntry ue in n.using_aliases) {
1127                                         if (ue.Alias == name)
1128                                                 return ue.Resolve (Doppelganger);
1129                                 }
1130                         }
1131
1132                         return null;
1133                 }
1134
1135                 private FullNamedExpression Lookup (string name, Location loc, bool ignore_cs0104)
1136                 {
1137                         //
1138                         // Check whether it's in the namespace.
1139                         //
1140                         FullNamedExpression fne = ns.Lookup (name, loc);
1141
1142                         //
1143                         // Check aliases. 
1144                         //
1145                         if (using_aliases != null) {
1146                                 foreach (UsingAliasEntry ue in using_aliases) {
1147                                         if (ue.Alias == name) {
1148                                                 if (fne != null) {
1149                                                         if (Doppelganger != null) {
1150                                                                 // TODO: Namespace has broken location
1151                                                                 //Report.SymbolRelatedToPreviousError (fne.Location, null);
1152                                                                 Report.SymbolRelatedToPreviousError (ue.Location, null);
1153                                                                 Report.Error (576, loc,
1154                                                                         "Namespace `{0}' contains a definition with same name as alias `{1}'",
1155                                                                         GetSignatureForError (), name);
1156                                                         } else {
1157                                                                 return fne;
1158                                                         }
1159                                                 }
1160
1161                                                 return ue.Resolve (Doppelganger);
1162                                         }
1163                                 }
1164                         }
1165
1166                         if (fne != null)
1167                                 return fne;
1168
1169                         if (IsImplicit)
1170                                 return null;
1171
1172                         //
1173                         // Check using entries.
1174                         //
1175                         FullNamedExpression match = null;
1176                         foreach (Namespace using_ns in GetUsingTable ()) {
1177                                 match = using_ns.Lookup (name, loc);
1178                                 if (match == null || !(match is TypeExpr))
1179                                         continue;
1180                                 if (fne != null) {
1181                                         if (!ignore_cs0104)
1182                                                 Error_AmbiguousTypeReference (loc, name, fne, match);
1183                                         return null;
1184                                 }
1185                                 fne = match;
1186                         }
1187
1188                         return fne;
1189                 }
1190
1191                 Namespace [] GetUsingTable ()
1192                 {
1193                         if (namespace_using_table != null)
1194                                 return namespace_using_table;
1195
1196                         if (using_clauses == null) {
1197                                 namespace_using_table = empty_namespaces;
1198                                 return namespace_using_table;
1199                         }
1200
1201                         ArrayList list = new ArrayList (using_clauses.Count);
1202
1203                         foreach (UsingEntry ue in using_clauses) {
1204                                 Namespace using_ns = ue.Resolve (Doppelganger);
1205                                 if (using_ns == null)
1206                                         continue;
1207
1208                                 list.Add (using_ns);
1209                         }
1210
1211                         namespace_using_table = (Namespace[])list.ToArray (typeof (Namespace));
1212                         return namespace_using_table;
1213                 }
1214
1215                 static readonly string [] empty_using_list = new string [0];
1216
1217                 public int SymbolFileID {
1218                         get {
1219                                 if (symfile_id == 0 && file.SourceFileEntry != null) {
1220                                         int parent_id = parent == null ? 0 : parent.SymbolFileID;
1221
1222                                         string [] using_list = empty_using_list;
1223                                         if (using_clauses != null) {
1224                                                 using_list = new string [using_clauses.Count];
1225                                                 for (int i = 0; i < using_clauses.Count; i++)
1226                                                         using_list [i] = ((UsingEntry) using_clauses [i]).MemberName.GetName ();
1227                                         }
1228
1229                                         symfile_id = SymbolWriter.DefineNamespace (ns.Name, file.CompileUnitEntry, using_list, parent_id);
1230                                 }
1231                                 return symfile_id;
1232                         }
1233                 }
1234
1235                 static void MsgtryRef (string s)
1236                 {
1237                         Console.WriteLine ("    Try using -r:" + s);
1238                 }
1239
1240                 static void MsgtryPkg (string s)
1241                 {
1242                         Console.WriteLine ("    Try using -pkg:" + s);
1243                 }
1244
1245                 public static void Error_GlobalNamespaceRedefined (Location loc)
1246                 {
1247                         Report.Error (1681, loc, "You cannot redefine the global extern alias");
1248                 }
1249
1250                 public static void Error_NamespaceNotFound (Location loc, string name)
1251                 {
1252                         Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
1253                                 name);
1254
1255                         switch (name) {
1256                         case "Gtk": case "GtkSharp":
1257                                 MsgtryPkg ("gtk-sharp");
1258                                 break;
1259
1260                         case "Gdk": case "GdkSharp":
1261                                 MsgtryPkg ("gdk-sharp");
1262                                 break;
1263
1264                         case "Glade": case "GladeSharp":
1265                                 MsgtryPkg ("glade-sharp");
1266                                 break;
1267
1268                         case "System.Drawing":
1269                         case "System.Web.Services":
1270                         case "System.Web":
1271                         case "System.Data":
1272                         case "System.Windows.Forms":
1273                                 MsgtryRef (name);
1274                                 break;
1275                         }
1276                 }
1277
1278                 /// <summary>
1279                 ///   Used to validate that all the using clauses are correct
1280                 ///   after we are finished parsing all the files.  
1281                 /// </summary>
1282                 void VerifyUsing ()
1283                 {
1284                         if (using_aliases != null) {
1285                                 foreach (UsingAliasEntry ue in using_aliases)
1286                                         ue.Resolve (Doppelganger);
1287                         }
1288
1289                         if (using_clauses != null) {
1290                                 foreach (UsingEntry ue in using_clauses)
1291                                         ue.Resolve (Doppelganger);
1292                         }
1293                 }
1294
1295                 /// <summary>
1296                 ///   Used to validate that all the using clauses are correct
1297                 ///   after we are finished parsing all the files.  
1298                 /// </summary>
1299                 static public void VerifyAllUsing ()
1300                 {
1301                         foreach (NamespaceEntry entry in entries)
1302                                 entry.VerifyUsing ();
1303                 }
1304
1305                 public string GetSignatureForError ()
1306                 {
1307                         return ns.GetSignatureForError ();
1308                 }
1309
1310                 public override string ToString ()
1311                 {
1312                         return ns.ToString ();
1313                 }
1314
1315                 #region IMemberContext Members
1316
1317                 public Type CurrentType {
1318                         get { return SlaveDeclSpace.CurrentType; }
1319                 }
1320
1321                 public TypeContainer CurrentTypeDefinition {
1322                         get { return SlaveDeclSpace.CurrentTypeDefinition; }
1323                 }
1324
1325                 public TypeParameter[] CurrentTypeParameters {
1326                         get { return SlaveDeclSpace.CurrentTypeParameters; }
1327                 }
1328
1329                 public bool IsObsolete {
1330                         get { return SlaveDeclSpace.IsObsolete; }
1331                 }
1332
1333                 public bool IsUnsafe {
1334                         get { return SlaveDeclSpace.IsUnsafe; }
1335                 }
1336
1337                 public bool IsStatic {
1338                         get { return SlaveDeclSpace.IsStatic; }
1339                 }
1340
1341                 #endregion
1342         }
1343 }