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