Fix #73282.
[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                                 //
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                                 AliasEntry ae = (AliasEntry)aliases [name];
425                                 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
426                                 Report.Error (1537, loc, "The using alias `" + name +
427                                               "' appeared previously in this namespace");
428                                 return;
429                         }
430
431                         aliases [name] = new AliasEntry (Doppelganger, name, alias, loc);
432                 }
433
434                 public FullNamedExpression LookupAlias (string alias)
435                 {
436                         AliasEntry entry = null;
437                         if (aliases != null)
438                                 entry = (AliasEntry) aliases [alias];
439
440                         return entry == null ? null : entry.Resolve ();
441                 }
442
443                 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
444                 {
445                         FullNamedExpression resolved = null;
446                         string rest = null;
447
448                         // If name is of the form `N.I', first lookup `N', then search a member `I' in it.
449                         int pos = name.IndexOf ('.');
450                         if (pos >= 0) {
451                                 rest = name.Substring (pos + 1);
452                                 name = name.Substring (0, pos);
453                         }
454
455                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
456                                 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
457                                         break;
458                         }
459
460                         if (resolved == null || rest == null)
461                                 return resolved;
462
463                         Namespace ns = resolved as Namespace;
464                         if (ns != null)
465                                 return ns.Lookup (ds, rest, loc);
466
467                         Type nested = TypeManager.LookupType (resolved.FullName + "." + rest);
468                         if ((nested == null) || ((ds != null) && !ds.CheckAccessLevel (nested)))
469                                 return null;
470
471                         return new TypeExpression (nested, Location.Null);
472                 }
473
474                 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
475                 {
476                         // Precondition: Only simple names (no dots) will be looked up with this function.
477
478                         //
479                         // Check whether it's in the namespace.
480                         //
481                         FullNamedExpression o = NS.Lookup (ds, name, loc);
482                         if (o != null)
483                                 return o;
484
485                         if (IsImplicit)
486                                 return null;
487
488                         //
489                         // Check aliases.
490                         //
491                         o = LookupAlias (name);
492                         if (o != null)
493                                 return o;
494
495                         //
496                         // Check using entries.
497                         //
498                         FullNamedExpression t = null, match = null;
499                         foreach (Namespace using_ns in GetUsingTable ()) {
500                                 match = using_ns.Lookup (ds, name, loc);
501                                 if ((match != null) && (match is TypeExpr)) {
502                                         if (t != null) {
503                                                 if (!ignore_cs0104)
504                                                         DeclSpace.Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
505                                                 
506                                                 return null;
507                                         } else {
508                                                 t = match;
509                                         }
510                                 }
511                         }
512
513                         return t;
514                 }
515
516                 // Our cached computation.
517                 Namespace [] namespace_using_table;
518                 public Namespace[] GetUsingTable ()
519                 {
520                         if (namespace_using_table != null)
521                                 return namespace_using_table;
522
523                         if (using_clauses == null) {
524                                 namespace_using_table = new Namespace [0];
525                                 return namespace_using_table;
526                         }
527
528                         ArrayList list = new ArrayList (using_clauses.Count);
529
530                         foreach (UsingEntry ue in using_clauses) {
531                                 Namespace using_ns = ue.Resolve ();
532                                 if (using_ns == null)
533                                         continue;
534
535                                 list.Add (using_ns);
536                         }
537
538                         namespace_using_table = new Namespace [list.Count];
539                         list.CopyTo (namespace_using_table, 0);
540                         return namespace_using_table;
541                 }
542
543                 public void DefineNamespace (SymbolWriter symwriter)
544                 {
545                         if (symfile_id != 0)
546                                 return;
547                         if (parent != null)
548                                 parent.DefineNamespace (symwriter);
549
550                         string[] using_list;
551                         if (using_clauses != null) {
552                                 using_list = new string [using_clauses.Count];
553                                 for (int i = 0; i < using_clauses.Count; i++)
554                                         using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
555                         } else {
556                                 using_list = new string [0];
557                         }
558
559                         int parent_id = parent != null ? parent.symfile_id : 0;
560                         if (file.SourceFileEntry == null)
561                                 return;
562
563                         symfile_id = symwriter.DefineNamespace (
564                                 ns.Name, file.SourceFileEntry, using_list, parent_id);
565                 }
566
567                 public int SymbolFileID {
568                         get {
569                                 return symfile_id;
570                         }
571                 }
572
573                 static void MsgtryRef (string s)
574                 {
575                         Console.WriteLine ("    Try using -r:" + s);
576                 }
577                 
578                 static void MsgtryPkg (string s)
579                 {
580                         Console.WriteLine ("    Try using -pkg:" + s);
581                 }
582
583                 protected void error246 (Location loc, string name)
584                 {
585                         Report.Error (246, loc, "The namespace `" + name +
586                                       "' can not be found (missing assembly reference?)");
587
588                         switch (name) {
589                         case "Gtk": case "GtkSharp":
590                                 MsgtryPkg ("gtk-sharp");
591                                 break;
592
593                         case "Gdk": case "GdkSharp":
594                                 MsgtryPkg ("gdk-sharp");
595                                 break;
596
597                         case "Glade": case "GladeSharp":
598                                 MsgtryPkg ("glade-sharp");
599                                 break;
600
601                         case "System.Drawing":
602                         case "System.Web.Services":
603                         case "System.Web":
604                         case "System.Data":
605                         case "System.Windows.Forms":
606                                 MsgtryRef (name);
607                                 break;
608                         }
609                 }
610
611                 /// <summary>
612                 ///   Used to validate that all the using clauses are correct
613                 ///   after we are finished parsing all the files.  
614                 /// </summary>
615                 public void VerifyUsing ()
616                 {
617                         if (using_clauses != null){
618                                 foreach (UsingEntry ue in using_clauses){
619                                         if (ue.Resolve () != null)
620                                                 continue;
621
622                                         if (ue.resolved == null)
623                                                 error246 (ue.Location, ue.Name.ToString ());
624                                         else
625                                                 Report.Error (138, ue.Location, "The using keyword only lets you specify a namespace, " +
626                                                               "`" + ue.Name + "' is a class not a namespace.");
627
628                                 }
629                         }
630
631                         if (aliases != null){
632                                 foreach (DictionaryEntry de in aliases){
633                                         AliasEntry alias = (AliasEntry) de.Value;
634
635                                         if (alias.Resolve () != null)
636                                                 continue;
637
638                                         error246 (alias.Location, alias.Alias.ToString ());
639                                 }
640                         }
641                 }
642
643                 public override string ToString ()
644                 {
645                         if (NS == Namespace.Root)
646                                 return "NamespaceEntry (<root>)";
647                         else
648                                 return String.Format ("NamespaceEntry ({0},{1},{2})", FullName, IsImplicit, ID);
649                 }
650         }
651 }