2 // namespace.cs: Tracks namespaces
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
10 using System.Collections;
11 using System.Collections.Specialized;
12 using System.Reflection;
14 namespace Mono.CSharp {
16 public class RootNamespace : Namespace {
17 static MethodInfo get_namespaces_method;
20 Assembly referenced_assembly;
22 Hashtable all_namespaces;
24 static Hashtable root_namespaces;
25 public static GlobalRootNamespace Global;
27 static RootNamespace ()
29 get_namespaces_method = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance | BindingFlags.NonPublic);
34 public static void Reset ()
36 root_namespaces = new Hashtable ();
37 Global = new GlobalRootNamespace ();
38 root_namespaces ["global"] = Global;
41 protected RootNamespace (string alias_name, Assembly assembly)
42 : base (null, String.Empty)
44 this.alias_name = alias_name;
45 referenced_assembly = assembly;
47 all_namespaces = new Hashtable ();
48 all_namespaces.Add ("", this);
50 if (referenced_assembly != null)
51 ComputeNamespaces (this.referenced_assembly);
54 public static void DefineRootNamespace (string name, Assembly assembly)
56 if (name == "global") {
57 // FIXME: Add proper error number
58 Report.Error (-42, "Cannot define an external alias named `global'");
61 RootNamespace retval = GetRootNamespace (name);
62 if (retval == null || retval.referenced_assembly != assembly)
63 root_namespaces [name] = new RootNamespace (name, assembly);
66 public static RootNamespace GetRootNamespace (string name)
68 return (RootNamespace) root_namespaces [name];
71 public virtual Type LookupTypeReflection (string name, Location loc)
73 return GetTypeInAssembly (referenced_assembly, name);
76 public void RegisterNamespace (Namespace child)
79 all_namespaces.Add (child.Name, child);
82 public bool IsNamespace (string name)
84 return all_namespaces.Contains (name);
87 protected void EnsureNamespace (string dotted_name)
89 if (dotted_name != null && dotted_name != "" && ! IsNamespace (dotted_name))
90 GetNamespace (dotted_name, true);
93 protected void ComputeNamespaces (Assembly assembly)
95 if (get_namespaces_method != null) {
96 string [] namespaces = (string []) get_namespaces_method.Invoke (assembly, null);
97 foreach (string ns in namespaces)
102 foreach (Type t in assembly.GetExportedTypes ())
103 EnsureNamespace (t.Namespace);
106 protected static Type GetTypeInAssembly (Assembly assembly, string name)
108 Type t = assembly.GetType (name);
113 throw new InternalErrorException ("Use GetPointerType() to get a pointer");
115 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
116 if (ta == TypeAttributes.NotPublic ||
117 ta == TypeAttributes.NestedPrivate ||
118 ta == TypeAttributes.NestedAssembly ||
119 ta == TypeAttributes.NestedFamANDAssem)
125 public override string ToString ()
127 return String.Format ("RootNamespace ({0}::)", alias_name);
130 public override string GetSignatureForError ()
132 return alias_name + "::";
136 public class GlobalRootNamespace : RootNamespace {
137 Assembly [] assemblies;
140 public GlobalRootNamespace ()
141 : base ("global", null)
143 assemblies = new Assembly [0];
146 public Assembly [] Assemblies {
147 get { return assemblies; }
150 public Module [] Modules {
151 get { return modules; }
154 public void AddAssemblyReference (Assembly a)
156 foreach (Assembly assembly in assemblies) {
161 int top = assemblies.Length;
162 Assembly [] n = new Assembly [top + 1];
163 assemblies.CopyTo (n, 0);
167 ComputeNamespaces (a);
170 public void AddModuleReference (Module m)
172 int top = modules != null ? modules.Length : 0;
173 Module [] n = new Module [top + 1];
175 modules.CopyTo (n, 0);
179 if (m == CodeGen.Module.Builder)
182 foreach (Type t in m.GetTypes ())
183 EnsureNamespace (t.Namespace);
186 public override Type LookupTypeReflection (string name, Location loc)
188 Type found_type = null;
190 foreach (Assembly a in assemblies) {
191 Type t = GetTypeInAssembly (a, name);
195 if (found_type == null) {
200 Report.SymbolRelatedToPreviousError (found_type);
201 Report.SymbolRelatedToPreviousError (t);
202 Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
207 if (modules != null) {
208 foreach (Module module in modules) {
209 Type t = module.GetType (name);
213 if (found_type == null) {
218 Report.SymbolRelatedToPreviousError (t);
219 Report.SymbolRelatedToPreviousError (found_type);
220 Report.Warning (436, 2, loc, "Ignoring imported type `{0}' since the current assembly already has a declaration with the same name",
221 TypeManager.CSharpName (t));
231 /// Keeps track of the namespaces defined in the C# code.
233 /// This is an Expression to allow it to be referenced in the
234 /// compiler parse/intermediate tree during name resolution.
236 public class Namespace : FullNamedExpression {
240 Hashtable namespaces;
241 IDictionary declspaces;
242 Hashtable cached_types;
245 public readonly MemberName MemberName;
248 /// Constructor Takes the current namespace and the
249 /// name. This is bootstrapped with parent == null
252 public Namespace (Namespace parent, string name)
254 // Expression members.
255 this.eclass = ExprClass.Namespace;
257 this.loc = Location.Null;
259 this.parent = parent;
262 this.root = parent.root;
264 this.root = this as RootNamespace;
266 if (this.root == null)
267 throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
269 string pname = parent != null ? parent.Name : "";
274 fullname = parent.Name + "." + name;
276 if (fullname == null)
277 throw new InternalErrorException ("Namespace has a null fullname");
279 if (parent != null && parent.MemberName != MemberName.Null)
280 MemberName = new MemberName (parent.MemberName, name);
282 MemberName = MemberName.Null;
284 MemberName = new MemberName (name);
286 namespaces = new Hashtable ();
287 cached_types = new Hashtable ();
289 root.RegisterNamespace (this);
292 public override Expression DoResolve (EmitContext ec)
297 public override void Emit (EmitContext ec)
299 throw new InternalErrorException ("Expression tree referenced namespace " + fullname + " during Emit ()");
302 public override string GetSignatureForError ()
307 public Namespace GetNamespace (string name, bool create)
309 int pos = name.IndexOf ('.');
314 first = name.Substring (0, pos);
318 ns = (Namespace) namespaces [first];
323 ns = new Namespace (this, first);
324 namespaces.Add (first, ns);
328 ns = ns.GetNamespace (name.Substring (pos + 1), create);
333 TypeExpr LookupType (string name, Location loc)
335 if (cached_types.Contains (name))
336 return cached_types [name] as TypeExpr;
339 if (declspaces != null) {
340 DeclSpace tdecl = declspaces [name] as DeclSpace;
343 // Note that this is not:
345 // t = tdecl.DefineType ()
347 // This is to make it somewhat more useful when a DefineType
348 // fails due to problems in nested types (more useful in the sense
349 // of fewer misleading error messages)
352 t = tdecl.TypeBuilder;
355 string lookup = t != null ? t.FullName : (fullname == "" ? name : fullname + "." + name);
356 Type rt = root.LookupTypeReflection (lookup, loc);
360 TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
361 cached_types [name] = te;
365 public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
367 if (namespaces.Contains (name))
368 return (Namespace) namespaces [name];
370 TypeExpr te = LookupType (name, loc);
371 if (te == null || !ds.CheckAccessLevel (te.Type))
377 public void AddDeclSpace (string name, DeclSpace ds)
379 if (declspaces == null)
380 declspaces = new HybridDictionary ();
381 declspaces.Add (name, ds);
385 /// The qualified name of the current namespace
388 get { return fullname; }
391 public override string FullName {
392 get { return fullname; }
396 /// The parent of this namespace, used by the parser to "Pop"
397 /// the current namespace declaration
399 public Namespace Parent {
400 get { return parent; }
403 public override string ToString ()
405 return String.Format ("Namespace ({0})", Name);
409 public class NamespaceEntry {
411 NamespaceEntry parent, implicit_parent;
415 ArrayList using_clauses;
416 public bool DeclarationFound = false;
419 ListDictionary extern_aliases;
421 static ArrayList entries = new ArrayList ();
423 public static void Reset ()
425 entries = new ArrayList ();
429 // This class holds the location where a using definition is
430 // done, and whether it has been used by the program or not.
432 // We use this to flag using clauses for namespaces that do not
435 public class UsingEntry {
436 public readonly MemberName Name;
437 readonly Expression Expr;
438 readonly NamespaceEntry NamespaceEntry;
439 readonly Location Location;
441 public UsingEntry (NamespaceEntry entry, MemberName name, Location loc)
444 Expr = name.GetTypeExpression ();
445 NamespaceEntry = entry;
449 internal Namespace resolved;
451 public Namespace Resolve ()
453 if (resolved != null)
456 DeclSpace root = RootContext.Tree.Types;
457 root.NamespaceEntry = NamespaceEntry;
458 FullNamedExpression fne = Expr.ResolveAsTypeStep (root, false);
459 root.NamespaceEntry = null;
462 Error_NamespaceNotFound (Location, Name.ToString ());
466 resolved = fne as Namespace;
467 if (resolved == null) {
468 Report.Error (138, Location,
469 "`{0} is a type not a namespace. A using namespace directive can only be applied to namespaces", Name.ToString ());
475 public abstract class AliasEntry {
476 public readonly string Name;
477 public readonly NamespaceEntry NamespaceEntry;
478 public readonly Location Location;
480 protected AliasEntry (NamespaceEntry entry, string name, Location loc)
483 NamespaceEntry = entry;
487 protected FullNamedExpression resolved;
490 public FullNamedExpression Resolve ()
492 if (resolved != null || error)
494 resolved = DoResolve ();
495 if (resolved == null)
500 protected abstract FullNamedExpression DoResolve ();
503 public class LocalAliasEntry : AliasEntry
505 public readonly Expression Alias;
507 public LocalAliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc) :
508 base (entry, name, loc)
510 Alias = alias.GetTypeExpression ();
513 protected override FullNamedExpression DoResolve ()
515 DeclSpace root = RootContext.Tree.Types;
516 root.NamespaceEntry = NamespaceEntry;
517 resolved = Alias.ResolveAsTypeStep (root, false);
518 root.NamespaceEntry = null;
520 if (resolved == null)
521 Error_NamespaceNotFound (Location, Alias.ToString ());
526 public class ExternAliasEntry : AliasEntry
528 public ExternAliasEntry (NamespaceEntry entry, string name, Location loc) :
529 base (entry, name, loc)
533 protected override FullNamedExpression DoResolve ()
535 resolved = RootNamespace.GetRootNamespace (Name);
536 if (resolved == null)
537 Report.Error (430, Location, "The extern alias '" + Name +
538 "' was not specified in a /reference option");
544 public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name, Location loc)
546 this.parent = parent;
549 this.ID = entries.Count;
552 ns = parent.NS.GetNamespace (name, true);
553 else if (name != null)
554 ns = RootNamespace.Global.GetNamespace (name, true);
556 ns = RootNamespace.Global;
559 private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns)
561 this.parent = parent;
563 // no need to add self to 'entries', since we don't have any aliases or using entries.
565 this.IsImplicit = true;
570 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
571 // resolved as if the immediately containing namespace body has no using-directives.
573 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
574 // in the using-namespace-directive.
576 // To implement these rules, the expressions in the using directives are resolved using
577 // the "doppelganger" (ghostly bodiless duplicate).
579 NamespaceEntry doppelganger;
580 NamespaceEntry Doppelganger {
582 if (!IsImplicit && doppelganger == null)
583 doppelganger = new NamespaceEntry (ImplicitParent, file, ns);
588 public readonly int ID;
589 public readonly bool IsImplicit;
591 public Namespace NS {
595 public NamespaceEntry Parent {
596 get { return parent; }
599 public NamespaceEntry ImplicitParent {
603 if (implicit_parent == null) {
604 implicit_parent = (parent.NS == ns.Parent)
606 : new NamespaceEntry (parent, file, ns.Parent);
608 return implicit_parent;
613 /// Records a new namespace for resolving name references
615 public void Using (MemberName name, Location loc)
617 if (DeclarationFound){
618 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
624 if (name.Equals (ns.MemberName))
627 if (using_clauses == null)
628 using_clauses = new ArrayList ();
630 foreach (UsingEntry old_entry in using_clauses) {
631 if (name.Equals (old_entry.Name)) {
632 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetName ());
637 UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
638 using_clauses.Add (ue);
641 public void UsingAlias (string name, MemberName alias, Location loc)
643 if (DeclarationFound){
644 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
651 aliases = new Hashtable ();
653 if (aliases.Contains (name)) {
654 AliasEntry ae = (AliasEntry) aliases [name];
655 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
656 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
660 if (RootContext.Version == LanguageVersion.Default &&
661 name == "global" && RootContext.WarningLevel >= 2)
662 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
663 " the global namespace will be used instead");
665 // FIXME: get correct error number. See if the above check can be merged
666 if (extern_aliases != null && extern_aliases.Contains (name)) {
667 AliasEntry ae = (AliasEntry) extern_aliases [name];
668 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
669 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
673 aliases [name] = new LocalAliasEntry (Doppelganger, name, alias, loc);
676 public void UsingExternalAlias (string name, Location loc)
678 if (UsingFound || DeclarationFound) {
679 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
683 // Share the extern_aliases field with the Doppelganger
684 if (extern_aliases == null) {
685 extern_aliases = new ListDictionary ();
686 Doppelganger.extern_aliases = extern_aliases;
689 if (extern_aliases.Contains (name)) {
690 AliasEntry ae = (AliasEntry) extern_aliases [name];
691 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
692 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
696 if (name == "global") {
697 Report.Error (1681, loc, "You cannot redefine the global extern alias");
701 // Register the alias in aliases and extern_aliases, since we need both of them
702 // to keep things simple (different resolution scenarios)
703 ExternAliasEntry alias = new ExternAliasEntry (Doppelganger, name, loc);
704 extern_aliases [name] = alias;
707 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
709 // Precondition: Only simple names (no dots) will be looked up with this function.
710 FullNamedExpression resolved = null;
711 for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
712 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
718 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
720 Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
721 name, t1.FullName, t2.FullName);
724 // Looks-up a alias named @name in this and surrounding namespace declarations
725 public FullNamedExpression LookupAlias (string name)
727 AliasEntry entry = null;
728 for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
729 if (n.extern_aliases != null && (entry = n.extern_aliases [name] as AliasEntry) != null)
731 if (n.aliases != null && (entry = n.aliases [name] as AliasEntry) != null)
734 return entry == null ? null : entry.Resolve ();
737 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
740 // Check whether it's in the namespace.
742 FullNamedExpression fne = NS.Lookup (ds, name, loc);
746 if (extern_aliases != null) {
747 AliasEntry entry = extern_aliases [name] as AliasEntry;
749 return entry.Resolve ();
758 if (aliases != null) {
759 AliasEntry entry = aliases [name] as AliasEntry;
761 return entry.Resolve ();
765 // Check using entries.
767 FullNamedExpression match = null;
768 foreach (Namespace using_ns in GetUsingTable ()) {
769 match = using_ns.Lookup (ds, name, loc);
770 if (match == null || !(match is TypeExpr))
774 Error_AmbiguousTypeReference (loc, name, fne, match);
783 // Our cached computation.
784 readonly Namespace [] empty_namespaces = new Namespace [0];
785 Namespace [] namespace_using_table;
786 Namespace [] GetUsingTable ()
788 if (namespace_using_table != null)
789 return namespace_using_table;
791 if (using_clauses == null) {
792 namespace_using_table = empty_namespaces;
793 return namespace_using_table;
796 ArrayList list = new ArrayList (using_clauses.Count);
798 foreach (UsingEntry ue in using_clauses) {
799 Namespace using_ns = ue.Resolve ();
800 if (using_ns == null)
806 namespace_using_table = new Namespace [list.Count];
807 list.CopyTo (namespace_using_table, 0);
808 return namespace_using_table;
811 readonly string [] empty_using_list = new string [0];
813 public int SymbolFileID {
815 if (symfile_id == 0 && file.SourceFileEntry != null) {
816 int parent_id = parent == null ? 0 : parent.SymbolFileID;
818 string [] using_list = empty_using_list;
819 if (using_clauses != null) {
820 using_list = new string [using_clauses.Count];
821 for (int i = 0; i < using_clauses.Count; i++)
822 using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
825 symfile_id = CodeGen.SymbolWriter.DefineNamespace (ns.Name, file.SourceFileEntry, using_list, parent_id);
831 static void MsgtryRef (string s)
833 Console.WriteLine (" Try using -r:" + s);
836 static void MsgtryPkg (string s)
838 Console.WriteLine (" Try using -pkg:" + s);
841 public static void Error_NamespaceNotFound (Location loc, string name)
843 Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
847 case "Gtk": case "GtkSharp":
848 MsgtryPkg ("gtk-sharp");
851 case "Gdk": case "GdkSharp":
852 MsgtryPkg ("gdk-sharp");
855 case "Glade": case "GladeSharp":
856 MsgtryPkg ("glade-sharp");
859 case "System.Drawing":
860 case "System.Web.Services":
863 case "System.Windows.Forms":
870 /// Used to validate that all the using clauses are correct
871 /// after we are finished parsing all the files.
875 if (extern_aliases != null) {
876 foreach (DictionaryEntry de in extern_aliases)
877 ((AliasEntry) de.Value).Resolve ();
880 if (using_clauses != null) {
881 foreach (UsingEntry ue in using_clauses)
885 if (aliases != null) {
886 foreach (DictionaryEntry de in aliases)
887 ((AliasEntry) de.Value).Resolve ();
892 /// Used to validate that all the using clauses are correct
893 /// after we are finished parsing all the files.
895 static public void VerifyAllUsing ()
897 foreach (NamespaceEntry entry in entries)
898 entry.VerifyUsing ();
901 public string GetSignatureForError ()
903 return ns.GetSignatureForError ();
906 public override string ToString ()
908 return ns.ToString ();