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(DeclSpace ds, 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 (DeclSpace ds, Location loc, string name)
309 if (name.IndexOf ("`") > 0) {
310 FullNamedExpression retval = Lookup (ds, SimpleName.RemoveGenericArity (name), loc);
311 if (retval != null) {
312 Error_TypeArgumentsCannotBeUsed(retval.Type, loc, "type");
316 Type t = LookForAnyGenericType (name);
318 Error_InvalidNumberOfTypeArguments(t, loc);
323 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
327 public static void Error_InvalidNumberOfTypeArguments (Type t, Location loc)
329 Report.SymbolRelatedToPreviousError (t);
330 Report.Error (305, loc, "Using the generic type `{0}' requires `{1}' type argument(s)",
331 TypeManager.CSharpName(t), TypeManager.GetNumberOfTypeArguments(t).ToString());
334 public static void Error_TypeArgumentsCannotBeUsed(Type t, Location loc, string symbol)
336 Report.SymbolRelatedToPreviousError(t);
337 Report.Error(308, loc, "The non-generic {0} `{1}' cannot be used with the type argument(s)",
338 symbol, TypeManager.CSharpName(t));
341 public override void Emit (EmitContext ec)
343 throw new InternalErrorException ("Expression tree referenced namespace " + fullname + " during Emit ()");
346 public override string GetSignatureForError ()
351 public Namespace GetNamespace (string name, bool create)
353 int pos = name.IndexOf ('.');
358 first = name.Substring (0, pos);
362 ns = (Namespace) namespaces [first];
367 ns = new Namespace (this, first);
368 namespaces.Add (first, ns);
372 ns = ns.GetNamespace (name.Substring (pos + 1), create);
377 TypeExpr LookupType (string name, Location loc)
379 if (cached_types.Contains (name))
380 return cached_types [name] as TypeExpr;
383 if (declspaces != null) {
384 DeclSpace tdecl = declspaces [name] as DeclSpace;
387 // Note that this is not:
389 // t = tdecl.DefineType ()
391 // This is to make it somewhat more useful when a DefineType
392 // fails due to problems in nested types (more useful in the sense
393 // of fewer misleading error messages)
396 t = tdecl.TypeBuilder;
399 string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
400 Type rt = root.LookupTypeReflection (lookup, loc);
404 TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
405 cached_types [name] = te;
410 /// Used for better error reporting only
412 public Type LookForAnyGenericType (string typeName)
414 typeName = SimpleName.RemoveGenericArity(typeName);
416 foreach (string type_item in declspaces.Keys) {
417 string[] sep_type = type_item.Split('`');
418 if (sep_type.Length < 2)
421 if (typeName == sep_type [0]) {
422 DeclSpace tdecl = (DeclSpace)declspaces [type_item];
423 return tdecl.TypeBuilder;
429 public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
431 if (namespaces.Contains (name))
432 return (Namespace) namespaces [name];
434 TypeExpr te = LookupType (name, loc);
435 if (te == null || !ds.CheckAccessLevel (te.Type))
441 public void AddDeclSpace (string name, DeclSpace ds)
443 if (declspaces == null)
444 declspaces = new HybridDictionary ();
445 declspaces.Add (name, ds);
449 /// The qualified name of the current namespace
452 get { return fullname; }
455 public override string FullName {
456 get { return fullname; }
460 /// The parent of this namespace, used by the parser to "Pop"
461 /// the current namespace declaration
463 public Namespace Parent {
464 get { return parent; }
467 public override string ToString ()
469 return String.Format ("Namespace ({0})", Name);
473 public class NamespaceEntry {
475 NamespaceEntry parent, implicit_parent;
479 ArrayList using_clauses;
480 public bool DeclarationFound = false;
483 public readonly DeclSpace SlaveDeclSpace;
485 ListDictionary extern_aliases;
487 static ArrayList entries = new ArrayList ();
489 public static void Reset ()
491 entries = new ArrayList ();
495 // This class holds the location where a using definition is
496 // done, and whether it has been used by the program or not.
498 // We use this to flag using clauses for namespaces that do not
501 public class UsingEntry : IResolveContext {
502 public readonly MemberName Name;
503 readonly Expression Expr;
504 readonly NamespaceEntry NamespaceEntry;
505 readonly Location Location;
507 public UsingEntry (NamespaceEntry entry, MemberName name, Location loc)
510 Expr = name.GetTypeExpression ();
511 NamespaceEntry = entry;
515 internal Namespace resolved;
517 public Namespace Resolve ()
519 if (resolved != null)
522 FullNamedExpression fne = Expr.ResolveAsTypeStep (this, false);
524 Error_NamespaceNotFound (Location, Name.ToString ());
528 resolved = fne as Namespace;
529 if (resolved == null) {
530 Report.Error (138, Location,
531 "`{0} is a type not a namespace. A using namespace directive can only be applied to namespaces", Name.ToString ());
536 DeclSpace IResolveContext.DeclContainer {
537 get { return NamespaceEntry.SlaveDeclSpace; }
540 DeclSpace IResolveContext.GenericDeclContainer {
541 get { return NamespaceEntry.SlaveDeclSpace; }
544 bool IResolveContext.IsInObsoleteScope {
545 get { return false; }
547 bool IResolveContext.IsInUnsafeScope {
548 get { return false; }
552 public abstract class AliasEntry {
553 public readonly string Name;
554 public readonly NamespaceEntry NamespaceEntry;
555 public readonly Location Location;
557 protected AliasEntry (NamespaceEntry entry, string name, Location loc)
560 NamespaceEntry = entry;
564 protected FullNamedExpression resolved;
567 public FullNamedExpression Resolve ()
569 if (resolved != null || error)
571 resolved = DoResolve ();
572 if (resolved == null)
577 protected abstract FullNamedExpression DoResolve ();
580 public class LocalAliasEntry : AliasEntry, IResolveContext {
581 public readonly Expression Alias;
583 public LocalAliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc) :
584 base (entry, name, loc)
586 Alias = alias.GetTypeExpression ();
589 protected override FullNamedExpression DoResolve ()
591 resolved = Alias.ResolveAsTypeStep (this, false);
592 if (resolved == null)
595 if (resolved.Type != null) {
596 TypeAttributes attr = resolved.Type.Attributes & TypeAttributes.VisibilityMask;
597 if (attr == TypeAttributes.NestedPrivate || attr == TypeAttributes.NestedFamily ||
598 ((attr == TypeAttributes.NestedFamORAssem || attr == TypeAttributes.NestedAssembly) &&
599 TypeManager.LookupDeclSpace (resolved.Type) == null)) {
600 Expression.ErrorIsInaccesible (Alias.Location, Alias.ToString ());
608 DeclSpace IResolveContext.DeclContainer {
609 get { return NamespaceEntry.SlaveDeclSpace; }
612 DeclSpace IResolveContext.GenericDeclContainer {
613 get { return NamespaceEntry.SlaveDeclSpace; }
616 bool IResolveContext.IsInObsoleteScope {
617 get { return false; }
619 bool IResolveContext.IsInUnsafeScope {
620 get { return false; }
624 public class ExternAliasEntry : AliasEntry {
625 public ExternAliasEntry (NamespaceEntry entry, string name, Location loc) :
626 base (entry, name, loc)
630 protected override FullNamedExpression DoResolve ()
632 resolved = RootNamespace.GetRootNamespace (Name);
633 if (resolved == null)
634 Report.Error (430, Location, "The extern alias '" + Name +
635 "' was not specified in a /reference option");
641 public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name)
643 this.parent = parent;
646 this.ID = entries.Count;
649 ns = parent.NS.GetNamespace (name, true);
650 else if (name != null)
651 ns = RootNamespace.Global.GetNamespace (name, true);
653 ns = RootNamespace.Global;
654 SlaveDeclSpace = new RootDeclSpace (this);
657 private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns, bool slave)
659 this.parent = parent;
661 // no need to add self to 'entries', since we don't have any aliases or using entries.
663 this.IsImplicit = true;
665 this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
669 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
670 // resolved as if the immediately containing namespace body has no using-directives.
672 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
673 // in the using-namespace-directive.
675 // To implement these rules, the expressions in the using directives are resolved using
676 // the "doppelganger" (ghostly bodiless duplicate).
678 NamespaceEntry doppelganger;
679 NamespaceEntry Doppelganger {
681 if (!IsImplicit && doppelganger == null)
682 doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
687 public readonly int ID;
688 public readonly bool IsImplicit;
690 public Namespace NS {
694 public NamespaceEntry Parent {
695 get { return parent; }
698 public NamespaceEntry ImplicitParent {
702 if (implicit_parent == null) {
703 implicit_parent = (parent.NS == ns.Parent)
705 : new NamespaceEntry (parent, file, ns.Parent, false);
707 return implicit_parent;
712 /// Records a new namespace for resolving name references
714 public void Using (MemberName name, Location loc)
716 if (DeclarationFound){
717 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
723 if (name.Equals (ns.MemberName))
726 if (using_clauses == null)
727 using_clauses = new ArrayList ();
729 foreach (UsingEntry old_entry in using_clauses) {
730 if (name.Equals (old_entry.Name)) {
731 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetName ());
736 UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
737 using_clauses.Add (ue);
740 public void UsingAlias (string name, MemberName alias, Location loc)
742 if (DeclarationFound){
743 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
750 aliases = new Hashtable ();
752 if (aliases.Contains (name)) {
753 AliasEntry ae = (AliasEntry) aliases [name];
754 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
755 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
759 if (RootContext.Version == LanguageVersion.Default &&
760 name == "global" && RootContext.WarningLevel >= 2)
761 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
762 " the global namespace will be used instead");
764 // FIXME: get correct error number. See if the above check can be merged
765 if (extern_aliases != null && extern_aliases.Contains (name)) {
766 AliasEntry ae = (AliasEntry) extern_aliases [name];
767 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
768 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
772 aliases [name] = new LocalAliasEntry (Doppelganger, name, alias, loc);
775 public void UsingExternalAlias (string name, Location loc)
777 if (UsingFound || DeclarationFound) {
778 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
782 // Share the extern_aliases field with the Doppelganger
783 if (extern_aliases == null) {
784 extern_aliases = new ListDictionary ();
785 Doppelganger.extern_aliases = extern_aliases;
788 if (extern_aliases.Contains (name)) {
789 AliasEntry ae = (AliasEntry) extern_aliases [name];
790 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
791 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
795 if (name == "global") {
796 Report.Error (1681, loc, "You cannot redefine the global extern alias");
800 // Register the alias in aliases and extern_aliases, since we need both of them
801 // to keep things simple (different resolution scenarios)
802 ExternAliasEntry alias = new ExternAliasEntry (Doppelganger, name, loc);
803 extern_aliases [name] = alias;
806 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
808 // Precondition: Only simple names (no dots) will be looked up with this function.
809 FullNamedExpression resolved = null;
810 for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
811 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
817 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
819 Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
820 name, t1.FullName, t2.FullName);
823 // Looks-up a alias named @name in this and surrounding namespace declarations
824 public FullNamedExpression LookupAlias (string name)
826 AliasEntry entry = null;
827 for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
828 if (n.extern_aliases != null && (entry = n.extern_aliases [name] as AliasEntry) != null)
830 if (n.aliases != null && (entry = n.aliases [name] as AliasEntry) != null)
833 return entry == null ? null : entry.Resolve ();
836 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
839 // Check whether it's in the namespace.
841 FullNamedExpression fne = NS.Lookup (ds, name, loc);
845 if (extern_aliases != null) {
846 AliasEntry entry = extern_aliases [name] as AliasEntry;
848 return entry.Resolve ();
857 if (aliases != null) {
858 AliasEntry entry = aliases [name] as AliasEntry;
860 return entry.Resolve ();
864 // Check using entries.
866 FullNamedExpression match = null;
867 foreach (Namespace using_ns in GetUsingTable ()) {
868 match = using_ns.Lookup (ds, name, loc);
869 if (match == null || !(match is TypeExpr))
873 Error_AmbiguousTypeReference (loc, name, fne, match);
882 // Our cached computation.
883 readonly Namespace [] empty_namespaces = new Namespace [0];
884 Namespace [] namespace_using_table;
885 Namespace [] GetUsingTable ()
887 if (namespace_using_table != null)
888 return namespace_using_table;
890 if (using_clauses == null) {
891 namespace_using_table = empty_namespaces;
892 return namespace_using_table;
895 ArrayList list = new ArrayList (using_clauses.Count);
897 foreach (UsingEntry ue in using_clauses) {
898 Namespace using_ns = ue.Resolve ();
899 if (using_ns == null)
905 namespace_using_table = new Namespace [list.Count];
906 list.CopyTo (namespace_using_table, 0);
907 return namespace_using_table;
910 readonly string [] empty_using_list = new string [0];
912 public int SymbolFileID {
914 if (symfile_id == 0 && file.SourceFileEntry != null) {
915 int parent_id = parent == null ? 0 : parent.SymbolFileID;
917 string [] using_list = empty_using_list;
918 if (using_clauses != null) {
919 using_list = new string [using_clauses.Count];
920 for (int i = 0; i < using_clauses.Count; i++)
921 using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
924 symfile_id = CodeGen.SymbolWriter.DefineNamespace (ns.Name, file.SourceFileEntry, using_list, parent_id);
930 static void MsgtryRef (string s)
932 Console.WriteLine (" Try using -r:" + s);
935 static void MsgtryPkg (string s)
937 Console.WriteLine (" Try using -pkg:" + s);
940 public static void Error_NamespaceNotFound (Location loc, string name)
942 Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
946 case "Gtk": case "GtkSharp":
947 MsgtryPkg ("gtk-sharp");
950 case "Gdk": case "GdkSharp":
951 MsgtryPkg ("gdk-sharp");
954 case "Glade": case "GladeSharp":
955 MsgtryPkg ("glade-sharp");
958 case "System.Drawing":
959 case "System.Web.Services":
962 case "System.Windows.Forms":
969 /// Used to validate that all the using clauses are correct
970 /// after we are finished parsing all the files.
974 if (extern_aliases != null) {
975 foreach (DictionaryEntry de in extern_aliases)
976 ((AliasEntry) de.Value).Resolve ();
979 if (using_clauses != null) {
980 foreach (UsingEntry ue in using_clauses)
984 if (aliases != null) {
985 foreach (DictionaryEntry de in aliases)
986 ((AliasEntry) de.Value).Resolve ();
991 /// Used to validate that all the using clauses are correct
992 /// after we are finished parsing all the files.
994 static public void VerifyAllUsing ()
996 foreach (NamespaceEntry entry in entries)
997 entry.VerifyUsing ();
1000 public string GetSignatureForError ()
1002 return ns.GetSignatureForError ();
1005 public override string ToString ()
1007 return ns.ToString ();