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