2 // namespace.cs: Tracks namespaces
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // (C) 2001 Ximian, Inc.
11 using System.Collections;
12 using System.Collections.Specialized;
13 using System.Reflection;
15 namespace Mono.CSharp {
17 public class RootNamespace : Namespace {
18 static MethodInfo get_namespaces_method;
21 Assembly referenced_assembly;
23 Hashtable all_namespaces;
25 static Hashtable root_namespaces;
26 public static GlobalRootNamespace Global;
28 static RootNamespace ()
30 get_namespaces_method = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance | BindingFlags.NonPublic);
35 public static void Reset ()
37 root_namespaces = new Hashtable ();
38 Global = new GlobalRootNamespace ();
39 root_namespaces ["global"] = Global;
42 protected RootNamespace (string alias_name, Assembly assembly)
43 : base (null, String.Empty)
45 this.alias_name = alias_name;
46 referenced_assembly = assembly;
48 all_namespaces = new Hashtable ();
49 all_namespaces.Add ("", this);
51 if (referenced_assembly != null)
52 ComputeNamespaces (this.referenced_assembly);
55 public static void DefineRootNamespace (string name, Assembly assembly)
57 if (name == "global") {
58 // FIXME: Add proper error number
59 Report.Error (-42, "Cannot define an external alias named `global'");
62 RootNamespace retval = GetRootNamespace (name);
63 if (retval == null || retval.referenced_assembly != assembly)
64 root_namespaces [name] = new RootNamespace (name, assembly);
67 public static RootNamespace GetRootNamespace (string name)
69 return (RootNamespace) root_namespaces [name];
72 public virtual Type LookupTypeReflection (string name, Location loc)
74 return GetTypeInAssembly (referenced_assembly, name);
77 public void RegisterNamespace (Namespace child)
80 all_namespaces.Add (child.Name, child);
83 public bool IsNamespace (string name)
85 return all_namespaces.Contains (name);
88 protected void EnsureNamespace (string dotted_name)
90 if (dotted_name != null && dotted_name.Length != 0 && ! IsNamespace (dotted_name))
91 GetNamespace (dotted_name, true);
94 protected void ComputeNamespaces (Assembly assembly)
96 if (get_namespaces_method != null) {
97 string [] namespaces = (string []) get_namespaces_method.Invoke (assembly, null);
98 foreach (string ns in namespaces)
103 foreach (Type t in assembly.GetExportedTypes ())
104 EnsureNamespace (t.Namespace);
107 protected static Type GetTypeInAssembly (Assembly assembly, string name)
109 Type t = assembly.GetType (name);
114 throw new InternalErrorException ("Use GetPointerType() to get a pointer");
116 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
117 if (ta == TypeAttributes.NestedPrivate)
120 if ((ta == TypeAttributes.NotPublic ||
121 ta == TypeAttributes.NestedAssembly ||
122 ta == TypeAttributes.NestedFamANDAssem) &&
123 !TypeManager.IsFriendAssembly (t.Assembly))
129 public override string ToString ()
131 return String.Format ("RootNamespace ({0}::)", alias_name);
134 public override string GetSignatureForError ()
136 return alias_name + "::";
140 public class GlobalRootNamespace : RootNamespace {
141 Assembly [] assemblies;
144 public GlobalRootNamespace ()
145 : base ("global", null)
147 assemblies = new Assembly [0];
150 public Assembly [] Assemblies {
151 get { return assemblies; }
154 public Module [] Modules {
155 get { return modules; }
158 public void AddAssemblyReference (Assembly a)
160 foreach (Assembly assembly in assemblies) {
165 int top = assemblies.Length;
166 Assembly [] n = new Assembly [top + 1];
167 assemblies.CopyTo (n, 0);
171 ComputeNamespaces (a);
174 public void AddModuleReference (Module m)
176 int top = modules != null ? modules.Length : 0;
177 Module [] n = new Module [top + 1];
179 modules.CopyTo (n, 0);
183 if (m == CodeGen.Module.Builder)
186 foreach (Type t in m.GetTypes ())
187 EnsureNamespace (t.Namespace);
190 public override void Error_NamespaceDoesNotExist(Location loc, string name)
192 Report.Error (400, loc, "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
196 public override Type LookupTypeReflection (string name, Location loc)
198 Type found_type = null;
200 foreach (Assembly a in assemblies) {
201 Type t = GetTypeInAssembly (a, name);
205 if (found_type == null) {
210 Report.SymbolRelatedToPreviousError (found_type);
211 Report.SymbolRelatedToPreviousError (t);
212 Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
217 if (modules != null) {
218 foreach (Module module in modules) {
219 Type t = module.GetType (name);
223 if (found_type == null) {
228 Report.SymbolRelatedToPreviousError (t);
229 Report.SymbolRelatedToPreviousError (found_type);
230 Report.Warning (436, 2, loc, "Ignoring imported type `{0}' since the current assembly already has a declaration with the same name",
231 TypeManager.CSharpName (t));
241 /// Keeps track of the namespaces defined in the C# code.
243 /// This is an Expression to allow it to be referenced in the
244 /// compiler parse/intermediate tree during name resolution.
246 public class Namespace : FullNamedExpression {
250 Hashtable namespaces;
251 IDictionary declspaces;
252 Hashtable cached_types;
255 public readonly MemberName MemberName;
258 /// Constructor Takes the current namespace and the
259 /// name. This is bootstrapped with parent == null
262 public Namespace (Namespace parent, string name)
264 // Expression members.
265 this.eclass = ExprClass.Namespace;
267 this.loc = Location.Null;
269 this.parent = parent;
272 this.root = parent.root;
274 this.root = this as RootNamespace;
276 if (this.root == null)
277 throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
279 string pname = parent != null ? parent.Name : "";
284 fullname = parent.Name + "." + name;
286 if (fullname == null)
287 throw new InternalErrorException ("Namespace has a null fullname");
289 if (parent != null && parent.MemberName != MemberName.Null)
290 MemberName = new MemberName (parent.MemberName, name);
291 else if (name.Length == 0)
292 MemberName = MemberName.Null;
294 MemberName = new MemberName (name);
296 namespaces = new Hashtable ();
297 cached_types = new Hashtable ();
299 root.RegisterNamespace (this);
302 public override Expression DoResolve (EmitContext ec)
307 public virtual void Error_NamespaceDoesNotExist (Location loc, string name)
309 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
313 public override void Emit (EmitContext ec)
315 throw new InternalErrorException ("Expression tree referenced namespace " + fullname + " during Emit ()");
318 public override string GetSignatureForError ()
323 public Namespace GetNamespace (string name, bool create)
325 int pos = name.IndexOf ('.');
330 first = name.Substring (0, pos);
334 ns = (Namespace) namespaces [first];
339 ns = new Namespace (this, first);
340 namespaces.Add (first, ns);
344 ns = ns.GetNamespace (name.Substring (pos + 1), create);
349 TypeExpr LookupType (string name, Location loc)
351 if (cached_types.Contains (name))
352 return cached_types [name] as TypeExpr;
355 if (declspaces != null) {
356 DeclSpace tdecl = declspaces [name] as DeclSpace;
359 // Note that this is not:
361 // t = tdecl.DefineType ()
363 // This is to make it somewhat more useful when a DefineType
364 // fails due to problems in nested types (more useful in the sense
365 // of fewer misleading error messages)
368 t = tdecl.TypeBuilder;
371 string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
372 Type rt = root.LookupTypeReflection (lookup, loc);
376 TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
377 cached_types [name] = te;
381 public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
383 if (namespaces.Contains (name))
384 return (Namespace) namespaces [name];
386 TypeExpr te = LookupType (name, loc);
387 if (te == null || !ds.CheckAccessLevel (te.Type))
393 public void AddDeclSpace (string name, DeclSpace ds)
395 if (declspaces == null)
396 declspaces = new HybridDictionary ();
397 declspaces.Add (name, ds);
401 /// The qualified name of the current namespace
404 get { return fullname; }
407 public override string FullName {
408 get { return fullname; }
412 /// The parent of this namespace, used by the parser to "Pop"
413 /// the current namespace declaration
415 public Namespace Parent {
416 get { return parent; }
419 public override string ToString ()
421 return String.Format ("Namespace ({0})", Name);
425 public class NamespaceEntry {
427 NamespaceEntry parent, implicit_parent;
431 ArrayList using_clauses;
432 public bool DeclarationFound = false;
435 public readonly DeclSpace SlaveDeclSpace;
437 ListDictionary extern_aliases;
439 static ArrayList entries = new ArrayList ();
441 public static void Reset ()
443 entries = new ArrayList ();
447 // This class holds the location where a using definition is
448 // done, and whether it has been used by the program or not.
450 // We use this to flag using clauses for namespaces that do not
453 public class UsingEntry : IResolveContext {
454 public readonly MemberName Name;
455 readonly Expression Expr;
456 readonly NamespaceEntry NamespaceEntry;
457 readonly Location Location;
459 public UsingEntry (NamespaceEntry entry, MemberName name, Location loc)
462 Expr = name.GetTypeExpression ();
463 NamespaceEntry = entry;
467 internal Namespace resolved;
469 public Namespace Resolve ()
471 if (resolved != null)
474 FullNamedExpression fne = Expr.ResolveAsTypeStep (this, false);
476 Error_NamespaceNotFound (Location, Name.ToString ());
480 resolved = fne as Namespace;
481 if (resolved == null) {
482 Report.Error (138, Location,
483 "`{0} is a type not a namespace. A using namespace directive can only be applied to namespaces", Name.ToString ());
488 DeclSpace IResolveContext.DeclContainer {
489 get { return NamespaceEntry.SlaveDeclSpace; }
492 DeclSpace IResolveContext.GenericDeclContainer {
493 get { return NamespaceEntry.SlaveDeclSpace; }
496 bool IResolveContext.IsInObsoleteScope {
497 get { return false; }
499 bool IResolveContext.IsInUnsafeScope {
500 get { return false; }
504 public abstract class AliasEntry {
505 public readonly string Name;
506 public readonly NamespaceEntry NamespaceEntry;
507 public readonly Location Location;
509 protected AliasEntry (NamespaceEntry entry, string name, Location loc)
512 NamespaceEntry = entry;
516 protected FullNamedExpression resolved;
519 public FullNamedExpression Resolve ()
521 if (resolved != null || error)
523 resolved = DoResolve ();
524 if (resolved == null)
529 protected abstract FullNamedExpression DoResolve ();
532 public class LocalAliasEntry : AliasEntry, IResolveContext {
533 public readonly Expression Alias;
535 public LocalAliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc) :
536 base (entry, name, loc)
538 Alias = alias.GetTypeExpression ();
541 protected override FullNamedExpression DoResolve ()
543 resolved = Alias.ResolveAsTypeStep (this, false);
544 if (resolved == null)
547 if (resolved.Type != null) {
548 TypeAttributes attr = resolved.Type.Attributes & TypeAttributes.VisibilityMask;
549 if (attr == TypeAttributes.NestedPrivate || attr == TypeAttributes.NestedFamily ||
550 ((attr == TypeAttributes.NestedFamORAssem || attr == TypeAttributes.NestedAssembly) &&
551 TypeManager.LookupDeclSpace (resolved.Type) == null)) {
552 Expression.ErrorIsInaccesible (Alias.Location, Alias.ToString ());
560 DeclSpace IResolveContext.DeclContainer {
561 get { return NamespaceEntry.SlaveDeclSpace; }
564 DeclSpace IResolveContext.GenericDeclContainer {
565 get { return NamespaceEntry.SlaveDeclSpace; }
568 bool IResolveContext.IsInObsoleteScope {
569 get { return false; }
571 bool IResolveContext.IsInUnsafeScope {
572 get { return false; }
576 public class ExternAliasEntry : AliasEntry {
577 public ExternAliasEntry (NamespaceEntry entry, string name, Location loc) :
578 base (entry, name, loc)
582 protected override FullNamedExpression DoResolve ()
584 resolved = RootNamespace.GetRootNamespace (Name);
585 if (resolved == null)
586 Report.Error (430, Location, "The extern alias '" + Name +
587 "' was not specified in a /reference option");
593 public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name)
595 this.parent = parent;
598 this.ID = entries.Count;
601 ns = parent.NS.GetNamespace (name, true);
602 else if (name != null)
603 ns = RootNamespace.Global.GetNamespace (name, true);
605 ns = RootNamespace.Global;
606 SlaveDeclSpace = new RootDeclSpace (this);
609 private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns, bool slave)
611 this.parent = parent;
613 // no need to add self to 'entries', since we don't have any aliases or using entries.
615 this.IsImplicit = true;
617 this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
621 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
622 // resolved as if the immediately containing namespace body has no using-directives.
624 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
625 // in the using-namespace-directive.
627 // To implement these rules, the expressions in the using directives are resolved using
628 // the "doppelganger" (ghostly bodiless duplicate).
630 NamespaceEntry doppelganger;
631 NamespaceEntry Doppelganger {
633 if (!IsImplicit && doppelganger == null)
634 doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
639 public readonly int ID;
640 public readonly bool IsImplicit;
642 public Namespace NS {
646 public NamespaceEntry Parent {
647 get { return parent; }
650 public NamespaceEntry ImplicitParent {
654 if (implicit_parent == null) {
655 implicit_parent = (parent.NS == ns.Parent)
657 : new NamespaceEntry (parent, file, ns.Parent, false);
659 return implicit_parent;
664 /// Records a new namespace for resolving name references
666 public void Using (MemberName name, Location loc)
668 if (DeclarationFound){
669 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
675 if (name.Equals (ns.MemberName))
678 if (using_clauses == null)
679 using_clauses = new ArrayList ();
681 foreach (UsingEntry old_entry in using_clauses) {
682 if (name.Equals (old_entry.Name)) {
683 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetName ());
688 UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
689 using_clauses.Add (ue);
692 public void UsingAlias (string name, MemberName alias, Location loc)
694 if (DeclarationFound){
695 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
702 aliases = new Hashtable ();
704 if (aliases.Contains (name)) {
705 AliasEntry ae = (AliasEntry) aliases [name];
706 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
707 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
711 if (RootContext.Version == LanguageVersion.Default &&
712 name == "global" && RootContext.WarningLevel >= 2)
713 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
714 " the global namespace will be used instead");
716 // FIXME: get correct error number. See if the above check can be merged
717 if (extern_aliases != null && extern_aliases.Contains (name)) {
718 AliasEntry ae = (AliasEntry) extern_aliases [name];
719 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
720 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
724 aliases [name] = new LocalAliasEntry (Doppelganger, name, alias, loc);
727 public void UsingExternalAlias (string name, Location loc)
729 if (UsingFound || DeclarationFound) {
730 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
734 // Share the extern_aliases field with the Doppelganger
735 if (extern_aliases == null) {
736 extern_aliases = new ListDictionary ();
737 Doppelganger.extern_aliases = extern_aliases;
740 if (extern_aliases.Contains (name)) {
741 AliasEntry ae = (AliasEntry) extern_aliases [name];
742 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
743 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
747 if (name == "global") {
748 Report.Error (1681, loc, "You cannot redefine the global extern alias");
752 // Register the alias in aliases and extern_aliases, since we need both of them
753 // to keep things simple (different resolution scenarios)
754 ExternAliasEntry alias = new ExternAliasEntry (Doppelganger, name, loc);
755 extern_aliases [name] = alias;
758 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
760 // Precondition: Only simple names (no dots) will be looked up with this function.
761 FullNamedExpression resolved = null;
762 for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
763 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
769 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
771 Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
772 name, t1.FullName, t2.FullName);
775 // Looks-up a alias named @name in this and surrounding namespace declarations
776 public FullNamedExpression LookupAlias (string name)
778 AliasEntry entry = null;
779 for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
780 if (n.extern_aliases != null && (entry = n.extern_aliases [name] as AliasEntry) != null)
782 if (n.aliases != null && (entry = n.aliases [name] as AliasEntry) != null)
785 return entry == null ? null : entry.Resolve ();
788 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
791 // Check whether it's in the namespace.
793 FullNamedExpression fne = NS.Lookup (ds, name, loc);
797 if (extern_aliases != null) {
798 AliasEntry entry = extern_aliases [name] as AliasEntry;
800 return entry.Resolve ();
809 if (aliases != null) {
810 AliasEntry entry = aliases [name] as AliasEntry;
812 return entry.Resolve ();
816 // Check using entries.
818 FullNamedExpression match = null;
819 foreach (Namespace using_ns in GetUsingTable ()) {
820 match = using_ns.Lookup (ds, name, loc);
821 if (match == null || !(match is TypeExpr))
825 Error_AmbiguousTypeReference (loc, name, fne, match);
834 // Our cached computation.
835 readonly Namespace [] empty_namespaces = new Namespace [0];
836 Namespace [] namespace_using_table;
837 Namespace [] GetUsingTable ()
839 if (namespace_using_table != null)
840 return namespace_using_table;
842 if (using_clauses == null) {
843 namespace_using_table = empty_namespaces;
844 return namespace_using_table;
847 ArrayList list = new ArrayList (using_clauses.Count);
849 foreach (UsingEntry ue in using_clauses) {
850 Namespace using_ns = ue.Resolve ();
851 if (using_ns == null)
857 namespace_using_table = new Namespace [list.Count];
858 list.CopyTo (namespace_using_table, 0);
859 return namespace_using_table;
862 readonly string [] empty_using_list = new string [0];
864 public int SymbolFileID {
866 if (symfile_id == 0 && file.SourceFileEntry != null) {
867 int parent_id = parent == null ? 0 : parent.SymbolFileID;
869 string [] using_list = empty_using_list;
870 if (using_clauses != null) {
871 using_list = new string [using_clauses.Count];
872 for (int i = 0; i < using_clauses.Count; i++)
873 using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
876 symfile_id = CodeGen.SymbolWriter.DefineNamespace (ns.Name, file.SourceFileEntry, using_list, parent_id);
882 static void MsgtryRef (string s)
884 Console.WriteLine (" Try using -r:" + s);
887 static void MsgtryPkg (string s)
889 Console.WriteLine (" Try using -pkg:" + s);
892 public static void Error_NamespaceNotFound (Location loc, string name)
894 Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
898 case "Gtk": case "GtkSharp":
899 MsgtryPkg ("gtk-sharp");
902 case "Gdk": case "GdkSharp":
903 MsgtryPkg ("gdk-sharp");
906 case "Glade": case "GladeSharp":
907 MsgtryPkg ("glade-sharp");
910 case "System.Drawing":
911 case "System.Web.Services":
914 case "System.Windows.Forms":
921 /// Used to validate that all the using clauses are correct
922 /// after we are finished parsing all the files.
926 if (extern_aliases != null) {
927 foreach (DictionaryEntry de in extern_aliases)
928 ((AliasEntry) de.Value).Resolve ();
931 if (using_clauses != null) {
932 foreach (UsingEntry ue in using_clauses)
936 if (aliases != null) {
937 foreach (DictionaryEntry de in aliases)
938 ((AliasEntry) de.Value).Resolve ();
943 /// Used to validate that all the using clauses are correct
944 /// after we are finished parsing all the files.
946 static public void VerifyAllUsing ()
948 foreach (NamespaceEntry entry in entries)
949 entry.VerifyUsing ();
952 public string GetSignatureForError ()
954 return ns.GetSignatureForError ();
957 public override string ToString ()
959 return ns.ToString ();