**** Merged r47302 from MCS ****
[mono.git] / mcs / gmcs / namespace.cs
1 //
2 // namespace.cs: Tracks namespaces
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc.
8 //
9 using System;
10 using System.Collections;
11
12 namespace Mono.CSharp {
13
14         /// <summary>
15         ///   Keeps track of the namespaces defined in the C# code.
16         ///
17         ///   This is an Expression to allow it to be referenced in the
18         ///   compiler parse/intermediate tree during name resolution.
19         /// </summary>
20         public class Namespace : FullNamedExpression {
21                 static ArrayList all_namespaces;
22                 static Hashtable namespaces_map;
23                 
24                 Namespace parent;
25                 string fullname;
26                 ArrayList entries;
27                 Hashtable namespaces;
28                 Hashtable declspaces;
29                 Hashtable cached_types;
30
31                 public readonly MemberName MemberName;
32
33                 public static Namespace Root;
34
35                 static Namespace ()
36                 {
37                         Reset ();
38                 }
39
40                 public static void Reset ()
41                 {
42                         all_namespaces = new ArrayList ();
43                         namespaces_map = new Hashtable ();
44
45                         Root = new Namespace (null, "");
46                 }
47
48                 /// <summary>
49                 ///   Constructor Takes the current namespace and the
50                 ///   name.  This is bootstrapped with parent == null
51                 ///   and name = ""
52                 /// </summary>
53                 public Namespace (Namespace parent, string name)
54                 {
55                         // Expression members.
56                         this.eclass = ExprClass.Namespace;
57                         this.Type = null;
58                         this.loc = Location.Null;
59
60                         this.parent = parent;
61
62                         string pname = parent != null ? parent.Name : "";
63                                 
64                         if (pname == "")
65                                 fullname = name;
66                         else
67                                 fullname = parent.Name + "." + name;
68
69                         if (parent != null && parent.MemberName != MemberName.Null)
70                                 MemberName = new MemberName (parent.MemberName, name);
71                         else if (name == "")
72                                 MemberName = MemberName.Null;
73                         else
74                                 MemberName = new MemberName (name);
75
76                         entries = new ArrayList ();
77                         namespaces = new Hashtable ();
78                         declspaces = new Hashtable ();
79                         cached_types = new Hashtable ();
80
81                         all_namespaces.Add (this);
82                         if (namespaces_map.Contains (fullname))
83                                 return;
84                         namespaces_map [fullname] = true;
85                 }
86
87                 public override Expression DoResolve (EmitContext ec)
88                 {
89                         return this;
90                 }
91
92                 public override void Emit (EmitContext ec)
93                 {
94                         throw new InternalErrorException ("Expression tree referenced namespace " + fullname + " during Emit ()");
95                 }
96
97                 public static bool IsNamespace (string name)
98                 {
99                         return namespaces_map [name] != null;
100                 }
101
102                 public override string GetSignatureForError ()
103                 {
104                         return Name.Length == 0 ? "::global" : Name;
105                 }
106                 
107                 public Namespace GetNamespace (string name, bool create)
108                 {
109                         int pos = name.IndexOf ('.');
110
111                         Namespace ns;
112                         string first;
113                         if (pos >= 0)
114                                 first = name.Substring (0, pos);
115                         else
116                                 first = name;
117
118                         ns = (Namespace) namespaces [first];
119                         if (ns == null) {
120                                 if (!create)
121                                         return null;
122
123                                 ns = new Namespace (this, first);
124                                 namespaces.Add (first, ns);
125                         }
126
127                         if (pos >= 0)
128                                 ns = ns.GetNamespace (name.Substring (pos + 1), create);
129
130                         return ns;
131                 }
132
133                 public static Namespace LookupNamespace (string name, bool create)
134                 {
135                         return Root.GetNamespace (name, create);
136                 }
137
138                 public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
139                 {
140                         Namespace ns = GetNamespace (name, false);
141                         if (ns != null)
142                                 return ns;
143
144                         TypeExpr te;
145                         if (cached_types.Contains (name)) {
146                                 te = (TypeExpr) cached_types [name];
147                         } else {
148                                 Type t;
149                                 DeclSpace tdecl = declspaces [name] as DeclSpace;
150                                 if (tdecl != null) {
151                                         //
152                                         // Note that this is not:
153                                         //
154                                         //   t = tdecl.DefineType ()
155                                         //
156                                         // This is to make it somewhat more useful when a DefineType
157                                         // fails due to problems in nested types (more useful in the sense
158                                         // of fewer misleading error messages)
159                                         //
160                                         tdecl.DefineType ();
161                                         t = tdecl.TypeBuilder;
162                                 } else {
163                                         string lookup = this == Namespace.Root ? name : fullname + "." + name;
164                                         t = TypeManager.LookupTypeReflection (lookup);
165                                 }
166                                 te = t == null ? null : new TypeExpression (t, Location.Null);
167                                 cached_types [name] = te;
168                         }
169
170                         if (te != null && ds != null && !ds.CheckAccessLevel (te.Type))
171                                 return null;
172
173                         return te;
174                 }
175
176                 public void AddNamespaceEntry (NamespaceEntry entry)
177                 {
178                         entries.Add (entry);
179                 }
180
181                 public void AddDeclSpace (string name, DeclSpace ds)
182                 {
183                         declspaces.Add (name, ds);
184                 }
185
186                 static public ArrayList UserDefinedNamespaces {
187                         get { return all_namespaces; }
188                 }
189
190                 /// <summary>
191                 ///   The qualified name of the current namespace
192                 /// </summary>
193                 public string Name {
194                         get { return fullname; }
195                 }
196
197                 public override string FullName {
198                         get { return fullname; }
199                 }
200
201                 /// <summary>
202                 ///   The parent of this namespace, used by the parser to "Pop"
203                 ///   the current namespace declaration
204                 /// </summary>
205                 public Namespace Parent {
206                         get { return parent; }
207                 }
208
209                 public static void DefineNamespaces (SymbolWriter symwriter)
210                 {
211                         foreach (Namespace ns in all_namespaces) {
212                                 foreach (NamespaceEntry entry in ns.entries)
213                                         entry.DefineNamespace (symwriter);
214                         }
215                 }
216
217                 /// <summary>
218                 ///   Used to validate that all the using clauses are correct
219                 ///   after we are finished parsing all the files.  
220                 /// </summary>
221                 public static void VerifyUsing ()
222                 {
223                         foreach (Namespace ns in all_namespaces) {
224                                 foreach (NamespaceEntry entry in ns.entries)
225                                         entry.VerifyUsing ();
226                         }
227                 }
228
229                 public override string ToString ()
230                 {
231                         if (this == Root)
232                                 return "Namespace (<root>)";
233                         else
234                                 return String.Format ("Namespace ({0})", Name);
235                 }
236         }
237
238         public class NamespaceEntry
239         {
240                 Namespace ns;
241                 NamespaceEntry parent, implicit_parent;
242                 SourceFile file;
243                 int symfile_id;
244                 Hashtable aliases;
245                 ArrayList using_clauses;
246                 public bool DeclarationFound = false;
247
248                 //
249                 // This class holds the location where a using definition is
250                 // done, and whether it has been used by the program or not.
251                 //
252                 // We use this to flag using clauses for namespaces that do not
253                 // exist.
254                 //
255                 public class UsingEntry {
256                         public MemberName Name;
257                         public Expression Expr;
258                         public readonly NamespaceEntry NamespaceEntry;
259                         public readonly Location Location;
260                         
261                         public UsingEntry (NamespaceEntry entry, MemberName name, Location loc)
262                         {
263                                 Name = name;
264                                 Expr = name.GetTypeExpression (loc);
265                                 NamespaceEntry = entry;
266                                 Location = loc;
267                         }
268
269                         internal FullNamedExpression resolved;
270
271                         public Namespace Resolve ()
272                         {
273                                 if (resolved != null)
274                                         return resolved as Namespace;
275
276                                 DeclSpace root = RootContext.Tree.Types;
277                                 root.NamespaceEntry = NamespaceEntry;
278                                 resolved = Expr.ResolveAsTypeStep (root.EmitContext);
279                                 root.NamespaceEntry = null;
280
281                                 return resolved as Namespace;
282                         }
283                 }
284
285                 public class AliasEntry {
286                         public readonly string Name;
287                         public readonly Expression Alias;
288                         public readonly NamespaceEntry NamespaceEntry;
289                         public readonly Location Location;
290                         
291                         public AliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc)
292                         {
293                                 Name = name;
294                                 Alias = alias.GetTypeExpression (loc);
295                                 NamespaceEntry = entry;
296                                 Location = loc;
297                         }
298
299                         FullNamedExpression resolved;
300
301                         public FullNamedExpression Resolve ()
302                         {
303                                 if (resolved != null)
304                                         return resolved;
305
306                                 DeclSpace root = RootContext.Tree.Types;
307                                 root.NamespaceEntry = NamespaceEntry;
308                                 resolved = Alias.ResolveAsTypeStep (root.EmitContext);
309                                 root.NamespaceEntry = null;
310
311                                 return resolved;
312                         }
313                 }
314
315                 public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name, Location loc)
316                 {
317                         this.parent = parent;
318                         this.file = file;
319                         this.IsImplicit = false;
320                         this.ID = ++next_id;
321
322                         if (parent != null)
323                                 ns = parent.NS.GetNamespace (name, true);
324                         else if (name != null)
325                                 ns = Namespace.LookupNamespace (name, true);
326                         else
327                                 ns = Namespace.Root;
328                         ns.AddNamespaceEntry (this);
329                 }
330
331
332                 private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns)
333                 {
334                         this.parent = parent;
335                         this.file = file;
336                         this.IsImplicit = true;
337                         this.ID = ++next_id;
338                         this.ns = ns;
339                 }
340
341                 //
342                 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
343                 // resolved as if the immediately containing namespace body has no using-directives.
344                 //
345                 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
346                 // in the using-namespace-directive.
347                 //
348                 // To implement these rules, the expressions in the using directives are resolved using 
349                 // the "doppelganger" (ghostly bodiless duplicate).
350                 //
351                 NamespaceEntry doppelganger;
352                 NamespaceEntry Doppelganger {
353                         get {
354                                 if (!IsImplicit && doppelganger == null)
355                                         doppelganger = new NamespaceEntry (ImplicitParent, file, ns);
356                                 return doppelganger;
357                         }
358                 }
359
360                 static int next_id = 0;
361                 public readonly int ID;
362                 public readonly bool IsImplicit;
363
364                 public Namespace NS {
365                         get {
366                                 return ns;
367                         }
368                 }
369
370                 public NamespaceEntry Parent {
371                         get {
372                                 return parent;
373                         }
374                 }
375
376                 public NamespaceEntry ImplicitParent {
377                         get {
378                                 if (parent == null)
379                                         return null;
380                                 if (implicit_parent == null) {
381                                         implicit_parent = (parent.NS == ns.Parent)
382                                                 ? parent
383                                                 : new NamespaceEntry (parent, file, ns.Parent);
384                                 }
385                                 return implicit_parent;
386                         }
387                 }
388
389                 /// <summary>
390                 ///   Records a new namespace for resolving name references
391                 /// </summary>
392                 public void Using (MemberName name, Location loc)
393                 {
394                         if (DeclarationFound){
395                                 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
396                                 return;
397                         }
398
399                         if (name.Equals (ns.MemberName))
400                                 return;
401                         
402                         if (using_clauses == null)
403                                 using_clauses = new ArrayList ();
404
405                         foreach (UsingEntry old_entry in using_clauses) {
406                                 if (name.Equals (old_entry.Name)) {
407                                         if (RootContext.WarningLevel >= 3)
408                                                 Report.Warning (105, loc, "The using directive for `{0}' appeared previously in this namespace", name);
409                                                 return;
410                                         }
411                                 }
412
413
414                         UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
415                         using_clauses.Add (ue);
416                 }
417
418                 public void UsingAlias (string name, MemberName alias, Location loc)
419                 {
420                         if (DeclarationFound){
421                                 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
422                                 return;
423                         }
424
425                         if (aliases == null)
426                                 aliases = new Hashtable ();
427
428                         if (aliases.Contains (name)){
429                                 AliasEntry ae = (AliasEntry)aliases [name];
430                                 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
431                                 Report.Error (1537, loc, "The using alias `" + name +
432                                               "' appeared previously in this namespace");
433                                 return;
434                         }
435
436                         aliases [name] = new AliasEntry (Doppelganger, name, alias, loc);
437                 }
438
439                 public FullNamedExpression LookupAlias (string alias)
440                 {
441                         AliasEntry entry = null;
442                         if (aliases != null)
443                                 entry = (AliasEntry) aliases [alias];
444
445                         return entry == null ? null : entry.Resolve ();
446                 }
447
448                 static readonly char [] dot_array = { '.' };
449
450                 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
451                 {
452                         FullNamedExpression resolved = null;
453                         string rest = null;
454
455                         // If name is of the form `N.I', first lookup `N', then search a member `I' in it.
456                         int pos = name.IndexOf ('.');
457                         if (pos >= 0) {
458                                 rest = name.Substring (pos + 1);
459                                 name = name.Substring (0, pos);
460                         }
461
462                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
463                                 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
464                                         break;
465                         }
466
467                         if (resolved == null || rest == null)
468                                 return resolved;
469
470                         // Now handle the rest of the the name.
471                         string [] elements = rest.Split (dot_array);
472                         int count = elements.Length;
473                         int i = 0;
474                         while (i < count && resolved != null && resolved is Namespace) {
475                                 Namespace ns = resolved as Namespace;
476                                 resolved = ns.Lookup (ds, elements [i++], loc);
477                         }
478
479                         if (resolved == null || resolved is Namespace)
480                                 return resolved;
481
482                         Type t = ((TypeExpr) resolved).Type;
483                         
484                         while (t != null) {
485                                 if (ds != null && !ds.CheckAccessLevel (t))
486                                         break;
487                                 if (i == count)
488                                         return new TypeExpression (t, Location.Null);
489                                 t = TypeManager.GetNestedType (t, elements [i++]);
490                         }
491
492                         return null;
493                 }
494
495                 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
496                 {
497                         // Precondition: Only simple names (no dots) will be looked up with this function.
498
499                         //
500                         // Check whether it's in the namespace.
501                         //
502                         FullNamedExpression o = NS.Lookup (ds, name, loc);
503                         if (o != null)
504                                 return o;
505
506                         if (IsImplicit)
507                                 return null;
508
509                         //
510                         // Check aliases.
511                         //
512                         o = LookupAlias (name);
513                         if (o != null)
514                                 return o;
515
516                         //
517                         // Check using entries.
518                         //
519                         FullNamedExpression t = null, match = null;
520                         foreach (Namespace using_ns in GetUsingTable ()) {
521                                 match = using_ns.Lookup (ds, name, loc);
522                                 if ((match != null) && (match is TypeExpr)) {
523                                         if (t != null) {
524                                                 if (!ignore_cs0104)
525                                                         DeclSpace.Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
526                                                 
527                                                 return null;
528                                         } else {
529                                                 t = match;
530                                         }
531                                 }
532                         }
533
534                         return t;
535                 }
536
537                 // Our cached computation.
538                 Namespace [] namespace_using_table;
539                 public Namespace[] GetUsingTable ()
540                 {
541                         if (namespace_using_table != null)
542                                 return namespace_using_table;
543
544                         if (using_clauses == null) {
545                                 namespace_using_table = new Namespace [0];
546                                 return namespace_using_table;
547                         }
548
549                         ArrayList list = new ArrayList (using_clauses.Count);
550
551                         foreach (UsingEntry ue in using_clauses) {
552                                 Namespace using_ns = ue.Resolve ();
553                                 if (using_ns == null)
554                                         continue;
555
556                                 list.Add (using_ns);
557                         }
558
559                         namespace_using_table = new Namespace [list.Count];
560                         list.CopyTo (namespace_using_table, 0);
561                         return namespace_using_table;
562                 }
563
564                 public void DefineNamespace (SymbolWriter symwriter)
565                 {
566                         if (symfile_id != 0)
567                                 return;
568                         if (parent != null)
569                                 parent.DefineNamespace (symwriter);
570
571                         string[] using_list;
572                         if (using_clauses != null) {
573                                 using_list = new string [using_clauses.Count];
574                                 for (int i = 0; i < using_clauses.Count; i++)
575                                         using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
576                         } else {
577                                 using_list = new string [0];
578                         }
579
580                         int parent_id = parent != null ? parent.symfile_id : 0;
581                         if (file.SourceFileEntry == null)
582                                 return;
583
584                         symfile_id = symwriter.DefineNamespace (
585                                 ns.Name, file.SourceFileEntry, using_list, parent_id);
586                 }
587
588                 public int SymbolFileID {
589                         get {
590                                 return symfile_id;
591                         }
592                 }
593
594                 static void MsgtryRef (string s)
595                 {
596                         Console.WriteLine ("    Try using -r:" + s);
597                 }
598                 
599                 static void MsgtryPkg (string s)
600                 {
601                         Console.WriteLine ("    Try using -pkg:" + s);
602                 }
603
604                 public static void Error_NamespaceNotFound (Location loc, string name)
605                 {
606                         Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
607                                 name);
608
609                         switch (name) {
610                         case "Gtk": case "GtkSharp":
611                                 MsgtryPkg ("gtk-sharp");
612                                 break;
613
614                         case "Gdk": case "GdkSharp":
615                                 MsgtryPkg ("gdk-sharp");
616                                 break;
617
618                         case "Glade": case "GladeSharp":
619                                 MsgtryPkg ("glade-sharp");
620                                 break;
621
622                         case "System.Drawing":
623                         case "System.Web.Services":
624                         case "System.Web":
625                         case "System.Data":
626                         case "System.Windows.Forms":
627                                 MsgtryRef (name);
628                                 break;
629                         }
630                 }
631
632                 /// <summary>
633                 ///   Used to validate that all the using clauses are correct
634                 ///   after we are finished parsing all the files.  
635                 /// </summary>
636                 public void VerifyUsing ()
637                 {
638                         if (using_clauses != null){
639                                 foreach (UsingEntry ue in using_clauses){
640                                         if (ue.Resolve () != null)
641                                                 continue;
642
643                                         if (ue.resolved == null)
644                                                 Error_NamespaceNotFound (ue.Location, ue.Name.ToString ());
645                                         else
646                                                 Report.Error (138, ue.Location,
647                                                         "`{0} is a type not a namespace. A using namespace directive can only be applied to namespaces", ue.Name);
648
649                                 }
650                         }
651
652                         if (aliases != null){
653                                 foreach (DictionaryEntry de in aliases){
654                                         AliasEntry alias = (AliasEntry) de.Value;
655
656                                         if (alias.Resolve () != null)
657                                                 continue;
658
659                                         Error_NamespaceNotFound (alias.Location, alias.Alias.ToString ());
660                                 }
661                         }
662                 }
663
664                 public override string ToString ()
665                 {
666                         if (NS == Namespace.Root)
667                                 return "NamespaceEntry (<root>)";
668                         else
669                                 return String.Format ("NamespaceEntry ({0},{1},{2})", ns.Name, IsImplicit, ID);
670                 }
671         }
672 }