2010-01-15 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.Generic;
13 using System.Reflection;
14
15 namespace Mono.CSharp {
16
17         public class RootNamespace : Namespace {
18                 //
19                 // Points to Mono's GetNamespaces method, an
20                 // optimization when running on Mono to fetch all the
21                 // namespaces in an assembly
22                 //
23                 static MethodInfo get_namespaces_method;
24
25                 protected readonly string alias_name;
26                 protected Assembly [] referenced_assemblies;
27
28                 Dictionary<string, Namespace> all_namespaces;
29
30                 static RootNamespace ()
31                 {
32                         get_namespaces_method = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance | BindingFlags.NonPublic);
33                 }
34
35                 public RootNamespace (string alias_name)
36                         : base (null, String.Empty)
37                 {
38                         this.alias_name = alias_name;
39                         referenced_assemblies = new Assembly [0];
40
41                         all_namespaces = new Dictionary<string, Namespace> ();
42                         all_namespaces.Add ("", this);
43                 }
44
45                 public void AddAssemblyReference (Assembly a)
46                 {
47                         foreach (Assembly assembly in referenced_assemblies) {
48                                 if (a == assembly)
49                                         return;
50                         }
51
52                         int top = referenced_assemblies.Length;
53                         Assembly [] n = new Assembly [top + 1];
54                         referenced_assemblies.CopyTo (n, 0);
55                         n [top] = a;
56                         referenced_assemblies = n;
57                 }
58
59                 public void ComputeNamespace (CompilerContext ctx, Type extensionType)
60                 {
61                         foreach (Assembly a in referenced_assemblies) {
62                                 try {
63                                         ComputeNamespaces (a, extensionType);
64                                 } catch (TypeLoadException e) {
65                                         ctx.Report.Error (11, Location.Null, e.Message);
66                                 } catch (System.IO.FileNotFoundException) {
67                                         ctx.Report.Error (12, Location.Null, "An assembly `{0}' is used without being referenced",
68                                                 a.FullName);
69                                 }
70                         }
71                 }
72
73                 public virtual Type LookupTypeReflection (CompilerContext ctx, string name, Location loc, bool must_be_unique)
74                 {
75                         // FIXME: Breaks dynamic
76                         Assembly invocation_assembly = CodeGen.Assembly.Builder;
77
78                         Type found_type = null;
79                         foreach (Assembly a in referenced_assemblies) {
80                                 Type t = GetTypeInAssembly (invocation_assembly, a, name);
81                                 if (t == null)
82                                         continue;
83
84                                 if (!must_be_unique)
85                                         return t;
86
87                                 if (found_type == null) {
88                                         found_type = t;
89                                         continue;
90                                 }
91
92                                 // When type is forwarded
93                                 if (t.Assembly == found_type.Assembly)
94                                         continue;                                       
95
96                                 ctx.Report.SymbolRelatedToPreviousError (found_type);
97                                 ctx.Report.SymbolRelatedToPreviousError (t);
98                                 if (loc.IsNull) {
99                                         Error_AmbiguousPredefinedType (ctx, loc, name, found_type);
100                                 } else {
101                                         ctx.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
102                                 }
103
104                                 return found_type;
105                         }
106
107                         return found_type;
108                 }
109
110                 //
111                 // Returns the types starting with the given prefix
112                 //
113                 public ICollection<string> CompletionGetTypesStartingWith (string prefix)
114                 {
115                         Dictionary<string, string> result = null;
116
117                         foreach (Assembly a in referenced_assemblies){
118                                 Type [] mtypes = a.GetTypes ();
119
120                                 foreach (Type t in mtypes){
121                                         string f = t.FullName;
122
123                                         if (f.StartsWith (prefix) && (result == null || !result.ContainsKey (f))){
124                                                 if (result == null)
125                                                         result = new Dictionary<string, string> ();
126
127                                                 result [f] = f;
128                                         }
129                                 }
130                         }
131                         return result == null ? null : result.Keys;
132                 }
133                 
134                 protected static void Error_AmbiguousPredefinedType (CompilerContext ctx, Location loc, string name, Type type)
135                 {
136                         ctx.Report.Warning (1685, 1, loc,
137                                 "The predefined type `{0}' is ambiguous. Using definition from `{1}'",
138                                 name, type.Assembly.FullName);
139                 }
140
141                 public void RegisterNamespace (Namespace child)
142                 {
143                         if (child != this)
144                                 all_namespaces.Add (child.Name, child);
145                 }
146
147                 public bool IsNamespace (string name)
148                 {
149                         return all_namespaces.ContainsKey (name);
150                 }
151
152                 protected void RegisterNamespace (string dotted_name)
153                 {
154                         if (dotted_name != null && dotted_name.Length != 0 && ! IsNamespace (dotted_name))
155                                 GetNamespace (dotted_name, true);
156                 }
157
158                 void RegisterExtensionMethodClass (Type t)
159                 {
160                         string n = t.Namespace;
161                         Namespace ns = null;
162                         if (n == null)
163                                 ns = GlobalRootNamespace.Instance;
164                         else
165                                 all_namespaces.TryGetValue (n, out ns);
166
167                         if (ns == null)
168                                 ns = GetNamespace (n, true);
169  
170                         ns.RegisterExternalExtensionMethodClass (t);
171                 }
172
173                 void ComputeNamespaces (Assembly assembly, Type extensionType)
174                 {
175                         bool contains_extension_methods = extensionType != null && assembly.IsDefined (extensionType, false);
176  
177                         if (get_namespaces_method != null) {
178                                 string [] namespaces = (string []) get_namespaces_method.Invoke (assembly, null);
179                                 foreach (string ns in namespaces)
180                                         RegisterNamespace (ns);
181
182                                 if (!contains_extension_methods)
183                                         return;
184                         }
185
186                         foreach (Type t in assembly.GetTypes ()) {
187                                 if ((t.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute &&
188                                         contains_extension_methods && t.IsDefined (extensionType, false))
189                                         RegisterExtensionMethodClass (t);
190
191                                 if (get_namespaces_method == null)
192                                         RegisterNamespace (t.Namespace);
193                         }
194                 }
195
196                 protected static Type GetTypeInAssembly (Assembly invocation, Assembly assembly, string name)
197                 {
198                         if (assembly == null)
199                                 throw new ArgumentNullException ("assembly");
200                         if (name == null)
201                                 throw new ArgumentNullException ("name");
202                         Type t = assembly.GetType (name);
203                         if (t == null)
204                                 return null;
205
206                         if (t.IsPointer)
207                                 throw new InternalErrorException ("Use GetPointerType() to get a pointer");
208
209                         TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
210                         if (ta == TypeAttributes.NestedPrivate)
211                                 return null;
212
213                         if ((ta == TypeAttributes.NotPublic ||
214                              ta == TypeAttributes.NestedAssembly ||
215                              ta == TypeAttributes.NestedFamANDAssem) &&
216                             !TypeManager.IsThisOrFriendAssembly (invocation, t.Assembly))
217                                 return null;
218
219                         return t;
220                 }
221
222                 public override string ToString ()
223                 {
224                         return String.Format ("RootNamespace ({0}::)", alias_name);
225                 }
226
227                 public override string GetSignatureForError ()
228                 {
229                         return alias_name + "::";
230                 }
231         }
232
233         public class GlobalRootNamespace : RootNamespace {
234                 Module [] modules;
235                 Dictionary<string, RootNamespace> root_namespaces;
236
237                 public static GlobalRootNamespace Instance = new GlobalRootNamespace ();
238
239                 GlobalRootNamespace ()
240                         : base ("global")
241                 {
242                         root_namespaces = new Dictionary<string, RootNamespace> ();
243                         root_namespaces.Add (alias_name, this);
244                 }
245
246                 public static void Reset ()
247                 {
248                         Instance = new GlobalRootNamespace ();
249                 }
250
251                 public Assembly [] Assemblies {
252                     get { return referenced_assemblies; }
253                 }
254
255                 public Module [] Modules {
256                         get { return modules; }
257                 }
258
259                 public void AddModuleReference (Module m)
260                 {
261                         int top = modules != null ? modules.Length : 0;
262                         Module [] n = new Module [top + 1];
263                         if (modules != null)
264                                 modules.CopyTo (n, 0);
265                         n [top] = m;
266                         modules = n;
267
268                         if (m == RootContext.ToplevelTypes.Builder)
269                                 return;
270
271                         foreach (Type t in m.GetTypes ())
272                                 RegisterNamespace (t.Namespace);
273                 }
274
275                 public void ComputeNamespaces (CompilerContext ctx)
276                 {
277                         //
278                         // Do very early lookup because type is required when we cache
279                         // imported extension types in ComputeNamespaces
280                         //
281                         Type extension_attribute_type = TypeManager.CoreLookupType (ctx, "System.Runtime.CompilerServices", "ExtensionAttribute", MemberKind.Class, false);
282
283                         foreach (RootNamespace rn in root_namespaces.Values) {
284                                 rn.ComputeNamespace (ctx, extension_attribute_type);
285                         }
286                 }
287
288                 public void DefineRootNamespace (string alias, Assembly assembly, CompilerContext ctx)
289                 {
290                         if (alias == alias_name) {
291                                 NamespaceEntry.Error_GlobalNamespaceRedefined (Location.Null, ctx.Report);
292                                 return;
293                         }
294
295                         RootNamespace retval = GetRootNamespace (alias);
296                         if (retval == null) {
297                                 retval = new RootNamespace (alias);
298                                 root_namespaces.Add (alias, retval);
299                         }
300
301                         retval.AddAssemblyReference (assembly);
302                 }
303
304                 public override void Error_NamespaceDoesNotExist (Location loc, string name, IMemberContext ctx)
305                 {
306                         ctx.Compiler.Report.Error (400, loc,
307                                 "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
308                                 name);
309                 }
310
311                 public RootNamespace GetRootNamespace (string name)
312                 {
313                         RootNamespace rn;
314                         if (!root_namespaces.TryGetValue (name, out rn))
315                                 return null;
316
317                         return rn;
318                 }
319
320                 public override Type LookupTypeReflection (CompilerContext ctx, string name, Location loc, bool must_be_unique)
321                 {
322                         Type found_type = base.LookupTypeReflection (ctx, name, loc, must_be_unique);
323
324                         if (modules != null) {
325                                 foreach (Module module in modules) {
326                                         Type t = module.GetType (name);
327                                         if (t == null)
328                                                 continue;
329
330                                         if (found_type == null) {
331                                                 found_type = t;
332                                                 continue;
333                                         }
334
335                                         ctx.Report.SymbolRelatedToPreviousError (found_type);
336                                         if (loc.IsNull) {
337                                                 DeclSpace ds = TypeManager.LookupDeclSpace (t);
338                                                 Error_AmbiguousPredefinedType (ctx, ds.Location, name, found_type);
339                                                 return found_type;
340                                         }
341                                         ctx.Report.SymbolRelatedToPreviousError (t);
342                                         ctx.Report.Warning (436, 2, loc, "The type `{0}' conflicts with the imported type `{1}'. Ignoring the imported type definition",
343                                                 TypeManager.CSharpName (t), TypeManager.CSharpName (found_type));
344                                         return t;
345                                 }
346                         }
347
348                         return found_type;
349                 }
350         }
351
352         /// <summary>
353         ///   Keeps track of the namespaces defined in the C# code.
354         ///
355         ///   This is an Expression to allow it to be referenced in the
356         ///   compiler parse/intermediate tree during name resolution.
357         /// </summary>
358         public class Namespace : FullNamedExpression {
359                 
360                 Namespace parent;
361                 string fullname;
362                 Dictionary<string, Namespace> namespaces;
363                 Dictionary<string, DeclSpace> declspaces;
364                 Dictionary<string, TypeExpr> cached_types;
365                 RootNamespace root;
366                 List<Type> external_exmethod_classes;
367
368                 public readonly MemberName MemberName;
369
370                 /// <summary>
371                 ///   Constructor Takes the current namespace and the
372                 ///   name.  This is bootstrapped with parent == null
373                 ///   and name = ""
374                 /// </summary>
375                 public Namespace (Namespace parent, string name)
376                 {
377                         // Expression members.
378                         this.eclass = ExprClass.Namespace;
379                         this.Type = typeof (Namespace);
380                         this.loc = Location.Null;
381
382                         this.parent = parent;
383
384                         if (parent != null)
385                                 this.root = parent.root;
386                         else
387                                 this.root = this as RootNamespace;
388
389                         if (this.root == null)
390                                 throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
391                         
392                         string pname = parent != null ? parent.fullname : "";
393                                 
394                         if (pname == "")
395                                 fullname = name;
396                         else
397                                 fullname = parent.fullname + "." + name;
398
399                         if (fullname == null)
400                                 throw new InternalErrorException ("Namespace has a null fullname");
401
402                         if (parent != null && parent.MemberName != MemberName.Null)
403                                 MemberName = new MemberName (parent.MemberName, name);
404                         else if (name.Length == 0)
405                                 MemberName = MemberName.Null;
406                         else
407                                 MemberName = new MemberName (name);
408
409                         namespaces = new Dictionary<string, Namespace> ();
410                         cached_types = new Dictionary<string, TypeExpr> ();
411
412                         root.RegisterNamespace (this);
413                 }
414
415                 protected override Expression DoResolve (ResolveContext ec)
416                 {
417                         return this;
418                 }
419
420                 public virtual void Error_NamespaceDoesNotExist (Location loc, string name, IMemberContext ctx)
421                 {
422                         if (name.IndexOf ('`') > 0) {
423                                 FullNamedExpression retval = Lookup (ctx.Compiler, SimpleName.RemoveGenericArity (name), loc);
424                                 if (retval != null) {
425                                         retval.Error_TypeArgumentsCannotBeUsed (ctx.Compiler.Report, loc);
426                                         return;
427                                 }
428                         } else {
429                                 Type t = LookForAnyGenericType (name);
430                                 if (t != null) {
431                                         Error_InvalidNumberOfTypeArguments (ctx.Compiler.Report, t, loc);
432                                         return;
433                                 }
434                         }
435
436                         ctx.Compiler.Report.Error (234, loc,
437                                 "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
438                                 name, GetSignatureForError ());
439                 }
440
441                 public static void Error_InvalidNumberOfTypeArguments (Report report, Type t, Location loc)
442                 {
443                         report.SymbolRelatedToPreviousError (t);
444                         report.Error (305, loc, "Using the generic type `{0}' requires `{1}' type argument(s)",
445                                 TypeManager.CSharpName(t), TypeManager.GetNumberOfTypeArguments(t).ToString());
446                 }
447
448                 public override string GetSignatureForError ()
449                 {
450                         return fullname;
451                 }
452                 
453                 public Namespace GetNamespace (string name, bool create)
454                 {
455                         int pos = name.IndexOf ('.');
456
457                         Namespace ns;
458                         string first;
459                         if (pos >= 0)
460                                 first = name.Substring (0, pos);
461                         else
462                                 first = name;
463
464                         if (!namespaces.TryGetValue (first, out ns)) {
465                                 if (!create)
466                                         return null;
467
468                                 ns = new Namespace (this, first);
469                                 namespaces.Add (first, ns);
470                         }
471
472                         if (pos >= 0)
473                                 ns = ns.GetNamespace (name.Substring (pos + 1), create);
474
475                         return ns;
476                 }
477
478                 public bool HasDefinition (string name)
479                 {
480                         return declspaces != null && declspaces.ContainsKey (name);
481                 }
482
483                 TypeExpr LookupType (CompilerContext ctx, string name, Location loc)
484                 {
485                         TypeExpr te;
486                         if (cached_types.TryGetValue (name, out te))
487                                 return te;
488
489                         Type t = null;
490                         if (declspaces != null) {
491                                 DeclSpace tdecl;
492                                 if (declspaces.TryGetValue (name, out tdecl)) {
493                                         //
494                                         // Note that this is not:
495                                         //
496                                         //   t = tdecl.DefineType ()
497                                         //
498                                         // This is to make it somewhat more useful when a DefineType
499                                         // fails due to problems in nested types (more useful in the sense
500                                         // of fewer misleading error messages)
501                                         //
502                                         tdecl.DefineType ();
503                                         t = tdecl.TypeBuilder;
504
505                                         if (RootContext.EvalMode){
506                                                 // Replace the TypeBuilder with a System.Type, as
507                                                 // Reflection.Emit fails otherwise (we end up pretty
508                                                 // much with Random type definitions later on).
509                                                 Type tt = t.Assembly.GetType (t.Name);
510                                                 if (tt != null)
511                                                         t = tt;
512                                         }
513                                 }
514                         }
515                         string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
516                         Type rt = root.LookupTypeReflection (ctx, lookup, loc, t == null);
517
518                         // HACK: loc.IsNull when the type is core type
519                         if (t == null || (rt != null && loc.IsNull))
520                                 t = rt;
521
522                         te = t == null ? null : new TypeExpression (t, Location.Null);
523                         cached_types [name] = te;
524                         return te;
525                 }
526
527                 ///
528                 /// Used for better error reporting only
529                 /// 
530                 public Type LookForAnyGenericType (string typeName)
531                 {
532                         if (declspaces == null)
533                                 return null;
534
535                         typeName = SimpleName.RemoveGenericArity (typeName);
536
537                         foreach (var de in declspaces) {
538                                 string type_item = de.Key;
539                                 int pos = type_item.LastIndexOf ('`');
540                                 if (pos == typeName.Length && String.Compare (typeName, 0, type_item, 0, pos) == 0)
541                                         return de.Value.TypeBuilder;
542                         }
543                         return null;
544                 }
545
546                 public FullNamedExpression Lookup (CompilerContext ctx, string name, Location loc)
547                 {
548                         if (namespaces.ContainsKey (name))
549                                 return namespaces [name];
550
551                         return LookupType (ctx, name, loc);
552                 }
553
554                 //
555                 // Completes types with the given `prefix' and stores the results in `result'
556                 //
557                 public void CompletionGetTypesStartingWith (string prefix, Dictionary<string, string> result)
558                 {
559                         int l = fullname.Length + 1;
560                         var res = root.CompletionGetTypesStartingWith (fullname + "." + prefix);
561
562                         if (res == null)
563                                 return;
564                         
565                         foreach (string match in res){
566                                 string x = match.Substring (l);
567
568                                 // Turn reflection nested classes foo+bar into foo.bar
569                                 x = x.Replace ('+', '.');
570
571                                 // Only get the first name element, no point in adding anything beyond the first dot.
572                                 int p = x.IndexOf ('.');
573                                 if (p != -1)
574                                         x = x.Substring (0, p);
575
576                                 // Turn Foo`N into Foo<
577                                 p = x.IndexOf ('`');
578                                 if (p != -1)
579                                         x = x.Substring (0, p) + "<";
580
581                                 if (!result.ContainsKey (x))
582                                         result [x] = x;
583                         }
584                 }
585
586                 public void RegisterExternalExtensionMethodClass (Type type)
587                 {
588                         // Ignore, extension methods cannot be nested
589                         if (type.DeclaringType != null)
590                                 return;
591
592                         // TODO: CodeGen.Assembly.Builder is global
593                         if (type.IsNotPublic && !TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, type.Assembly))
594                                 return;
595
596                         if (external_exmethod_classes == null)
597                                 external_exmethod_classes = new List<Type> ();
598
599                         external_exmethod_classes.Add (type);
600                 }
601
602                 /// 
603                 /// Looks for extension method in this namespace
604                 /// 
605                 public List<MethodSpec> LookupExtensionMethod (Type extensionType, ClassOrStruct currentClass, string name)
606                 {
607                         List<MethodSpec> found = null;
608
609                         // TODO: problematic
610                         var invocation_assembly = CodeGen.Assembly.Builder;
611
612                         if (declspaces != null) {
613                                 var e = declspaces.Values.GetEnumerator ();
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                                         var res = c.MemberCache.FindExtensionMethods (invocation_assembly, 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                                 var res = m.FindExtensionMethods (invocation_assembly, 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 Dictionary<string, DeclSpace> ();
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 : IMemberContext {
683
684                 public 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 (IMemberContext 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                                         rc.Compiler.Report.SymbolRelatedToPreviousError (fne.Type);
722                                         rc.Compiler.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                 public 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 (IMemberContext rc)
746                         {
747                                 FullNamedExpression fne = GlobalRootNamespace.Instance.GetRootNamespace (Alias);
748                                 if (fne == null) {
749                                         rc.Compiler.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 (IMemberContext rc)
775                         {
776                                 if (resolved != null || value == null)
777                                         return resolved;
778
779                                 if (rc == null)
780                                         return null;
781
782                                 resolved = value.GetTypeExpression ().ResolveAsTypeStep (rc, false);
783                                 if (resolved == null) {
784                                         value = null;
785                                         return null;
786                                 }
787
788                                 if (resolved is TypeExpr)
789                                         resolved = resolved.ResolveAsBaseTerminal (rc, false);
790
791                                 return resolved;
792                         }
793
794                         public override string ToString ()
795                         {
796                                 return String.Format ("{0} = {1}", Alias, value.GetSignatureForError ());
797                         }
798                 }
799
800                 Namespace ns;
801                 NamespaceEntry parent, implicit_parent;
802                 CompilationUnit file;
803                 int symfile_id;
804
805                 // Namespace using import block
806                 List<UsingAliasEntry> using_aliases;
807                 List<UsingEntry> using_clauses;
808                 public bool DeclarationFound;
809                 // End
810
811                 public readonly bool IsImplicit;
812                 public readonly DeclSpace SlaveDeclSpace;
813                 static readonly Namespace [] empty_namespaces = new Namespace [0];
814                 Namespace [] namespace_using_table;
815
816                 static List<NamespaceEntry> entries = new List<NamespaceEntry> ();
817
818                 public static void Reset ()
819                 {
820                         entries = new List<NamespaceEntry> ();
821                 }
822
823                 public NamespaceEntry (NamespaceEntry parent, CompilationUnit file, string name)
824                 {
825                         this.parent = parent;
826                         this.file = file;
827                         entries.Add (this);
828
829                         if (parent != null)
830                                 ns = parent.NS.GetNamespace (name, true);
831                         else if (name != null)
832                                 ns = GlobalRootNamespace.Instance.GetNamespace (name, true);
833                         else
834                                 ns = GlobalRootNamespace.Instance;
835                         SlaveDeclSpace = new RootDeclSpace (this);
836                 }
837
838                 private NamespaceEntry (NamespaceEntry parent, CompilationUnit file, Namespace ns, bool slave)
839                 {
840                         this.parent = parent;
841                         this.file = file;
842                         this.IsImplicit = true;
843                         this.ns = ns;
844                         this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
845                 }
846
847                 //
848                 // Populates the Namespace with some using declarations, used by the
849                 // eval mode. 
850                 //
851                 public void Populate (List<UsingAliasEntry> source_using_aliases, List<UsingEntry> source_using_clauses)
852                 {
853                         foreach (UsingAliasEntry uae in source_using_aliases){
854                                 if (using_aliases == null)
855                                         using_aliases = new List<UsingAliasEntry> ();
856                                 
857                                 using_aliases.Add (uae);
858                         }
859
860                         foreach (UsingEntry ue in source_using_clauses){
861                                 if (using_clauses == null)
862                                         using_clauses = new List<UsingEntry> ();
863                                 
864                                 using_clauses.Add (ue);
865                         }
866                 }
867
868                 //
869                 // Extracts the using alises and using clauses into a couple of
870                 // arrays that might already have the same information;  Used by the
871                 // C# Eval mode.
872                 //
873                 public void Extract (List<UsingAliasEntry> out_using_aliases, List<UsingEntry> out_using_clauses)
874                 {
875                         if (using_aliases != null){
876                                 foreach (UsingAliasEntry uae in using_aliases){
877                                         bool replaced = false;
878                                         
879                                         for (int i = 0; i < out_using_aliases.Count; i++){
880                                                 UsingAliasEntry out_uea = (UsingAliasEntry) out_using_aliases [i];
881                                                 
882                                                 if (out_uea.Alias == uae.Alias){
883                                                         out_using_aliases [i] = uae;
884                                                         replaced = true;
885                                                         break;
886                                                 }
887                                         }
888                                         if (!replaced)
889                                                 out_using_aliases.Add (uae);
890                                 }
891                         }
892
893                         if (using_clauses != null){
894                                 foreach (UsingEntry ue in using_clauses){
895                                         bool found = false;
896                                         
897                                         foreach (UsingEntry out_ue in out_using_clauses)
898                                                 if (out_ue.Name == ue.Name){
899                                                         found = true;
900                                                         break;
901                                                 }
902                                         if (!found)
903                                                 out_using_clauses.Add (ue);
904                                 }
905                         }
906                 }
907                 
908                 //
909                 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
910                 // resolved as if the immediately containing namespace body has no using-directives.
911                 //
912                 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
913                 // in the using-namespace-directive.
914                 //
915                 // To implement these rules, the expressions in the using directives are resolved using 
916                 // the "doppelganger" (ghostly bodiless duplicate).
917                 //
918                 NamespaceEntry doppelganger;
919                 NamespaceEntry Doppelganger {
920                         get {
921                                 if (!IsImplicit && doppelganger == null) {
922                                         doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
923                                         doppelganger.using_aliases = using_aliases;
924                                 }
925                                 return doppelganger;
926                         }
927                 }
928
929                 public Namespace NS {
930                         get { return ns; }
931                 }
932
933                 public NamespaceEntry Parent {
934                         get { return parent; }
935                 }
936
937                 public NamespaceEntry ImplicitParent {
938                         get {
939                                 if (parent == null)
940                                         return null;
941                                 if (implicit_parent == null) {
942                                         implicit_parent = (parent.NS == ns.Parent)
943                                                 ? parent
944                                                 : new NamespaceEntry (parent, file, ns.Parent, false);
945                                 }
946                                 return implicit_parent;
947                         }
948                 }
949
950                 /// <summary>
951                 ///   Records a new namespace for resolving name references
952                 /// </summary>
953                 public void AddUsing (MemberName name, Location loc)
954                 {
955                         if (DeclarationFound){
956                                 Compiler.Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
957                         }
958
959                         if (using_clauses == null) {
960                                 using_clauses = new List<UsingEntry> ();
961                         } else {
962                                 foreach (UsingEntry old_entry in using_clauses) {
963                                         if (name.Equals (old_entry.MemberName)) {
964                                                 Compiler.Report.SymbolRelatedToPreviousError (old_entry.Location, old_entry.GetSignatureForError ());
965                                                 Compiler.Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetSignatureForError ());
966                                                 return;
967                                         }
968                                 }
969                         }
970
971                         using_clauses.Add (new UsingEntry (name));
972                 }
973
974                 public void AddUsingAlias (string alias, MemberName name, Location loc)
975                 {
976                         // TODO: This is parser bussines
977                         if (DeclarationFound){
978                                 Compiler.Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
979                         }
980
981                         if (RootContext.Version != LanguageVersion.ISO_1 && alias == "global")
982                                 Compiler.Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
983                                         " the global namespace will be used instead");
984
985                         AddUsingAlias (new LocalUsingAliasEntry (alias, name, loc));
986                 }
987
988                 public void AddUsingExternalAlias (string alias, Location loc, Report Report)
989                 {
990                         // TODO: Do this in parser
991                         bool not_first = using_clauses != null || DeclarationFound;
992                         if (using_aliases != null && !not_first) {
993                                 foreach (UsingAliasEntry uae in using_aliases) {
994                                         if (uae is LocalUsingAliasEntry) {
995                                                 not_first = true;
996                                                 break;
997                                         }
998                                 }
999                         }
1000
1001                         if (not_first)
1002                                 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
1003
1004                         if (alias == "global") {
1005                                 Error_GlobalNamespaceRedefined (loc, Report);
1006                                 return;
1007                         }
1008
1009                         AddUsingAlias (new UsingAliasEntry (alias, loc));
1010                 }
1011
1012                 void AddUsingAlias (UsingAliasEntry uae)
1013                 {
1014                         if (using_aliases == null) {
1015                                 using_aliases = new List<UsingAliasEntry> ();
1016                         } else {
1017                                 foreach (UsingAliasEntry entry in using_aliases) {
1018                                         if (uae.Alias == entry.Alias) {
1019                                                 Compiler.Report.SymbolRelatedToPreviousError (uae.Location, uae.Alias);
1020                                                 Compiler.Report.Error (1537, entry.Location, "The using alias `{0}' appeared previously in this namespace",
1021                                                         entry.Alias);
1022                                                 return;
1023                                         }
1024                                 }
1025                         }
1026
1027                         using_aliases.Add (uae);
1028                 }
1029
1030                 ///
1031                 /// Does extension methods look up to find a method which matches name and extensionType.
1032                 /// Search starts from this namespace and continues hierarchically up to top level.
1033                 ///
1034                 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
1035                 {
1036                         List<MethodSpec> candidates = null;
1037                         foreach (Namespace n in GetUsingTable ()) {
1038                                 var a = n.LookupExtensionMethod (extensionType, null, name);
1039                                 if (a == null)
1040                                         continue;
1041
1042                                 if (candidates == null)
1043                                         candidates = a;
1044                                 else
1045                                         candidates.AddRange (a);
1046                         }
1047
1048                         if (candidates != null)
1049                                 return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
1050
1051                         if (parent == null)
1052                                 return null;
1053
1054                         //
1055                         // Inspect parent namespaces in namespace expression
1056                         //
1057                         Namespace parent_ns = ns.Parent;
1058                         do {
1059                                 candidates = parent_ns.LookupExtensionMethod (extensionType, null, name);
1060                                 if (candidates != null)
1061                                         return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
1062
1063                                 parent_ns = parent_ns.Parent;
1064                         } while (parent_ns != null);
1065
1066                         //
1067                         // Continue in parent scope
1068                         //
1069                         return parent.LookupExtensionMethod (extensionType, name, loc);
1070                 }
1071
1072                 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
1073                 {
1074                         // Precondition: Only simple names (no dots) will be looked up with this function.
1075                         FullNamedExpression resolved = null;
1076                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
1077                                 if ((resolved = curr_ns.Lookup (name, loc, ignore_cs0104)) != null)
1078                                         break;
1079                         }
1080                         return resolved;
1081                 }
1082
1083                 public ICollection<string> CompletionGetTypesStartingWith (string prefix)
1084                 {
1085                         var result = new Dictionary<string, string> ();
1086                         
1087                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent){
1088                                 foreach (Namespace using_ns in GetUsingTable ()){
1089                                         if (prefix.StartsWith (using_ns.Name)){
1090                                                 int ld = prefix.LastIndexOf ('.');
1091                                                 if (ld != -1){
1092                                                         string rest = prefix.Substring (ld+1);
1093
1094                                                         using_ns.CompletionGetTypesStartingWith (rest, result);
1095                                                 }
1096                                         }
1097                                         using_ns.CompletionGetTypesStartingWith (prefix, result);
1098                                 }
1099                         }
1100
1101                         return result.Keys;
1102                 }
1103                 
1104                 void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
1105                 {
1106                         Compiler.Report.SymbolRelatedToPreviousError (t1.Type);
1107                         Compiler.Report.SymbolRelatedToPreviousError (t2.Type);
1108                         Compiler.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 LookupNamespaceAlias (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 (string name, Location loc, bool ignore_cs0104)
1129                 {
1130                         //
1131                         // Check whether it's in the namespace.
1132                         //
1133                         FullNamedExpression fne = ns.Lookup (Compiler, 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                                                                 Compiler.Report.SymbolRelatedToPreviousError (ue.Location, null);
1146                                                                 Compiler.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 (Compiler, 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                         var list = new List<Namespace> (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 = list.ToArray ();
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, Report Report)
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, Report Report)
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 IMemberContext Members
1309
1310                 public CompilerContext Compiler {
1311                         get { return RootContext.ToplevelTypes.Compiler; }
1312                 }
1313
1314                 public Type CurrentType {
1315                         get { return SlaveDeclSpace.CurrentType; }
1316                 }
1317
1318                 public TypeContainer CurrentTypeDefinition {
1319                         get { return SlaveDeclSpace.CurrentTypeDefinition; }
1320                 }
1321
1322                 public TypeParameter[] CurrentTypeParameters {
1323                         get { return SlaveDeclSpace.CurrentTypeParameters; }
1324                 }
1325
1326                 public bool IsObsolete {
1327                         get { return SlaveDeclSpace.IsObsolete; }
1328                 }
1329
1330                 public bool IsUnsafe {
1331                         get { return SlaveDeclSpace.IsUnsafe; }
1332                 }
1333
1334                 public bool IsStatic {
1335                         get { return SlaveDeclSpace.IsStatic; }
1336                 }
1337
1338                 #endregion
1339         }
1340 }