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