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 NamespaceEntry.Error_GlobalNamespaceRedefined (Location.Null);
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 RegisterNamespace (string dotted_name)
89 if (dotted_name != null && dotted_name.Length != 0 && ! 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)
98 RegisterNamespace (ns);
102 foreach (Type t in assembly.GetExportedTypes ())
103 RegisterNamespace (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.NestedPrivate)
119 if ((ta == TypeAttributes.NotPublic ||
120 ta == TypeAttributes.NestedAssembly ||
121 ta == TypeAttributes.NestedFamANDAssem) &&
122 !TypeManager.IsFriendAssembly (t.Assembly))
128 public override string ToString ()
130 return String.Format ("RootNamespace ({0}::)", alias_name);
133 public override string GetSignatureForError ()
135 return alias_name + "::";
139 public class GlobalRootNamespace : RootNamespace {
140 Assembly [] assemblies;
143 public GlobalRootNamespace ()
144 : base ("global", null)
146 assemblies = new Assembly [0];
149 public Assembly [] Assemblies {
150 get { return assemblies; }
153 public Module [] Modules {
154 get { return modules; }
157 public void AddAssemblyReference (Assembly a)
159 foreach (Assembly assembly in assemblies) {
164 int top = assemblies.Length;
165 Assembly [] n = new Assembly [top + 1];
166 assemblies.CopyTo (n, 0);
170 ComputeNamespaces (a);
173 public void AddModuleReference (Module m)
175 int top = modules != null ? modules.Length : 0;
176 Module [] n = new Module [top + 1];
178 modules.CopyTo (n, 0);
182 if (m == CodeGen.Module.Builder)
185 foreach (Type t in m.GetTypes ())
186 RegisterNamespace (t.Namespace);
189 public override void Error_NamespaceDoesNotExist(DeclSpace ds, Location loc, string name)
191 Report.Error (400, loc, "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
195 public override Type LookupTypeReflection (string name, Location loc)
197 Type found_type = null;
199 foreach (Assembly a in assemblies) {
200 Type t = GetTypeInAssembly (a, name);
204 if (found_type == null) {
209 Report.SymbolRelatedToPreviousError (found_type);
210 Report.SymbolRelatedToPreviousError (t);
211 Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
216 if (modules != null) {
217 foreach (Module module in modules) {
218 Type t = module.GetType (name);
222 if (found_type == null) {
227 Report.SymbolRelatedToPreviousError (found_type);
229 DeclSpace ds = TypeManager.LookupDeclSpace (t);
230 Report.Warning (1685, 1, ds.Location, "The type `{0}' conflicts with the predefined type `{1}' and will be ignored",
231 ds.GetSignatureForError (), TypeManager.CSharpName (found_type));
234 Report.SymbolRelatedToPreviousError (t);
235 Report.Warning (436, 2, loc, "The type `{0}' conflicts with the imported type `{1}'. Ignoring the imported type definition",
236 TypeManager.CSharpName (t), TypeManager.CSharpName (found_type));
246 /// Keeps track of the namespaces defined in the C# code.
248 /// This is an Expression to allow it to be referenced in the
249 /// compiler parse/intermediate tree during name resolution.
251 public class Namespace : FullNamedExpression {
255 IDictionary namespaces;
256 IDictionary declspaces;
257 Hashtable cached_types;
260 public readonly MemberName MemberName;
263 /// Constructor Takes the current namespace and the
264 /// name. This is bootstrapped with parent == null
267 public Namespace (Namespace parent, string name)
269 // Expression members.
270 this.eclass = ExprClass.Namespace;
271 this.Type = typeof (Namespace);
272 this.loc = Location.Null;
274 this.parent = parent;
277 this.root = parent.root;
279 this.root = this as RootNamespace;
281 if (this.root == null)
282 throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
284 string pname = parent != null ? parent.Name : "";
289 fullname = parent.Name + "." + name;
291 if (fullname == null)
292 throw new InternalErrorException ("Namespace has a null fullname");
294 if (parent != null && parent.MemberName != MemberName.Null)
295 MemberName = new MemberName (parent.MemberName, name);
296 else if (name.Length == 0)
297 MemberName = MemberName.Null;
299 MemberName = new MemberName (name);
301 namespaces = new HybridDictionary ();
302 cached_types = new Hashtable ();
304 root.RegisterNamespace (this);
307 public override Expression DoResolve (EmitContext ec)
312 public virtual void Error_NamespaceDoesNotExist (DeclSpace ds, Location loc, string name)
314 if (name.IndexOf ('`') > 0) {
315 FullNamedExpression retval = Lookup (ds, SimpleName.RemoveGenericArity (name), loc);
316 if (retval != null) {
317 Error_TypeArgumentsCannotBeUsed (retval.Type, loc, "type");
321 Type t = LookForAnyGenericType (name);
323 Error_InvalidNumberOfTypeArguments (t, loc);
328 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
332 public static void Error_InvalidNumberOfTypeArguments (Type t, Location loc)
334 Report.SymbolRelatedToPreviousError (t);
335 Report.Error (305, loc, "Using the generic type `{0}' requires `{1}' type argument(s)",
336 TypeManager.CSharpName(t), TypeManager.GetNumberOfTypeArguments(t).ToString());
339 public static void Error_TypeArgumentsCannotBeUsed(Type t, Location loc, string symbol)
341 Report.SymbolRelatedToPreviousError(t);
342 Report.Error(308, loc, "The non-generic {0} `{1}' cannot be used with the type argument(s)",
343 symbol, TypeManager.CSharpName(t));
346 public override void Emit (EmitContext ec)
348 throw new InternalErrorException ("Expression tree referenced namespace " + fullname + " during Emit ()");
351 public override string GetSignatureForError ()
356 public Namespace GetNamespace (string name, bool create)
358 int pos = name.IndexOf ('.');
363 first = name.Substring (0, pos);
367 ns = (Namespace) namespaces [first];
372 ns = new Namespace (this, first);
373 namespaces.Add (first, ns);
377 ns = ns.GetNamespace (name.Substring (pos + 1), create);
382 TypeExpr LookupType (string name, Location loc)
384 if (cached_types.Contains (name))
385 return cached_types [name] as TypeExpr;
388 if (declspaces != null) {
389 DeclSpace tdecl = declspaces [name] as DeclSpace;
392 // Note that this is not:
394 // t = tdecl.DefineType ()
396 // This is to make it somewhat more useful when a DefineType
397 // fails due to problems in nested types (more useful in the sense
398 // of fewer misleading error messages)
401 t = tdecl.TypeBuilder;
404 string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
405 Type rt = root.LookupTypeReflection (lookup, loc);
407 // HACK: loc.IsNull when the type is core type
408 if (t == null || (rt != null && loc.IsNull))
411 TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
412 cached_types [name] = te;
417 /// Used for better error reporting only
419 public Type LookForAnyGenericType (string typeName)
421 if (declspaces == null)
424 typeName = SimpleName.RemoveGenericArity (typeName);
426 foreach (DictionaryEntry de in declspaces) {
427 string type_item = (string) de.Key;
428 int pos = type_item.LastIndexOf ('`');
429 if (pos == typeName.Length && String.Compare (typeName, 0, type_item, 0, pos) == 0)
430 return ((DeclSpace) de.Value).TypeBuilder;
435 public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
437 if (namespaces.Contains (name))
438 return (Namespace) namespaces [name];
440 TypeExpr te = LookupType (name, loc);
441 if (te == null || !ds.CheckAccessLevel (te.Type))
447 public void AddDeclSpace (string name, DeclSpace ds)
449 if (declspaces == null)
450 declspaces = new HybridDictionary ();
451 declspaces.Add (name, ds);
455 /// The qualified name of the current namespace
458 get { return fullname; }
461 public override string FullName {
462 get { return fullname; }
466 /// The parent of this namespace, used by the parser to "Pop"
467 /// the current namespace declaration
469 public Namespace Parent {
470 get { return parent; }
473 public override string ToString ()
475 return String.Format ("Namespace ({0})", Name);
479 public class NamespaceEntry {
481 NamespaceEntry parent, implicit_parent;
485 ArrayList using_clauses;
486 public bool DeclarationFound = false;
489 public readonly DeclSpace SlaveDeclSpace;
491 ListDictionary extern_aliases;
493 static ArrayList entries = new ArrayList ();
495 public static void Reset ()
497 entries = new ArrayList ();
501 // This class holds the location where a using definition is
502 // done, and whether it has been used by the program or not.
504 // We use this to flag using clauses for namespaces that do not
507 public class UsingEntry : IResolveContext {
508 public readonly MemberName Name;
509 readonly NamespaceEntry NamespaceEntry;
510 readonly Location Location;
512 public UsingEntry (NamespaceEntry entry, MemberName name, Location loc)
515 NamespaceEntry = entry;
519 internal Namespace resolved;
521 public Namespace Resolve ()
523 if (resolved != null)
526 FullNamedExpression fne = Name.GetTypeExpression ().ResolveAsTypeStep (this, false);
528 Error_NamespaceNotFound (Location, Name.ToString ());
532 resolved = fne as Namespace;
533 if (resolved == null) {
534 Report.SymbolRelatedToPreviousError (fne.Type);
535 Report.Error (138, Location,
536 "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces", Name.ToString ());
541 DeclSpace IResolveContext.DeclContainer {
542 get { return NamespaceEntry.SlaveDeclSpace; }
545 DeclSpace IResolveContext.GenericDeclContainer {
546 get { return NamespaceEntry.SlaveDeclSpace; }
549 bool IResolveContext.IsInObsoleteScope {
550 get { return false; }
552 bool IResolveContext.IsInUnsafeScope {
553 get { return false; }
557 public abstract class AliasEntry {
558 public readonly string Name;
559 public readonly NamespaceEntry NamespaceEntry;
560 public readonly Location Location;
562 protected AliasEntry (NamespaceEntry entry, string name, Location loc)
565 NamespaceEntry = entry;
569 protected FullNamedExpression resolved;
572 public FullNamedExpression Resolve ()
574 if (resolved != null || error)
576 resolved = DoResolve ();
577 if (resolved == null)
582 protected abstract FullNamedExpression DoResolve ();
585 public class LocalAliasEntry : AliasEntry, IResolveContext {
586 public readonly Expression Alias;
588 public LocalAliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc) :
589 base (entry, name, loc)
591 Alias = alias.GetTypeExpression ();
594 protected override FullNamedExpression DoResolve ()
596 resolved = Alias.ResolveAsTypeStep (this, false);
597 if (resolved == null)
600 if (resolved.Type != null) {
601 TypeAttributes attr = resolved.Type.Attributes & TypeAttributes.VisibilityMask;
602 if (attr == TypeAttributes.NestedPrivate || attr == TypeAttributes.NestedFamily ||
603 ((attr == TypeAttributes.NestedFamORAssem || attr == TypeAttributes.NestedAssembly) &&
604 TypeManager.LookupDeclSpace (resolved.Type) == null)) {
605 Expression.ErrorIsInaccesible (Alias.Location, Alias.ToString ());
613 DeclSpace IResolveContext.DeclContainer {
614 get { return NamespaceEntry.SlaveDeclSpace; }
617 DeclSpace IResolveContext.GenericDeclContainer {
618 get { return NamespaceEntry.SlaveDeclSpace; }
621 bool IResolveContext.IsInObsoleteScope {
622 get { return false; }
624 bool IResolveContext.IsInUnsafeScope {
625 get { return false; }
629 public class ExternAliasEntry : AliasEntry {
630 public ExternAliasEntry (NamespaceEntry entry, string name, Location loc) :
631 base (entry, name, loc)
635 protected override FullNamedExpression DoResolve ()
637 resolved = RootNamespace.GetRootNamespace (Name);
638 if (resolved == null)
639 Report.Error (430, Location, "The extern alias '" + Name +
640 "' was not specified in a /reference option");
646 public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name)
648 this.parent = parent;
651 this.ID = entries.Count;
654 ns = parent.NS.GetNamespace (name, true);
655 else if (name != null)
656 ns = RootNamespace.Global.GetNamespace (name, true);
658 ns = RootNamespace.Global;
659 SlaveDeclSpace = new RootDeclSpace (this);
662 private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns, bool slave)
664 this.parent = parent;
666 // no need to add self to 'entries', since we don't have any aliases or using entries.
668 this.IsImplicit = true;
670 this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
674 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
675 // resolved as if the immediately containing namespace body has no using-directives.
677 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
678 // in the using-namespace-directive.
680 // To implement these rules, the expressions in the using directives are resolved using
681 // the "doppelganger" (ghostly bodiless duplicate).
683 NamespaceEntry doppelganger;
684 NamespaceEntry Doppelganger {
686 if (!IsImplicit && doppelganger == null)
687 doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
692 public readonly int ID;
693 public readonly bool IsImplicit;
695 public Namespace NS {
699 public NamespaceEntry Parent {
700 get { return parent; }
703 public NamespaceEntry ImplicitParent {
707 if (implicit_parent == null) {
708 implicit_parent = (parent.NS == ns.Parent)
710 : new NamespaceEntry (parent, file, ns.Parent, false);
712 return implicit_parent;
717 /// Records a new namespace for resolving name references
719 public void Using (MemberName name, Location loc)
721 if (DeclarationFound){
722 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
728 if (name.Equals (ns.MemberName))
731 if (using_clauses == null)
732 using_clauses = new ArrayList ();
734 foreach (UsingEntry old_entry in using_clauses) {
735 if (name.Equals (old_entry.Name)) {
736 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetName ());
741 UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
742 using_clauses.Add (ue);
745 public void UsingAlias (string name, MemberName alias, Location loc)
747 if (DeclarationFound){
748 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
755 aliases = new Hashtable ();
757 if (aliases.Contains (name)) {
758 AliasEntry ae = (AliasEntry) aliases [name];
759 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
760 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
764 if (RootContext.Version == LanguageVersion.Default &&
765 name == "global" && RootContext.WarningLevel >= 2)
766 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
767 " the global namespace will be used instead");
769 // FIXME: get correct error number. See if the above check can be merged
770 if (extern_aliases != null && extern_aliases.Contains (name)) {
771 AliasEntry ae = (AliasEntry) extern_aliases [name];
772 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
773 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
777 aliases [name] = new LocalAliasEntry (Doppelganger, name, alias, loc);
780 public void UsingExternalAlias (string name, Location loc)
782 if (UsingFound || DeclarationFound) {
783 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
787 // Share the extern_aliases field with the Doppelganger
788 if (extern_aliases == null) {
789 extern_aliases = new ListDictionary ();
790 Doppelganger.extern_aliases = extern_aliases;
793 if (extern_aliases.Contains (name)) {
794 AliasEntry ae = (AliasEntry) extern_aliases [name];
795 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
796 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
800 if (name == "global") {
801 Error_GlobalNamespaceRedefined (loc);
805 // Register the alias in aliases and extern_aliases, since we need both of them
806 // to keep things simple (different resolution scenarios)
807 ExternAliasEntry alias = new ExternAliasEntry (Doppelganger, name, loc);
808 extern_aliases [name] = alias;
811 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
813 // Precondition: Only simple names (no dots) will be looked up with this function.
814 FullNamedExpression resolved = null;
815 for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
816 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
822 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
824 Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
825 name, t1.FullName, t2.FullName);
828 // Looks-up a alias named @name in this and surrounding namespace declarations
829 public FullNamedExpression LookupAlias (string name)
831 AliasEntry entry = null;
832 for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
833 if (n.extern_aliases != null && (entry = n.extern_aliases [name] as AliasEntry) != null)
835 if (n.aliases != null && (entry = n.aliases [name] as AliasEntry) != null)
838 return entry == null ? null : entry.Resolve ();
841 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
844 // Check whether it's in the namespace.
846 FullNamedExpression fne = ns.Lookup (ds, name, loc);
850 if (extern_aliases != null) {
851 AliasEntry entry = extern_aliases [name] as AliasEntry;
853 return entry.Resolve ();
862 if (aliases != null) {
863 AliasEntry entry = aliases [name] as AliasEntry;
865 return entry.Resolve ();
869 // Check using entries.
871 FullNamedExpression match = null;
872 foreach (Namespace using_ns in GetUsingTable ()) {
873 match = using_ns.Lookup (ds, name, loc);
874 if (match == null || !(match is TypeExpr))
878 Error_AmbiguousTypeReference (loc, name, fne, match);
887 // Our cached computation.
888 static readonly Namespace [] empty_namespaces = new Namespace [0];
889 Namespace [] namespace_using_table;
890 Namespace [] GetUsingTable ()
892 if (namespace_using_table != null)
893 return namespace_using_table;
895 if (using_clauses == null) {
896 namespace_using_table = empty_namespaces;
897 return namespace_using_table;
900 ArrayList list = new ArrayList (using_clauses.Count);
902 foreach (UsingEntry ue in using_clauses) {
903 Namespace using_ns = ue.Resolve ();
904 if (using_ns == null)
910 namespace_using_table = new Namespace [list.Count];
911 list.CopyTo (namespace_using_table, 0);
912 return namespace_using_table;
915 static readonly string [] empty_using_list = new string [0];
917 public int SymbolFileID {
919 if (symfile_id == 0 && file.SourceFileEntry != null) {
920 int parent_id = parent == null ? 0 : parent.SymbolFileID;
922 string [] using_list = empty_using_list;
923 if (using_clauses != null) {
924 using_list = new string [using_clauses.Count];
925 for (int i = 0; i < using_clauses.Count; i++)
926 using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
929 symfile_id = CodeGen.SymbolWriter.DefineNamespace (ns.Name, file.SourceFileEntry, using_list, parent_id);
935 static void MsgtryRef (string s)
937 Console.WriteLine (" Try using -r:" + s);
940 static void MsgtryPkg (string s)
942 Console.WriteLine (" Try using -pkg:" + s);
945 public static void Error_GlobalNamespaceRedefined (Location loc)
947 Report.Error (1681, loc, "You cannot redefine the global extern alias");
950 public static void Error_NamespaceNotFound (Location loc, string name)
952 Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
956 case "Gtk": case "GtkSharp":
957 MsgtryPkg ("gtk-sharp");
960 case "Gdk": case "GdkSharp":
961 MsgtryPkg ("gdk-sharp");
964 case "Glade": case "GladeSharp":
965 MsgtryPkg ("glade-sharp");
968 case "System.Drawing":
969 case "System.Web.Services":
972 case "System.Windows.Forms":
979 /// Used to validate that all the using clauses are correct
980 /// after we are finished parsing all the files.
984 if (extern_aliases != null) {
985 foreach (DictionaryEntry de in extern_aliases)
986 ((AliasEntry) de.Value).Resolve ();
989 if (using_clauses != null) {
990 foreach (UsingEntry ue in using_clauses)
994 if (aliases != null) {
995 foreach (DictionaryEntry de in aliases)
996 ((AliasEntry) de.Value).Resolve ();
1001 /// Used to validate that all the using clauses are correct
1002 /// after we are finished parsing all the files.
1004 static public void VerifyAllUsing ()
1006 foreach (NamespaceEntry entry in entries)
1007 entry.VerifyUsing ();
1010 public string GetSignatureForError ()
1012 return ns.GetSignatureForError ();
1015 public override string ToString ()
1017 return ns.ToString ();