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 ListDictionary extern_aliases;
434 static ArrayList entries = new ArrayList ();
436 public static void Reset ()
438 entries = new ArrayList ();
442 // This class holds the location where a using definition is
443 // done, and whether it has been used by the program or not.
445 // We use this to flag using clauses for namespaces that do not
448 public class UsingEntry {
449 public readonly MemberName Name;
450 readonly Expression Expr;
451 readonly NamespaceEntry NamespaceEntry;
452 readonly Location Location;
454 public UsingEntry (NamespaceEntry entry, MemberName name, Location loc)
457 Expr = name.GetTypeExpression ();
458 NamespaceEntry = entry;
462 internal Namespace resolved;
464 public Namespace Resolve ()
466 if (resolved != null)
469 DeclSpace root = RootContext.Tree.Types;
470 root.NamespaceEntry = NamespaceEntry;
471 FullNamedExpression fne = Expr.ResolveAsTypeStep (root, false);
472 root.NamespaceEntry = null;
475 Error_NamespaceNotFound (Location, Name.ToString ());
479 resolved = fne as Namespace;
480 if (resolved == null) {
481 Report.Error (138, Location,
482 "`{0} is a type not a namespace. A using namespace directive can only be applied to namespaces", Name.ToString ());
488 public abstract class AliasEntry {
489 public readonly string Name;
490 public readonly NamespaceEntry NamespaceEntry;
491 public readonly Location Location;
493 protected AliasEntry (NamespaceEntry entry, string name, Location loc)
496 NamespaceEntry = entry;
500 protected FullNamedExpression resolved;
503 public FullNamedExpression Resolve ()
505 if (resolved != null || error)
507 resolved = DoResolve ();
508 if (resolved == null)
513 protected abstract FullNamedExpression DoResolve ();
516 public class LocalAliasEntry : AliasEntry
518 public readonly Expression Alias;
520 public LocalAliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc) :
521 base (entry, name, loc)
523 Alias = alias.GetTypeExpression ();
526 protected override FullNamedExpression DoResolve ()
528 DeclSpace root = RootContext.Tree.Types;
529 root.NamespaceEntry = NamespaceEntry;
530 resolved = Alias.ResolveAsTypeStep (root, false);
531 root.NamespaceEntry = null;
533 if (resolved == null)
536 if (resolved.Type != null) {
537 TypeAttributes attr = resolved.Type.Attributes & TypeAttributes.VisibilityMask;
538 if (attr == TypeAttributes.NestedPrivate || attr == TypeAttributes.NestedFamily ||
539 ((attr == TypeAttributes.NestedFamORAssem || attr == TypeAttributes.NestedAssembly) &&
540 TypeManager.LookupDeclSpace (resolved.Type) == null)) {
541 Expression.ErrorIsInaccesible (Alias.Location, Alias.ToString ());
550 public class ExternAliasEntry : AliasEntry
552 public ExternAliasEntry (NamespaceEntry entry, string name, Location loc) :
553 base (entry, name, loc)
557 protected override FullNamedExpression DoResolve ()
559 resolved = RootNamespace.GetRootNamespace (Name);
560 if (resolved == null)
561 Report.Error (430, Location, "The extern alias '" + Name +
562 "' was not specified in a /reference option");
568 public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name)
570 this.parent = parent;
573 this.ID = entries.Count;
576 ns = parent.NS.GetNamespace (name, true);
577 else if (name != null)
578 ns = RootNamespace.Global.GetNamespace (name, true);
580 ns = RootNamespace.Global;
583 private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns)
585 this.parent = parent;
587 // no need to add self to 'entries', since we don't have any aliases or using entries.
589 this.IsImplicit = true;
594 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
595 // resolved as if the immediately containing namespace body has no using-directives.
597 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
598 // in the using-namespace-directive.
600 // To implement these rules, the expressions in the using directives are resolved using
601 // the "doppelganger" (ghostly bodiless duplicate).
603 NamespaceEntry doppelganger;
604 NamespaceEntry Doppelganger {
606 if (!IsImplicit && doppelganger == null)
607 doppelganger = new NamespaceEntry (ImplicitParent, file, ns);
612 public readonly int ID;
613 public readonly bool IsImplicit;
615 public Namespace NS {
619 public NamespaceEntry Parent {
620 get { return parent; }
623 public NamespaceEntry ImplicitParent {
627 if (implicit_parent == null) {
628 implicit_parent = (parent.NS == ns.Parent)
630 : new NamespaceEntry (parent, file, ns.Parent);
632 return implicit_parent;
637 /// Records a new namespace for resolving name references
639 public void Using (MemberName name, Location loc)
641 if (DeclarationFound){
642 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
648 if (name.Equals (ns.MemberName))
651 if (using_clauses == null)
652 using_clauses = new ArrayList ();
654 foreach (UsingEntry old_entry in using_clauses) {
655 if (name.Equals (old_entry.Name)) {
656 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetName ());
661 UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
662 using_clauses.Add (ue);
665 public void UsingAlias (string name, MemberName alias, Location loc)
667 if (DeclarationFound){
668 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
675 aliases = new Hashtable ();
677 if (aliases.Contains (name)) {
678 AliasEntry ae = (AliasEntry) aliases [name];
679 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
680 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
684 if (RootContext.Version == LanguageVersion.Default &&
685 name == "global" && RootContext.WarningLevel >= 2)
686 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
687 " the global namespace will be used instead");
689 // FIXME: get correct error number. See if the above check can be merged
690 if (extern_aliases != null && extern_aliases.Contains (name)) {
691 AliasEntry ae = (AliasEntry) extern_aliases [name];
692 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
693 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
697 aliases [name] = new LocalAliasEntry (Doppelganger, name, alias, loc);
700 public void UsingExternalAlias (string name, Location loc)
702 if (UsingFound || DeclarationFound) {
703 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
707 // Share the extern_aliases field with the Doppelganger
708 if (extern_aliases == null) {
709 extern_aliases = new ListDictionary ();
710 Doppelganger.extern_aliases = extern_aliases;
713 if (extern_aliases.Contains (name)) {
714 AliasEntry ae = (AliasEntry) extern_aliases [name];
715 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
716 Report.Error (1537, loc, "The using alias `{0}' appeared previously in this namespace", name);
720 if (name == "global") {
721 Report.Error (1681, loc, "You cannot redefine the global extern alias");
725 // Register the alias in aliases and extern_aliases, since we need both of them
726 // to keep things simple (different resolution scenarios)
727 ExternAliasEntry alias = new ExternAliasEntry (Doppelganger, name, loc);
728 extern_aliases [name] = alias;
731 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
733 // Precondition: Only simple names (no dots) will be looked up with this function.
734 FullNamedExpression resolved = null;
735 for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
736 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
742 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
744 Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
745 name, t1.FullName, t2.FullName);
748 // Looks-up a alias named @name in this and surrounding namespace declarations
749 public FullNamedExpression LookupAlias (string name)
751 AliasEntry entry = null;
752 for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
753 if (n.extern_aliases != null && (entry = n.extern_aliases [name] as AliasEntry) != null)
755 if (n.aliases != null && (entry = n.aliases [name] as AliasEntry) != null)
758 return entry == null ? null : entry.Resolve ();
761 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
764 // Check whether it's in the namespace.
766 FullNamedExpression fne = NS.Lookup (ds, name, loc);
770 if (extern_aliases != null) {
771 AliasEntry entry = extern_aliases [name] as AliasEntry;
773 return entry.Resolve ();
782 if (aliases != null) {
783 AliasEntry entry = aliases [name] as AliasEntry;
785 return entry.Resolve ();
789 // Check using entries.
791 FullNamedExpression match = null;
792 foreach (Namespace using_ns in GetUsingTable ()) {
793 match = using_ns.Lookup (ds, name, loc);
794 if (match == null || !(match is TypeExpr))
798 Error_AmbiguousTypeReference (loc, name, fne, match);
807 // Our cached computation.
808 readonly Namespace [] empty_namespaces = new Namespace [0];
809 Namespace [] namespace_using_table;
810 Namespace [] GetUsingTable ()
812 if (namespace_using_table != null)
813 return namespace_using_table;
815 if (using_clauses == null) {
816 namespace_using_table = empty_namespaces;
817 return namespace_using_table;
820 ArrayList list = new ArrayList (using_clauses.Count);
822 foreach (UsingEntry ue in using_clauses) {
823 Namespace using_ns = ue.Resolve ();
824 if (using_ns == null)
830 namespace_using_table = new Namespace [list.Count];
831 list.CopyTo (namespace_using_table, 0);
832 return namespace_using_table;
835 readonly string [] empty_using_list = new string [0];
837 public int SymbolFileID {
839 if (symfile_id == 0 && file.SourceFileEntry != null) {
840 int parent_id = parent == null ? 0 : parent.SymbolFileID;
842 string [] using_list = empty_using_list;
843 if (using_clauses != null) {
844 using_list = new string [using_clauses.Count];
845 for (int i = 0; i < using_clauses.Count; i++)
846 using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
849 symfile_id = CodeGen.SymbolWriter.DefineNamespace (ns.Name, file.SourceFileEntry, using_list, parent_id);
855 static void MsgtryRef (string s)
857 Console.WriteLine (" Try using -r:" + s);
860 static void MsgtryPkg (string s)
862 Console.WriteLine (" Try using -pkg:" + s);
865 public static void Error_NamespaceNotFound (Location loc, string name)
867 Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
871 case "Gtk": case "GtkSharp":
872 MsgtryPkg ("gtk-sharp");
875 case "Gdk": case "GdkSharp":
876 MsgtryPkg ("gdk-sharp");
879 case "Glade": case "GladeSharp":
880 MsgtryPkg ("glade-sharp");
883 case "System.Drawing":
884 case "System.Web.Services":
887 case "System.Windows.Forms":
894 /// Used to validate that all the using clauses are correct
895 /// after we are finished parsing all the files.
899 if (extern_aliases != null) {
900 foreach (DictionaryEntry de in extern_aliases)
901 ((AliasEntry) de.Value).Resolve ();
904 if (using_clauses != null) {
905 foreach (UsingEntry ue in using_clauses)
909 if (aliases != null) {
910 foreach (DictionaryEntry de in aliases)
911 ((AliasEntry) de.Value).Resolve ();
916 /// Used to validate that all the using clauses are correct
917 /// after we are finished parsing all the files.
919 static public void VerifyAllUsing ()
921 foreach (NamespaceEntry entry in entries)
922 entry.VerifyUsing ();
925 public string GetSignatureForError ()
927 return ns.GetSignatureForError ();
930 public override string ToString ()
932 return ns.ToString ();