2 // namespace.cs: Tracks namespaces
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
10 using System.Collections;
11 using System.Collections.Specialized;
12 using System.Reflection;
14 namespace Mono.CSharp {
16 public class RootNamespace : Namespace {
17 static MethodInfo get_namespaces_method;
20 Assembly referenced_assembly;
22 Hashtable all_namespaces;
24 static Hashtable root_namespaces;
25 public static GlobalRootNamespace Global;
27 static RootNamespace ()
29 get_namespaces_method = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance | BindingFlags.NonPublic);
34 public static void Reset ()
36 root_namespaces = new Hashtable ();
37 Global = new GlobalRootNamespace ();
38 root_namespaces ["global"] = Global;
41 protected RootNamespace (string alias_name, Assembly assembly)
42 : base (null, String.Empty)
44 this.alias_name = alias_name;
45 referenced_assembly = assembly;
47 all_namespaces = new Hashtable ();
48 all_namespaces.Add ("", this);
50 if (referenced_assembly != null)
51 ComputeNamespaces (this.referenced_assembly);
54 public static void DefineRootNamespace (string name, Assembly assembly)
56 if (name == "global") {
57 // FIXME: Add proper error number
58 Report.Error (-42, "Cannot define an external alias named `global'");
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 EnsureNamespace (string dotted_name)
89 if (dotted_name != null && dotted_name != "" && ! 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)
102 foreach (Type t in assembly.GetExportedTypes ())
103 EnsureNamespace (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.NotPublic ||
117 ta == TypeAttributes.NestedPrivate ||
118 ta == TypeAttributes.NestedAssembly ||
119 ta == TypeAttributes.NestedFamANDAssem)
125 public override string ToString ()
127 return String.Format ("RootNamespace ({0}::)", alias_name);
130 public override string GetSignatureForError ()
132 return alias_name + "::";
136 public class GlobalRootNamespace : RootNamespace {
137 Assembly [] assemblies;
140 public GlobalRootNamespace ()
141 : base ("global", null)
143 assemblies = new Assembly [0];
146 public Assembly [] Assemblies {
147 get { return assemblies; }
150 public Module [] Modules {
151 get { return modules; }
154 public void AddAssemblyReference (Assembly a)
156 foreach (Assembly assembly in assemblies) {
161 int top = assemblies.Length;
162 Assembly [] n = new Assembly [top + 1];
163 assemblies.CopyTo (n, 0);
167 ComputeNamespaces (a);
170 public void AddModuleReference (Module m)
172 int top = modules != null ? modules.Length : 0;
173 Module [] n = new Module [top + 1];
175 modules.CopyTo (n, 0);
179 if (m == CodeGen.Module.Builder)
182 foreach (Type t in m.GetTypes ())
183 EnsureNamespace (t.Namespace);
186 public override Type LookupTypeReflection (string name, Location loc)
188 Type found_type = null;
190 foreach (Assembly a in assemblies) {
191 Type t = GetTypeInAssembly (a, name);
195 if (found_type == null) {
200 Report.SymbolRelatedToPreviousError (found_type);
201 Report.SymbolRelatedToPreviousError (t);
202 Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
207 if (modules != null) {
208 foreach (Module module in modules) {
209 Type t = module.GetType (name);
213 if (found_type == null) {
218 Report.SymbolRelatedToPreviousError (t);
219 Report.SymbolRelatedToPreviousError (found_type);
220 Report.Warning (436, 2, loc, "Ignoring imported type `{0}' since the current assembly already has a declaration with the same name",
221 TypeManager.CSharpName (t));
231 /// Keeps track of the namespaces defined in the C# code.
233 /// This is an Expression to allow it to be referenced in the
234 /// compiler parse/intermediate tree during name resolution.
236 public class Namespace : FullNamedExpression {
240 Hashtable namespaces;
241 IDictionary declspaces;
242 Hashtable cached_types;
245 public readonly MemberName MemberName;
248 /// Constructor Takes the current namespace and the
249 /// name. This is bootstrapped with parent == null
252 public Namespace (Namespace parent, string name)
254 // Expression members.
255 this.eclass = ExprClass.Namespace;
257 this.loc = Location.Null;
259 this.parent = parent;
262 this.root = parent.root;
264 this.root = this as RootNamespace;
266 if (this.root == null)
267 throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
269 string pname = parent != null ? parent.Name : "";
274 fullname = parent.Name + "." + name;
276 if (fullname == null)
277 throw new InternalErrorException ("Namespace has a null fullname");
279 if (parent != null && parent.MemberName != MemberName.Null)
280 MemberName = new MemberName (parent.MemberName, name);
282 MemberName = MemberName.Null;
284 MemberName = new MemberName (name);
286 namespaces = new Hashtable ();
287 cached_types = new Hashtable ();
289 root.RegisterNamespace (this);
292 public override Expression DoResolve (EmitContext ec)
297 public override void Emit (EmitContext ec)
299 throw new InternalErrorException ("Expression tree referenced namespace " + fullname + " during Emit ()");
302 public override string GetSignatureForError ()
307 public Namespace GetNamespace (string name, bool create)
309 int pos = name.IndexOf ('.');
314 first = name.Substring (0, pos);
318 ns = (Namespace) namespaces [first];
323 ns = new Namespace (this, first);
324 namespaces.Add (first, ns);
328 ns = ns.GetNamespace (name.Substring (pos + 1), create);
333 TypeExpr LookupType (string name, Location loc)
335 if (cached_types.Contains (name))
336 return cached_types [name] as TypeExpr;
339 if (declspaces != null) {
340 DeclSpace tdecl = declspaces [name] as DeclSpace;
343 // Note that this is not:
345 // t = tdecl.DefineType ()
347 // This is to make it somewhat more useful when a DefineType
348 // fails due to problems in nested types (more useful in the sense
349 // of fewer misleading error messages)
352 t = tdecl.TypeBuilder;
355 string lookup = t != null ? t.FullName : (fullname == "" ? name : fullname + "." + name);
356 Type rt = root.LookupTypeReflection (lookup, loc);
360 TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
361 cached_types [name] = te;
365 public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
367 if (namespaces.Contains (name))
368 return (Namespace) namespaces [name];
370 TypeExpr te = LookupType (name, loc);
371 if (te == null || !ds.CheckAccessLevel (te.Type))
377 public void AddDeclSpace (string name, DeclSpace ds)
379 if (declspaces == null)
380 declspaces = new HybridDictionary ();
381 declspaces.Add (name, ds);
385 /// The qualified name of the current namespace
388 get { return fullname; }
391 public override string FullName {
392 get { return fullname; }
396 /// The parent of this namespace, used by the parser to "Pop"
397 /// the current namespace declaration
399 public Namespace Parent {
400 get { return parent; }
403 public override string ToString ()
405 return String.Format ("Namespace ({0})", Name);
409 public class NamespaceEntry {
411 NamespaceEntry parent, implicit_parent;
415 ArrayList using_clauses;
416 public bool DeclarationFound = false;
417 public bool UsingFound = false;
419 static ArrayList entries = new ArrayList ();
421 public static void Reset ()
423 entries = new ArrayList ();
427 // This class holds the location where a using definition is
428 // done, and whether it has been used by the program or not.
430 // We use this to flag using clauses for namespaces that do not
433 public class UsingEntry {
434 public readonly MemberName Name;
435 readonly Expression Expr;
436 readonly NamespaceEntry NamespaceEntry;
437 readonly Location Location;
439 public UsingEntry (NamespaceEntry entry, MemberName name, Location loc)
442 Expr = name.GetTypeExpression ();
443 NamespaceEntry = entry;
447 internal Namespace resolved;
449 public Namespace Resolve ()
451 if (resolved != null)
454 DeclSpace root = RootContext.Tree.Types;
455 root.NamespaceEntry = NamespaceEntry;
456 FullNamedExpression fne = Expr.ResolveAsTypeStep (root.EmitContext, false);
457 root.NamespaceEntry = null;
460 Error_NamespaceNotFound (Location, Name.ToString ());
464 resolved = fne as Namespace;
465 if (resolved == null) {
466 Report.Error (138, Location,
467 "`{0} is a type not a namespace. A using namespace directive can only be applied to namespaces", Name.ToString ());
473 public abstract class AliasEntry {
474 public readonly string Name;
475 public readonly NamespaceEntry NamespaceEntry;
476 public readonly Location Location;
478 protected AliasEntry (NamespaceEntry entry, string name, Location loc)
481 NamespaceEntry = entry;
485 protected FullNamedExpression resolved;
488 public FullNamedExpression Resolve ()
490 if (resolved != null || error)
492 resolved = DoResolve ();
493 if (resolved == null)
498 protected abstract FullNamedExpression DoResolve ();
501 public class LocalAliasEntry : AliasEntry
503 public readonly Expression Alias;
505 public LocalAliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc) :
506 base (entry, name, loc)
508 Alias = alias.GetTypeExpression ();
511 protected override FullNamedExpression DoResolve ()
513 DeclSpace root = RootContext.Tree.Types;
514 root.NamespaceEntry = NamespaceEntry;
515 resolved = Alias.ResolveAsTypeStep (root.EmitContext, false);
516 root.NamespaceEntry = null;
518 if (resolved == null)
519 Error_NamespaceNotFound (Location, Alias.ToString ());
524 public class ExternAliasEntry : AliasEntry
526 public ExternAliasEntry (NamespaceEntry entry, string name, Location loc) :
527 base (entry, name, loc)
531 protected override FullNamedExpression DoResolve ()
533 resolved = RootNamespace.GetRootNamespace (Name);
534 if (resolved == null)
535 Report.Error (430, Location, "The extern alias '" + Name +
536 "' was not specified in a /reference option");
542 public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name, Location loc)
544 this.parent = parent;
546 this.IsImplicit = false;
548 this.ID = entries.Count;
551 ns = parent.NS.GetNamespace (name, true);
552 else if (name != null)
553 ns = RootNamespace.Global.GetNamespace (name, true);
555 ns = RootNamespace.Global;
558 private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns)
560 this.parent = parent;
562 // no need to add self to 'entries', since we don't have any aliases or using entries.
564 this.IsImplicit = true;
569 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
570 // resolved as if the immediately containing namespace body has no using-directives.
572 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
573 // in the using-namespace-directive.
575 // To implement these rules, the expressions in the using directives are resolved using
576 // the "doppelganger" (ghostly bodiless duplicate).
578 NamespaceEntry doppelganger;
579 NamespaceEntry Doppelganger {
581 if (!IsImplicit && doppelganger == null)
582 doppelganger = new NamespaceEntry (ImplicitParent, file, ns);
587 public readonly int ID;
588 public readonly bool IsImplicit;
590 public Namespace NS {
594 public NamespaceEntry Parent {
595 get { return parent; }
598 public NamespaceEntry ImplicitParent {
602 if (implicit_parent == null) {
603 implicit_parent = (parent.NS == ns.Parent)
605 : new NamespaceEntry (parent, file, ns.Parent);
607 return implicit_parent;
612 /// Records a new namespace for resolving name references
614 public void Using (MemberName name, Location loc)
616 if (DeclarationFound){
617 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
621 if (name.Equals (ns.MemberName))
624 if (using_clauses == null)
625 using_clauses = new ArrayList ();
627 foreach (UsingEntry old_entry in using_clauses) {
628 if (name.Equals (old_entry.Name)) {
629 if (RootContext.WarningLevel >= 3)
630 Report.Warning (105, loc, "The using directive for `{0}' appeared previously in this namespace", name);
635 UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
636 using_clauses.Add (ue);
639 public void UsingAlias (string name, MemberName alias, Location loc)
641 if (DeclarationFound){
642 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
647 aliases = new Hashtable ();
649 if (aliases.Contains (name)) {
650 AliasEntry ae = (AliasEntry)aliases [name];
651 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
652 Report.Error (1537, loc, "The using alias `" + name +
653 "' appeared previously in this namespace");
657 if (RootContext.Version == LanguageVersion.Default &&
658 name == "global" && RootContext.WarningLevel >= 2)
659 Report.Warning (440, loc, "An alias named `global' will not be used when resolving 'global::';" +
660 " the global namespace will be used instead");
662 aliases [name] = new LocalAliasEntry (Doppelganger, name, alias, loc);
665 public void UsingExternalAlias (string name, Location loc)
667 if (UsingFound || DeclarationFound) {
668 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
673 aliases = new Hashtable ();
675 if (aliases.Contains (name)) {
676 AliasEntry ae = (AliasEntry) aliases [name];
677 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
678 Report.Error (1537, loc, "The using alias `" + name +
679 "' appeared previously in this namespace");
683 if (name == "global") {
684 Report.Error (1681, loc, "You cannot redefine the global extern alias");
688 aliases [name] = new ExternAliasEntry (Doppelganger, name, loc);
691 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
693 // Precondition: Only simple names (no dots) will be looked up with this function.
694 FullNamedExpression resolved = null;
695 for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
696 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
702 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
704 Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
705 name, t1.FullName, t2.FullName);
708 // Looks-up a alias named @name in this and surrounding namespace declarations
709 public FullNamedExpression LookupAlias (string name)
711 AliasEntry entry = null;
712 // We use Parent rather than ImplicitParent since we know implicit namespace declarations
713 // cannot have using entries.
714 for (NamespaceEntry n = this; n != null; n = n.Parent) {
715 if (n.aliases == null)
717 entry = n.aliases [name] as AliasEntry;
719 return entry.Resolve ();
724 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
727 // Check whether it's in the namespace.
729 FullNamedExpression fne = NS.Lookup (ds, name, loc);
739 if (aliases != null) {
740 AliasEntry entry = aliases [name] as AliasEntry;
742 return entry.Resolve ();
746 // Check using entries.
748 FullNamedExpression match = null;
749 foreach (Namespace using_ns in GetUsingTable ()) {
750 match = using_ns.Lookup (ds, name, loc);
751 if (match == null || !(match is TypeExpr))
755 Error_AmbiguousTypeReference (loc, name, fne, match);
764 // Our cached computation.
765 readonly Namespace [] empty_namespaces = new Namespace [0];
766 Namespace [] namespace_using_table;
767 Namespace [] GetUsingTable ()
769 if (namespace_using_table != null)
770 return namespace_using_table;
772 if (using_clauses == null) {
773 namespace_using_table = empty_namespaces;
774 return namespace_using_table;
777 ArrayList list = new ArrayList (using_clauses.Count);
779 foreach (UsingEntry ue in using_clauses) {
780 Namespace using_ns = ue.Resolve ();
781 if (using_ns == null)
787 namespace_using_table = new Namespace [list.Count];
788 list.CopyTo (namespace_using_table, 0);
789 return namespace_using_table;
792 readonly string [] empty_using_list = new string [0];
794 public int SymbolFileID {
796 if (symfile_id == 0 && file.SourceFileEntry != null) {
797 int parent_id = parent == null ? 0 : parent.SymbolFileID;
799 string [] using_list = empty_using_list;
800 if (using_clauses != null) {
801 using_list = new string [using_clauses.Count];
802 for (int i = 0; i < using_clauses.Count; i++)
803 using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
806 symfile_id = CodeGen.SymbolWriter.DefineNamespace (ns.Name, file.SourceFileEntry, using_list, parent_id);
812 static void MsgtryRef (string s)
814 Console.WriteLine (" Try using -r:" + s);
817 static void MsgtryPkg (string s)
819 Console.WriteLine (" Try using -pkg:" + s);
822 public static void Error_NamespaceNotFound (Location loc, string name)
824 Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
828 case "Gtk": case "GtkSharp":
829 MsgtryPkg ("gtk-sharp");
832 case "Gdk": case "GdkSharp":
833 MsgtryPkg ("gdk-sharp");
836 case "Glade": case "GladeSharp":
837 MsgtryPkg ("glade-sharp");
840 case "System.Drawing":
841 case "System.Web.Services":
844 case "System.Windows.Forms":
851 /// Used to validate that all the using clauses are correct
852 /// after we are finished parsing all the files.
856 if (using_clauses != null) {
857 foreach (UsingEntry ue in using_clauses)
861 if (aliases != null) {
862 foreach (DictionaryEntry de in aliases)
863 ((AliasEntry) de.Value).Resolve ();
868 /// Used to validate that all the using clauses are correct
869 /// after we are finished parsing all the files.
871 static public void VerifyAllUsing ()
873 foreach (NamespaceEntry entry in entries)
874 entry.VerifyUsing ();
877 public string GetSignatureForError ()
879 return ns.GetSignatureForError ();
882 public override string ToString ()
884 return ns.ToString ();