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 Type LookupTypeReflection (string name, Location loc)
189 Type found_type = null;
191 foreach (Assembly a in assemblies) {
192 Type t = GetTypeInAssembly (a, name);
196 if (found_type == null) {
201 Report.SymbolRelatedToPreviousError (found_type);
202 Report.SymbolRelatedToPreviousError (t);
203 Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
208 if (modules != null) {
209 foreach (Module module in modules) {
210 Type t = module.GetType (name);
214 if (found_type == null) {
219 Report.SymbolRelatedToPreviousError (t);
220 Report.SymbolRelatedToPreviousError (found_type);
221 Report.Warning (436, 2, loc, "Ignoring imported type `{0}' since the current assembly already has a declaration with the same name",
222 TypeManager.CSharpName (t));
232 /// Keeps track of the namespaces defined in the C# code.
234 /// This is an Expression to allow it to be referenced in the
235 /// compiler parse/intermediate tree during name resolution.
237 public class Namespace : FullNamedExpression {
241 Hashtable namespaces;
242 IDictionary declspaces;
243 Hashtable cached_types;
246 public readonly MemberName MemberName;
249 /// Constructor Takes the current namespace and the
250 /// name. This is bootstrapped with parent == null
253 public Namespace (Namespace parent, string name)
255 // Expression members.
256 this.eclass = ExprClass.Namespace;
258 this.loc = Location.Null;
260 this.parent = parent;
263 this.root = parent.root;
265 this.root = this as RootNamespace;
267 if (this.root == null)
268 throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
270 string pname = parent != null ? parent.Name : "";
275 fullname = parent.Name + "." + name;
277 if (fullname == null)
278 throw new InternalErrorException ("Namespace has a null fullname");
280 if (parent != null && parent.MemberName != MemberName.Null)
281 MemberName = new MemberName (parent.MemberName, name);
282 else if (name.Length == 0)
283 MemberName = MemberName.Null;
285 MemberName = new MemberName (name);
287 namespaces = new Hashtable ();
288 cached_types = new Hashtable ();
290 root.RegisterNamespace (this);
293 public override Expression DoResolve (EmitContext ec)
298 public override void Emit (EmitContext ec)
300 throw new InternalErrorException ("Expression tree referenced namespace " + fullname + " during Emit ()");
303 public override string GetSignatureForError ()
308 public Namespace GetNamespace (string name, bool create)
310 int pos = name.IndexOf ('.');
315 first = name.Substring (0, pos);
319 ns = (Namespace) namespaces [first];
324 ns = new Namespace (this, first);
325 namespaces.Add (first, ns);
329 ns = ns.GetNamespace (name.Substring (pos + 1), create);
334 TypeExpr LookupType (string name, Location loc)
336 if (cached_types.Contains (name))
337 return cached_types [name] as TypeExpr;
340 if (declspaces != null) {
341 DeclSpace tdecl = declspaces [name] as DeclSpace;
344 // Note that this is not:
346 // t = tdecl.DefineType ()
348 // This is to make it somewhat more useful when a DefineType
349 // fails due to problems in nested types (more useful in the sense
350 // of fewer misleading error messages)
353 t = tdecl.TypeBuilder;
356 string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
357 Type rt = root.LookupTypeReflection (lookup, loc);
361 TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
362 cached_types [name] = te;
366 public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
368 if (namespaces.Contains (name))
369 return (Namespace) namespaces [name];
371 TypeExpr te = LookupType (name, loc);
372 if (te == null || !ds.CheckAccessLevel (te.Type))
378 public void AddDeclSpace (string name, DeclSpace ds)
380 if (declspaces == null)
381 declspaces = new HybridDictionary ();
382 declspaces.Add (name, ds);
386 /// The qualified name of the current namespace
389 get { return fullname; }
392 public override string FullName {
393 get { return fullname; }
397 /// The parent of this namespace, used by the parser to "Pop"
398 /// the current namespace declaration
400 public Namespace Parent {
401 get { return parent; }
404 public override string ToString ()
406 return String.Format ("Namespace ({0})", Name);
410 public class NamespaceEntry {
412 NamespaceEntry parent, implicit_parent;
416 ArrayList using_clauses;
417 public bool DeclarationFound = false;
420 ListDictionary extern_aliases;
422 static ArrayList entries = new ArrayList ();
424 public static void Reset ()
426 entries = new ArrayList ();
430 // This class holds the location where a using definition is
431 // done, and whether it has been used by the program or not.
433 // We use this to flag using clauses for namespaces that do not
436 public class UsingEntry {
437 public readonly MemberName Name;
438 readonly Expression Expr;
439 readonly NamespaceEntry NamespaceEntry;
440 readonly Location Location;
442 public UsingEntry (NamespaceEntry entry, MemberName name, Location loc)
445 Expr = name.GetTypeExpression ();
446 NamespaceEntry = entry;
450 internal Namespace resolved;
452 public Namespace Resolve ()
454 if (resolved != null)
457 DeclSpace root = RootContext.Tree.Types;
458 root.NamespaceEntry = NamespaceEntry;
459 FullNamedExpression fne = Expr.ResolveAsTypeStep (root, false);
460 root.NamespaceEntry = null;
463 Error_NamespaceNotFound (Location, Name.ToString ());
467 resolved = fne as Namespace;
468 if (resolved == null) {
469 Report.Error (138, Location,
470 "`{0} is a type not a namespace. A using namespace directive can only be applied to namespaces", Name.ToString ());
476 public abstract class AliasEntry {
477 public readonly string Name;
478 public readonly NamespaceEntry NamespaceEntry;
479 public readonly Location Location;
481 protected AliasEntry (NamespaceEntry entry, string name, Location loc)
484 NamespaceEntry = entry;
488 protected FullNamedExpression resolved;
491 public FullNamedExpression Resolve ()
493 if (resolved != null || error)
495 resolved = DoResolve ();
496 if (resolved == null)
501 protected abstract FullNamedExpression DoResolve ();
504 public class LocalAliasEntry : AliasEntry
506 public readonly Expression Alias;
508 public LocalAliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc) :
509 base (entry, name, loc)
511 Alias = alias.GetTypeExpression ();
514 protected override FullNamedExpression DoResolve ()
516 DeclSpace root = RootContext.Tree.Types;
517 root.NamespaceEntry = NamespaceEntry;
518 resolved = Alias.ResolveAsTypeStep (root, false);
519 root.NamespaceEntry = null;
521 if (resolved == null)
524 if (resolved.Type != null) {
525 TypeAttributes attr = resolved.Type.Attributes & TypeAttributes.VisibilityMask;
526 if (attr == TypeAttributes.NestedPrivate || attr == TypeAttributes.NestedFamily ||
527 ((attr == TypeAttributes.NestedFamORAssem || attr == TypeAttributes.NestedAssembly) &&
528 TypeManager.LookupDeclSpace (resolved.Type) == null)) {
529 Expression.ErrorIsInaccesible (Alias.Location, Alias.ToString ());
538 public class ExternAliasEntry : AliasEntry
540 public ExternAliasEntry (NamespaceEntry entry, string name, Location loc) :
541 base (entry, name, loc)
545 protected override FullNamedExpression DoResolve ()
547 resolved = RootNamespace.GetRootNamespace (Name);
548 if (resolved == null)
549 Report.Error (430, Location, "The extern alias '" + Name +
550 "' was not specified in a /reference option");
556 public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name)
558 this.parent = parent;
561 this.ID = entries.Count;
564 ns = parent.NS.GetNamespace (name, true);
565 else if (name != null)
566 ns = RootNamespace.Global.GetNamespace (name, true);
568 ns = RootNamespace.Global;
571 private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns)
573 this.parent = parent;
575 // no need to add self to 'entries', since we don't have any aliases or using entries.
577 this.IsImplicit = true;
582 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
583 // resolved as if the immediately containing namespace body has no using-directives.
585 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
586 // in the using-namespace-directive.
588 // To implement these rules, the expressions in the using directives are resolved using
589 // the "doppelganger" (ghostly bodiless duplicate).
591 NamespaceEntry doppelganger;
592 NamespaceEntry Doppelganger {
594 if (!IsImplicit && doppelganger == null)
595 doppelganger = new NamespaceEntry (ImplicitParent, file, ns);
600 public readonly int ID;
601 public readonly bool IsImplicit;
603 public Namespace NS {
607 public NamespaceEntry Parent {
608 get { return parent; }
611 public NamespaceEntry ImplicitParent {
615 if (implicit_parent == null) {
616 implicit_parent = (parent.NS == ns.Parent)
618 : new NamespaceEntry (parent, file, ns.Parent);
620 return implicit_parent;
625 /// Records a new namespace for resolving name references
627 public void Using (MemberName name, Location loc)
629 if (DeclarationFound){
630 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
636 if (name.Equals (ns.MemberName))
639 if (using_clauses == null)
640 using_clauses = new ArrayList ();
642 foreach (UsingEntry old_entry in using_clauses) {
643 if (name.Equals (old_entry.Name)) {
644 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetName ());
649 UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
650 using_clauses.Add (ue);
653 public void UsingAlias (string name, MemberName alias, Location loc)
655 if (DeclarationFound){
656 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
663 aliases = new Hashtable ();
665 if (aliases.Contains (name)) {
666 AliasEntry ae = (AliasEntry) aliases [name];
667 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
668 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
672 if (RootContext.Version == LanguageVersion.Default &&
673 name == "global" && RootContext.WarningLevel >= 2)
674 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
675 " the global namespace will be used instead");
677 // FIXME: get correct error number. See if the above check can be merged
678 if (extern_aliases != null && extern_aliases.Contains (name)) {
679 AliasEntry ae = (AliasEntry) extern_aliases [name];
680 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
681 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
685 aliases [name] = new LocalAliasEntry (Doppelganger, name, alias, loc);
688 public void UsingExternalAlias (string name, Location loc)
690 if (UsingFound || DeclarationFound) {
691 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
695 // Share the extern_aliases field with the Doppelganger
696 if (extern_aliases == null) {
697 extern_aliases = new ListDictionary ();
698 Doppelganger.extern_aliases = extern_aliases;
701 if (extern_aliases.Contains (name)) {
702 AliasEntry ae = (AliasEntry) extern_aliases [name];
703 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
704 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
708 if (name == "global") {
709 Report.Error (1681, loc, "You cannot redefine the global extern alias");
713 // Register the alias in aliases and extern_aliases, since we need both of them
714 // to keep things simple (different resolution scenarios)
715 ExternAliasEntry alias = new ExternAliasEntry (Doppelganger, name, loc);
716 extern_aliases [name] = alias;
719 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
721 // Precondition: Only simple names (no dots) will be looked up with this function.
722 FullNamedExpression resolved = null;
723 for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
724 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
730 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
732 Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
733 name, t1.FullName, t2.FullName);
736 // Looks-up a alias named @name in this and surrounding namespace declarations
737 public FullNamedExpression LookupAlias (string name)
739 AliasEntry entry = null;
740 for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
741 if (n.extern_aliases != null && (entry = n.extern_aliases [name] as AliasEntry) != null)
743 if (n.aliases != null && (entry = n.aliases [name] as AliasEntry) != null)
746 return entry == null ? null : entry.Resolve ();
749 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
752 // Check whether it's in the namespace.
754 FullNamedExpression fne = NS.Lookup (ds, name, loc);
758 if (extern_aliases != null) {
759 AliasEntry entry = extern_aliases [name] as AliasEntry;
761 return entry.Resolve ();
770 if (aliases != null) {
771 AliasEntry entry = aliases [name] as AliasEntry;
773 return entry.Resolve ();
777 // Check using entries.
779 FullNamedExpression match = null;
780 foreach (Namespace using_ns in GetUsingTable ()) {
781 match = using_ns.Lookup (ds, name, loc);
782 if (match == null || !(match is TypeExpr))
786 Error_AmbiguousTypeReference (loc, name, fne, match);
795 // Our cached computation.
796 readonly Namespace [] empty_namespaces = new Namespace [0];
797 Namespace [] namespace_using_table;
798 Namespace [] GetUsingTable ()
800 if (namespace_using_table != null)
801 return namespace_using_table;
803 if (using_clauses == null) {
804 namespace_using_table = empty_namespaces;
805 return namespace_using_table;
808 ArrayList list = new ArrayList (using_clauses.Count);
810 foreach (UsingEntry ue in using_clauses) {
811 Namespace using_ns = ue.Resolve ();
812 if (using_ns == null)
818 namespace_using_table = new Namespace [list.Count];
819 list.CopyTo (namespace_using_table, 0);
820 return namespace_using_table;
823 readonly string [] empty_using_list = new string [0];
825 public int SymbolFileID {
827 if (symfile_id == 0 && file.SourceFileEntry != null) {
828 int parent_id = parent == null ? 0 : parent.SymbolFileID;
830 string [] using_list = empty_using_list;
831 if (using_clauses != null) {
832 using_list = new string [using_clauses.Count];
833 for (int i = 0; i < using_clauses.Count; i++)
834 using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
837 symfile_id = CodeGen.SymbolWriter.DefineNamespace (ns.Name, file.SourceFileEntry, using_list, parent_id);
843 static void MsgtryRef (string s)
845 Console.WriteLine (" Try using -r:" + s);
848 static void MsgtryPkg (string s)
850 Console.WriteLine (" Try using -pkg:" + s);
853 public static void Error_NamespaceNotFound (Location loc, string name)
855 Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
859 case "Gtk": case "GtkSharp":
860 MsgtryPkg ("gtk-sharp");
863 case "Gdk": case "GdkSharp":
864 MsgtryPkg ("gdk-sharp");
867 case "Glade": case "GladeSharp":
868 MsgtryPkg ("glade-sharp");
871 case "System.Drawing":
872 case "System.Web.Services":
875 case "System.Windows.Forms":
882 /// Used to validate that all the using clauses are correct
883 /// after we are finished parsing all the files.
887 if (extern_aliases != null) {
888 foreach (DictionaryEntry de in extern_aliases)
889 ((AliasEntry) de.Value).Resolve ();
892 if (using_clauses != null) {
893 foreach (UsingEntry ue in using_clauses)
897 if (aliases != null) {
898 foreach (DictionaryEntry de in aliases)
899 ((AliasEntry) de.Value).Resolve ();
904 /// Used to validate that all the using clauses are correct
905 /// after we are finished parsing all the files.
907 static public void VerifyAllUsing ()
909 foreach (NamespaceEntry entry in entries)
910 entry.VerifyUsing ();
913 public string GetSignatureForError ()
915 return ns.GetSignatureForError ();
918 public override string ToString ()
920 return ns.ToString ();