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