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.NotPublic ||
118 ta == TypeAttributes.NestedPrivate ||
119 ta == TypeAttributes.NestedAssembly ||
120 ta == TypeAttributes.NestedFamANDAssem)
126 public override string ToString ()
128 return String.Format ("RootNamespace ({0}::)", alias_name);
131 public override string GetSignatureForError ()
133 return alias_name + "::";
137 public class GlobalRootNamespace : RootNamespace {
138 Assembly [] assemblies;
141 public GlobalRootNamespace ()
142 : base ("global", null)
144 assemblies = new Assembly [0];
147 public Assembly [] Assemblies {
148 get { return assemblies; }
151 public Module [] Modules {
152 get { return modules; }
155 public void AddAssemblyReference (Assembly a)
157 foreach (Assembly assembly in assemblies) {
162 int top = assemblies.Length;
163 Assembly [] n = new Assembly [top + 1];
164 assemblies.CopyTo (n, 0);
168 ComputeNamespaces (a);
171 public void AddModuleReference (Module m)
173 int top = modules != null ? modules.Length : 0;
174 Module [] n = new Module [top + 1];
176 modules.CopyTo (n, 0);
180 if (m == CodeGen.Module.Builder)
183 foreach (Type t in m.GetTypes ())
184 EnsureNamespace (t.Namespace);
187 public override void Error_NamespaceDoesNotExist(Location loc, string name)
189 Report.Error (400, loc, "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
193 public override Type LookupTypeReflection (string name, Location loc)
195 Type found_type = null;
197 foreach (Assembly a in assemblies) {
198 Type t = GetTypeInAssembly (a, name);
202 if (found_type == null) {
207 Report.SymbolRelatedToPreviousError (found_type);
208 Report.SymbolRelatedToPreviousError (t);
209 Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
214 if (modules != null) {
215 foreach (Module module in modules) {
216 Type t = module.GetType (name);
220 if (found_type == null) {
225 Report.SymbolRelatedToPreviousError (t);
226 Report.SymbolRelatedToPreviousError (found_type);
227 Report.Warning (436, 2, loc, "Ignoring imported type `{0}' since the current assembly already has a declaration with the same name",
228 TypeManager.CSharpName (t));
238 /// Keeps track of the namespaces defined in the C# code.
240 /// This is an Expression to allow it to be referenced in the
241 /// compiler parse/intermediate tree during name resolution.
243 public class Namespace : FullNamedExpression {
247 Hashtable namespaces;
248 IDictionary declspaces;
249 Hashtable cached_types;
252 public readonly MemberName MemberName;
255 /// Constructor Takes the current namespace and the
256 /// name. This is bootstrapped with parent == null
259 public Namespace (Namespace parent, string name)
261 // Expression members.
262 this.eclass = ExprClass.Namespace;
264 this.loc = Location.Null;
266 this.parent = parent;
269 this.root = parent.root;
271 this.root = this as RootNamespace;
273 if (this.root == null)
274 throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
276 string pname = parent != null ? parent.Name : "";
281 fullname = parent.Name + "." + name;
283 if (fullname == null)
284 throw new InternalErrorException ("Namespace has a null fullname");
286 if (parent != null && parent.MemberName != MemberName.Null)
287 MemberName = new MemberName (parent.MemberName, name);
288 else if (name.Length == 0)
289 MemberName = MemberName.Null;
291 MemberName = new MemberName (name);
293 namespaces = new Hashtable ();
294 cached_types = new Hashtable ();
296 root.RegisterNamespace (this);
299 public override Expression DoResolve (EmitContext ec)
304 public virtual void Error_NamespaceDoesNotExist (Location loc, string name)
306 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
310 public override void Emit (EmitContext ec)
312 throw new InternalErrorException ("Expression tree referenced namespace " + fullname + " during Emit ()");
315 public override string GetSignatureForError ()
320 public Namespace GetNamespace (string name, bool create)
322 int pos = name.IndexOf ('.');
327 first = name.Substring (0, pos);
331 ns = (Namespace) namespaces [first];
336 ns = new Namespace (this, first);
337 namespaces.Add (first, ns);
341 ns = ns.GetNamespace (name.Substring (pos + 1), create);
346 TypeExpr LookupType (string name, Location loc)
348 if (cached_types.Contains (name))
349 return cached_types [name] as TypeExpr;
352 if (declspaces != null) {
353 DeclSpace tdecl = declspaces [name] as DeclSpace;
356 // Note that this is not:
358 // t = tdecl.DefineType ()
360 // This is to make it somewhat more useful when a DefineType
361 // fails due to problems in nested types (more useful in the sense
362 // of fewer misleading error messages)
365 t = tdecl.TypeBuilder;
368 string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
369 Type rt = root.LookupTypeReflection (lookup, loc);
373 TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
374 cached_types [name] = te;
378 public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
380 if (namespaces.Contains (name))
381 return (Namespace) namespaces [name];
383 TypeExpr te = LookupType (name, loc);
384 if (te == null || !ds.CheckAccessLevel (te.Type))
390 public void AddDeclSpace (string name, DeclSpace ds)
392 if (declspaces == null)
393 declspaces = new HybridDictionary ();
394 declspaces.Add (name, ds);
398 /// The qualified name of the current namespace
401 get { return fullname; }
404 public override string FullName {
405 get { return fullname; }
409 /// The parent of this namespace, used by the parser to "Pop"
410 /// the current namespace declaration
412 public Namespace Parent {
413 get { return parent; }
416 public override string ToString ()
418 return String.Format ("Namespace ({0})", Name);
422 public class NamespaceEntry {
424 NamespaceEntry parent, implicit_parent;
428 ArrayList using_clauses;
429 public bool DeclarationFound = false;
432 public readonly DeclSpace SlaveDeclSpace;
434 ListDictionary extern_aliases;
436 static ArrayList entries = new ArrayList ();
438 public static void Reset ()
440 entries = new ArrayList ();
444 // This class holds the location where a using definition is
445 // done, and whether it has been used by the program or not.
447 // We use this to flag using clauses for namespaces that do not
450 public class UsingEntry : IResolveContext {
451 public readonly MemberName Name;
452 readonly Expression Expr;
453 readonly NamespaceEntry NamespaceEntry;
454 readonly Location Location;
456 public UsingEntry (NamespaceEntry entry, MemberName name, Location loc)
459 Expr = name.GetTypeExpression ();
460 NamespaceEntry = entry;
464 internal Namespace resolved;
466 public Namespace Resolve ()
468 if (resolved != null)
471 FullNamedExpression fne = Expr.ResolveAsTypeStep (this, false);
473 Error_NamespaceNotFound (Location, Name.ToString ());
477 resolved = fne as Namespace;
478 if (resolved == null) {
479 Report.Error (138, Location,
480 "`{0} is a type not a namespace. A using namespace directive can only be applied to namespaces", Name.ToString ());
485 DeclSpace IResolveContext.DeclContainer {
486 get { return NamespaceEntry.SlaveDeclSpace; }
488 bool IResolveContext.IsInObsoleteScope {
489 get { return false; }
491 bool IResolveContext.IsInUnsafeScope {
492 get { return false; }
496 public abstract class AliasEntry {
497 public readonly string Name;
498 public readonly NamespaceEntry NamespaceEntry;
499 public readonly Location Location;
501 protected AliasEntry (NamespaceEntry entry, string name, Location loc)
504 NamespaceEntry = entry;
508 protected FullNamedExpression resolved;
511 public FullNamedExpression Resolve ()
513 if (resolved != null || error)
515 resolved = DoResolve ();
516 if (resolved == null)
521 protected abstract FullNamedExpression DoResolve ();
524 public class LocalAliasEntry : AliasEntry, IResolveContext {
525 public readonly Expression Alias;
527 public LocalAliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc) :
528 base (entry, name, loc)
530 Alias = alias.GetTypeExpression ();
533 protected override FullNamedExpression DoResolve ()
535 resolved = Alias.ResolveAsTypeStep (this, false);
536 if (resolved == null)
539 if (resolved.Type != null) {
540 TypeAttributes attr = resolved.Type.Attributes & TypeAttributes.VisibilityMask;
541 if (attr == TypeAttributes.NestedPrivate || attr == TypeAttributes.NestedFamily ||
542 ((attr == TypeAttributes.NestedFamORAssem || attr == TypeAttributes.NestedAssembly) &&
543 TypeManager.LookupDeclSpace (resolved.Type) == null)) {
544 Expression.ErrorIsInaccesible (Alias.Location, Alias.ToString ());
552 DeclSpace IResolveContext.DeclContainer {
553 get { return NamespaceEntry.SlaveDeclSpace; }
555 bool IResolveContext.IsInObsoleteScope {
556 get { return false; }
558 bool IResolveContext.IsInUnsafeScope {
559 get { return false; }
563 public class ExternAliasEntry : AliasEntry {
564 public ExternAliasEntry (NamespaceEntry entry, string name, Location loc) :
565 base (entry, name, loc)
569 protected override FullNamedExpression DoResolve ()
571 resolved = RootNamespace.GetRootNamespace (Name);
572 if (resolved == null)
573 Report.Error (430, Location, "The extern alias '" + Name +
574 "' was not specified in a /reference option");
580 public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name)
582 this.parent = parent;
585 this.ID = entries.Count;
588 ns = parent.NS.GetNamespace (name, true);
589 else if (name != null)
590 ns = RootNamespace.Global.GetNamespace (name, true);
592 ns = RootNamespace.Global;
593 SlaveDeclSpace = new RootDeclSpace (this);
596 private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns, bool slave)
598 this.parent = parent;
600 // no need to add self to 'entries', since we don't have any aliases or using entries.
602 this.IsImplicit = true;
604 this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
608 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
609 // resolved as if the immediately containing namespace body has no using-directives.
611 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
612 // in the using-namespace-directive.
614 // To implement these rules, the expressions in the using directives are resolved using
615 // the "doppelganger" (ghostly bodiless duplicate).
617 NamespaceEntry doppelganger;
618 NamespaceEntry Doppelganger {
620 if (!IsImplicit && doppelganger == null)
621 doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
626 public readonly int ID;
627 public readonly bool IsImplicit;
629 public Namespace NS {
633 public NamespaceEntry Parent {
634 get { return parent; }
637 public NamespaceEntry ImplicitParent {
641 if (implicit_parent == null) {
642 implicit_parent = (parent.NS == ns.Parent)
644 : new NamespaceEntry (parent, file, ns.Parent, false);
646 return implicit_parent;
651 /// Records a new namespace for resolving name references
653 public void Using (MemberName name, Location loc)
655 if (DeclarationFound){
656 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
662 if (name.Equals (ns.MemberName))
665 if (using_clauses == null)
666 using_clauses = new ArrayList ();
668 foreach (UsingEntry old_entry in using_clauses) {
669 if (name.Equals (old_entry.Name)) {
670 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetName ());
675 UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
676 using_clauses.Add (ue);
679 public void UsingAlias (string name, MemberName alias, Location loc)
681 if (DeclarationFound){
682 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
689 aliases = new Hashtable ();
691 if (aliases.Contains (name)) {
692 AliasEntry ae = (AliasEntry) aliases [name];
693 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
694 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
698 if (RootContext.Version == LanguageVersion.Default &&
699 name == "global" && RootContext.WarningLevel >= 2)
700 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
701 " the global namespace will be used instead");
703 // FIXME: get correct error number. See if the above check can be merged
704 if (extern_aliases != null && extern_aliases.Contains (name)) {
705 AliasEntry ae = (AliasEntry) extern_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 aliases [name] = new LocalAliasEntry (Doppelganger, name, alias, loc);
714 public void UsingExternalAlias (string name, Location loc)
716 if (UsingFound || DeclarationFound) {
717 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
721 // Share the extern_aliases field with the Doppelganger
722 if (extern_aliases == null) {
723 extern_aliases = new ListDictionary ();
724 Doppelganger.extern_aliases = extern_aliases;
727 if (extern_aliases.Contains (name)) {
728 AliasEntry ae = (AliasEntry) extern_aliases [name];
729 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
730 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
734 if (name == "global") {
735 Report.Error (1681, loc, "You cannot redefine the global extern alias");
739 // Register the alias in aliases and extern_aliases, since we need both of them
740 // to keep things simple (different resolution scenarios)
741 ExternAliasEntry alias = new ExternAliasEntry (Doppelganger, name, loc);
742 extern_aliases [name] = alias;
745 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
747 // Precondition: Only simple names (no dots) will be looked up with this function.
748 FullNamedExpression resolved = null;
749 for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
750 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
756 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
758 Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
759 name, t1.FullName, t2.FullName);
762 // Looks-up a alias named @name in this and surrounding namespace declarations
763 public FullNamedExpression LookupAlias (string name)
765 AliasEntry entry = null;
766 for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
767 if (n.extern_aliases != null && (entry = n.extern_aliases [name] as AliasEntry) != null)
769 if (n.aliases != null && (entry = n.aliases [name] as AliasEntry) != null)
772 return entry == null ? null : entry.Resolve ();
775 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
778 // Check whether it's in the namespace.
780 FullNamedExpression fne = NS.Lookup (ds, name, loc);
784 if (extern_aliases != null) {
785 AliasEntry entry = extern_aliases [name] as AliasEntry;
787 return entry.Resolve ();
796 if (aliases != null) {
797 AliasEntry entry = aliases [name] as AliasEntry;
799 return entry.Resolve ();
803 // Check using entries.
805 FullNamedExpression match = null;
806 foreach (Namespace using_ns in GetUsingTable ()) {
807 match = using_ns.Lookup (ds, name, loc);
808 if (match == null || !(match is TypeExpr))
812 Error_AmbiguousTypeReference (loc, name, fne, match);
821 // Our cached computation.
822 readonly Namespace [] empty_namespaces = new Namespace [0];
823 Namespace [] namespace_using_table;
824 Namespace [] GetUsingTable ()
826 if (namespace_using_table != null)
827 return namespace_using_table;
829 if (using_clauses == null) {
830 namespace_using_table = empty_namespaces;
831 return namespace_using_table;
834 ArrayList list = new ArrayList (using_clauses.Count);
836 foreach (UsingEntry ue in using_clauses) {
837 Namespace using_ns = ue.Resolve ();
838 if (using_ns == null)
844 namespace_using_table = new Namespace [list.Count];
845 list.CopyTo (namespace_using_table, 0);
846 return namespace_using_table;
849 readonly string [] empty_using_list = new string [0];
851 public int SymbolFileID {
853 if (symfile_id == 0 && file.SourceFileEntry != null) {
854 int parent_id = parent == null ? 0 : parent.SymbolFileID;
856 string [] using_list = empty_using_list;
857 if (using_clauses != null) {
858 using_list = new string [using_clauses.Count];
859 for (int i = 0; i < using_clauses.Count; i++)
860 using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
863 symfile_id = CodeGen.SymbolWriter.DefineNamespace (ns.Name, file.SourceFileEntry, using_list, parent_id);
869 static void MsgtryRef (string s)
871 Console.WriteLine (" Try using -r:" + s);
874 static void MsgtryPkg (string s)
876 Console.WriteLine (" Try using -pkg:" + s);
879 public static void Error_NamespaceNotFound (Location loc, string name)
881 Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
885 case "Gtk": case "GtkSharp":
886 MsgtryPkg ("gtk-sharp");
889 case "Gdk": case "GdkSharp":
890 MsgtryPkg ("gdk-sharp");
893 case "Glade": case "GladeSharp":
894 MsgtryPkg ("glade-sharp");
897 case "System.Drawing":
898 case "System.Web.Services":
901 case "System.Windows.Forms":
908 /// Used to validate that all the using clauses are correct
909 /// after we are finished parsing all the files.
913 if (extern_aliases != null) {
914 foreach (DictionaryEntry de in extern_aliases)
915 ((AliasEntry) de.Value).Resolve ();
918 if (using_clauses != null) {
919 foreach (UsingEntry ue in using_clauses)
923 if (aliases != null) {
924 foreach (DictionaryEntry de in aliases)
925 ((AliasEntry) de.Value).Resolve ();
930 /// Used to validate that all the using clauses are correct
931 /// after we are finished parsing all the files.
933 static public void VerifyAllUsing ()
935 foreach (NamespaceEntry entry in entries)
936 entry.VerifyUsing ();
939 public string GetSignatureForError ()
941 return ns.GetSignatureForError ();
944 public override string ToString ()
946 return ns.ToString ();