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