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