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 {
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 DeclSpace root = RootContext.ToplevelTypes;
472 root.NamespaceEntry = NamespaceEntry;
473 FullNamedExpression fne = Expr.ResolveAsTypeStep (root, false);
474 root.NamespaceEntry = null;
477 Error_NamespaceNotFound (Location, Name.ToString ());
481 resolved = fne as Namespace;
482 if (resolved == null) {
483 Report.Error (138, Location,
484 "`{0} is a type not a namespace. A using namespace directive can only be applied to namespaces", Name.ToString ());
490 public abstract class AliasEntry {
491 public readonly string Name;
492 public readonly NamespaceEntry NamespaceEntry;
493 public readonly Location Location;
495 protected AliasEntry (NamespaceEntry entry, string name, Location loc)
498 NamespaceEntry = entry;
502 protected FullNamedExpression resolved;
505 public FullNamedExpression Resolve ()
507 if (resolved != null || error)
509 resolved = DoResolve ();
510 if (resolved == null)
515 protected abstract FullNamedExpression DoResolve ();
518 public class LocalAliasEntry : AliasEntry
520 public readonly Expression Alias;
522 public LocalAliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc) :
523 base (entry, name, loc)
525 Alias = alias.GetTypeExpression ();
528 protected override FullNamedExpression DoResolve ()
530 DeclSpace root = RootContext.ToplevelTypes;
531 root.NamespaceEntry = NamespaceEntry;
532 resolved = Alias.ResolveAsTypeStep (root, false);
533 root.NamespaceEntry = null;
535 if (resolved == null)
538 if (resolved.Type != null) {
539 TypeAttributes attr = resolved.Type.Attributes & TypeAttributes.VisibilityMask;
540 if (attr == TypeAttributes.NestedPrivate || attr == TypeAttributes.NestedFamily ||
541 ((attr == TypeAttributes.NestedFamORAssem || attr == TypeAttributes.NestedAssembly) &&
542 TypeManager.LookupDeclSpace (resolved.Type) == null)) {
543 Expression.ErrorIsInaccesible (Alias.Location, Alias.ToString ());
552 public class ExternAliasEntry : AliasEntry
554 public ExternAliasEntry (NamespaceEntry entry, string name, Location loc) :
555 base (entry, name, loc)
559 protected override FullNamedExpression DoResolve ()
561 resolved = RootNamespace.GetRootNamespace (Name);
562 if (resolved == null)
563 Report.Error (430, Location, "The extern alias '" + Name +
564 "' was not specified in a /reference option");
570 public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name)
572 this.parent = parent;
575 this.ID = entries.Count;
578 ns = parent.NS.GetNamespace (name, true);
579 else if (name != null)
580 ns = RootNamespace.Global.GetNamespace (name, true);
582 ns = RootNamespace.Global;
583 SlaveDeclSpace = new RootDeclSpace (this);
586 private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns)
588 this.parent = parent;
590 // no need to add self to 'entries', since we don't have any aliases or using entries.
592 this.IsImplicit = true;
594 this.SlaveDeclSpace = null;
598 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
599 // resolved as if the immediately containing namespace body has no using-directives.
601 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
602 // in the using-namespace-directive.
604 // To implement these rules, the expressions in the using directives are resolved using
605 // the "doppelganger" (ghostly bodiless duplicate).
607 NamespaceEntry doppelganger;
608 NamespaceEntry Doppelganger {
610 if (!IsImplicit && doppelganger == null)
611 doppelganger = new NamespaceEntry (ImplicitParent, file, ns);
616 public readonly int ID;
617 public readonly bool IsImplicit;
619 public Namespace NS {
623 public NamespaceEntry Parent {
624 get { return parent; }
627 public NamespaceEntry ImplicitParent {
631 if (implicit_parent == null) {
632 implicit_parent = (parent.NS == ns.Parent)
634 : new NamespaceEntry (parent, file, ns.Parent);
636 return implicit_parent;
641 /// Records a new namespace for resolving name references
643 public void Using (MemberName name, Location loc)
645 if (DeclarationFound){
646 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
652 if (name.Equals (ns.MemberName))
655 if (using_clauses == null)
656 using_clauses = new ArrayList ();
658 foreach (UsingEntry old_entry in using_clauses) {
659 if (name.Equals (old_entry.Name)) {
660 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetName ());
665 UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
666 using_clauses.Add (ue);
669 public void UsingAlias (string name, MemberName alias, Location loc)
671 if (DeclarationFound){
672 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
679 aliases = new Hashtable ();
681 if (aliases.Contains (name)) {
682 AliasEntry ae = (AliasEntry) aliases [name];
683 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
684 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
688 if (RootContext.Version == LanguageVersion.Default &&
689 name == "global" && RootContext.WarningLevel >= 2)
690 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
691 " the global namespace will be used instead");
693 // FIXME: get correct error number. See if the above check can be merged
694 if (extern_aliases != null && extern_aliases.Contains (name)) {
695 AliasEntry ae = (AliasEntry) extern_aliases [name];
696 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
697 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
701 aliases [name] = new LocalAliasEntry (Doppelganger, name, alias, loc);
704 public void UsingExternalAlias (string name, Location loc)
706 if (UsingFound || DeclarationFound) {
707 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
711 // Share the extern_aliases field with the Doppelganger
712 if (extern_aliases == null) {
713 extern_aliases = new ListDictionary ();
714 Doppelganger.extern_aliases = extern_aliases;
717 if (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 if (name == "global") {
725 Report.Error (1681, loc, "You cannot redefine the global extern alias");
729 // Register the alias in aliases and extern_aliases, since we need both of them
730 // to keep things simple (different resolution scenarios)
731 ExternAliasEntry alias = new ExternAliasEntry (Doppelganger, name, loc);
732 extern_aliases [name] = alias;
735 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
737 // Precondition: Only simple names (no dots) will be looked up with this function.
738 FullNamedExpression resolved = null;
739 for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
740 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
746 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
748 Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
749 name, t1.FullName, t2.FullName);
752 // Looks-up a alias named @name in this and surrounding namespace declarations
753 public FullNamedExpression LookupAlias (string name)
755 AliasEntry entry = null;
756 for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
757 if (n.extern_aliases != null && (entry = n.extern_aliases [name] as AliasEntry) != null)
759 if (n.aliases != null && (entry = n.aliases [name] as AliasEntry) != null)
762 return entry == null ? null : entry.Resolve ();
765 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
768 // Check whether it's in the namespace.
770 FullNamedExpression fne = NS.Lookup (ds, name, loc);
774 if (extern_aliases != null) {
775 AliasEntry entry = extern_aliases [name] as AliasEntry;
777 return entry.Resolve ();
786 if (aliases != null) {
787 AliasEntry entry = aliases [name] as AliasEntry;
789 return entry.Resolve ();
793 // Check using entries.
795 FullNamedExpression match = null;
796 foreach (Namespace using_ns in GetUsingTable ()) {
797 match = using_ns.Lookup (ds, name, loc);
798 if (match == null || !(match is TypeExpr))
802 Error_AmbiguousTypeReference (loc, name, fne, match);
811 // Our cached computation.
812 readonly Namespace [] empty_namespaces = new Namespace [0];
813 Namespace [] namespace_using_table;
814 Namespace [] GetUsingTable ()
816 if (namespace_using_table != null)
817 return namespace_using_table;
819 if (using_clauses == null) {
820 namespace_using_table = empty_namespaces;
821 return namespace_using_table;
824 ArrayList list = new ArrayList (using_clauses.Count);
826 foreach (UsingEntry ue in using_clauses) {
827 Namespace using_ns = ue.Resolve ();
828 if (using_ns == null)
834 namespace_using_table = new Namespace [list.Count];
835 list.CopyTo (namespace_using_table, 0);
836 return namespace_using_table;
839 readonly string [] empty_using_list = new string [0];
841 public int SymbolFileID {
843 if (symfile_id == 0 && file.SourceFileEntry != null) {
844 int parent_id = parent == null ? 0 : parent.SymbolFileID;
846 string [] using_list = empty_using_list;
847 if (using_clauses != null) {
848 using_list = new string [using_clauses.Count];
849 for (int i = 0; i < using_clauses.Count; i++)
850 using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
853 symfile_id = CodeGen.SymbolWriter.DefineNamespace (ns.Name, file.SourceFileEntry, using_list, parent_id);
859 static void MsgtryRef (string s)
861 Console.WriteLine (" Try using -r:" + s);
864 static void MsgtryPkg (string s)
866 Console.WriteLine (" Try using -pkg:" + s);
869 public static void Error_NamespaceNotFound (Location loc, string name)
871 Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
875 case "Gtk": case "GtkSharp":
876 MsgtryPkg ("gtk-sharp");
879 case "Gdk": case "GdkSharp":
880 MsgtryPkg ("gdk-sharp");
883 case "Glade": case "GladeSharp":
884 MsgtryPkg ("glade-sharp");
887 case "System.Drawing":
888 case "System.Web.Services":
891 case "System.Windows.Forms":
898 /// Used to validate that all the using clauses are correct
899 /// after we are finished parsing all the files.
903 if (extern_aliases != null) {
904 foreach (DictionaryEntry de in extern_aliases)
905 ((AliasEntry) de.Value).Resolve ();
908 if (using_clauses != null) {
909 foreach (UsingEntry ue in using_clauses)
913 if (aliases != null) {
914 foreach (DictionaryEntry de in aliases)
915 ((AliasEntry) de.Value).Resolve ();
920 /// Used to validate that all the using clauses are correct
921 /// after we are finished parsing all the files.
923 static public void VerifyAllUsing ()
925 foreach (NamespaceEntry entry in entries)
926 entry.VerifyUsing ();
929 public string GetSignatureForError ()
931 return ns.GetSignatureForError ();
934 public override string ToString ()
936 return ns.ToString ();