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");
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 if (!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 Type LookupTypeReflection (string name, Location loc)
192 Type found_type = null;
194 foreach (Assembly a in assemblies) {
195 Type t = GetTypeInAssembly (a, name);
199 if (found_type == null) {
204 Report.SymbolRelatedToPreviousError (found_type);
205 Report.SymbolRelatedToPreviousError (t);
206 Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
211 if (modules != null) {
212 foreach (Module module in modules) {
213 Type t = module.GetType (name);
217 if (found_type == null) {
222 Report.SymbolRelatedToPreviousError (t);
223 Report.SymbolRelatedToPreviousError (found_type);
224 Report.Warning (436, 2, loc, "Ignoring imported type `{0}' since the current assembly already has a declaration with the same name",
225 TypeManager.CSharpName (t));
235 /// Keeps track of the namespaces defined in the C# code.
237 /// This is an Expression to allow it to be referenced in the
238 /// compiler parse/intermediate tree during name resolution.
240 public class Namespace : FullNamedExpression {
244 Hashtable namespaces;
245 IDictionary declspaces;
246 Hashtable cached_types;
249 public readonly MemberName MemberName;
252 /// Constructor Takes the current namespace and the
253 /// name. This is bootstrapped with parent == null
256 public Namespace (Namespace parent, string name)
258 // Expression members.
259 this.eclass = ExprClass.Namespace;
261 this.loc = Location.Null;
263 this.parent = parent;
266 this.root = parent.root;
268 this.root = this as RootNamespace;
270 if (this.root == null)
271 throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
273 string pname = parent != null ? parent.Name : "";
278 fullname = parent.Name + "." + name;
280 if (fullname == null)
281 throw new InternalErrorException ("Namespace has a null fullname");
283 if (parent != null && parent.MemberName != MemberName.Null)
284 MemberName = new MemberName (
285 parent.MemberName, name, parent.MemberName.Location);
287 MemberName = MemberName.Null;
289 MemberName = new MemberName (name, Location.Null);
291 namespaces = new Hashtable ();
292 cached_types = new Hashtable ();
294 root.RegisterNamespace (this);
297 public override Expression DoResolve (EmitContext ec)
302 public override void Emit (EmitContext ec)
304 throw new InternalErrorException ("Expression tree referenced namespace " + fullname + " during Emit ()");
307 public override string GetSignatureForError ()
312 public Namespace GetNamespace (string name, bool create)
314 int pos = name.IndexOf ('.');
319 first = name.Substring (0, pos);
323 ns = (Namespace) namespaces [first];
328 ns = new Namespace (this, first);
329 namespaces.Add (first, ns);
333 ns = ns.GetNamespace (name.Substring (pos + 1), create);
338 TypeExpr LookupType (string name, Location loc)
340 if (cached_types.Contains (name))
341 return cached_types [name] as TypeExpr;
344 if (declspaces != null) {
345 DeclSpace tdecl = declspaces [name] as DeclSpace;
348 // Note that this is not:
350 // t = tdecl.DefineType ()
352 // This is to make it somewhat more useful when a DefineType
353 // fails due to problems in nested types (more useful in the sense
354 // of fewer misleading error messages)
357 t = tdecl.TypeBuilder;
360 string lookup = t != null ? t.FullName : (fullname == "" ? name : fullname + "." + name);
361 Type rt = root.LookupTypeReflection (lookup, loc);
365 TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
366 cached_types [name] = te;
370 public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
372 if (namespaces.Contains (name))
373 return (Namespace) namespaces [name];
375 TypeExpr te = LookupType (name, loc);
376 if (te == null || !ds.CheckAccessLevel (te.Type))
382 public void AddDeclSpace (string name, DeclSpace ds)
384 if (declspaces == null)
385 declspaces = new HybridDictionary ();
386 declspaces.Add (name, ds);
390 /// The qualified name of the current namespace
393 get { return fullname; }
396 public override string FullName {
397 get { return fullname; }
401 /// The parent of this namespace, used by the parser to "Pop"
402 /// the current namespace declaration
404 public Namespace Parent {
405 get { return parent; }
408 public override string ToString ()
410 return String.Format ("Namespace ({0})", Name);
414 public class NamespaceEntry {
416 NamespaceEntry parent, implicit_parent;
420 ArrayList using_clauses;
421 public bool DeclarationFound = false;
424 static ArrayList entries = new ArrayList ();
426 public static void Reset ()
428 entries = new ArrayList ();
432 // This class holds the location where a using definition is
433 // done, and whether it has been used by the program or not.
435 // We use this to flag using clauses for namespaces that do not
438 public class UsingEntry {
439 public readonly MemberName Name;
440 readonly Expression Expr;
441 readonly NamespaceEntry NamespaceEntry;
442 readonly Location Location;
444 public UsingEntry (NamespaceEntry entry, MemberName name, Location loc)
447 Expr = name.GetTypeExpression ();
448 NamespaceEntry = entry;
452 internal Namespace resolved;
454 public Namespace Resolve ()
456 if (resolved != null)
459 DeclSpace root = RootContext.Tree.Types;
460 root.NamespaceEntry = NamespaceEntry;
461 FullNamedExpression fne = Expr.ResolveAsTypeStep (root.EmitContext, false);
462 root.NamespaceEntry = null;
465 Error_NamespaceNotFound (Location, Name.ToString ());
469 resolved = fne as Namespace;
470 if (resolved == null) {
471 Report.Error (138, Location,
472 "`{0} is a type not a namespace. A using namespace directive can only be applied to namespaces", Name.ToString ());
478 public abstract class AliasEntry {
479 public readonly string Name;
480 public readonly NamespaceEntry NamespaceEntry;
481 public readonly Location Location;
483 protected AliasEntry (NamespaceEntry entry, string name, Location loc)
486 NamespaceEntry = entry;
490 protected FullNamedExpression resolved;
493 public FullNamedExpression Resolve ()
495 if (resolved != null || error)
497 resolved = DoResolve ();
498 if (resolved == null)
503 protected abstract FullNamedExpression DoResolve ();
506 public class LocalAliasEntry : AliasEntry
508 public readonly Expression Alias;
510 public LocalAliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc) :
511 base (entry, name, loc)
513 Alias = alias.GetTypeExpression ();
516 protected override FullNamedExpression DoResolve ()
518 DeclSpace root = RootContext.Tree.Types;
519 root.NamespaceEntry = NamespaceEntry;
520 resolved = Alias.ResolveAsTypeStep (root.EmitContext, false);
521 root.NamespaceEntry = null;
523 if (resolved == null)
524 Error_NamespaceNotFound (Location, Alias.ToString ());
529 public class ExternAliasEntry : AliasEntry
531 public ExternAliasEntry (NamespaceEntry entry, string name, Location loc) :
532 base (entry, name, loc)
536 protected override FullNamedExpression DoResolve ()
538 resolved = RootNamespace.GetRootNamespace (Name);
539 if (resolved == null)
540 Report.Error (430, Location, "The extern alias '" + Name +
541 "' was not specified in a /reference option");
547 public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name, Location loc)
549 this.parent = parent;
552 this.ID = entries.Count;
555 ns = parent.NS.GetNamespace (name, true);
556 else if (name != null)
557 ns = RootNamespace.Global.GetNamespace (name, true);
559 ns = RootNamespace.Global;
562 private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns)
564 this.parent = parent;
566 // no need to add self to 'entries', since we don't have any aliases or using entries.
568 this.IsImplicit = true;
573 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
574 // resolved as if the immediately containing namespace body has no using-directives.
576 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
577 // in the using-namespace-directive.
579 // To implement these rules, the expressions in the using directives are resolved using
580 // the "doppelganger" (ghostly bodiless duplicate).
582 NamespaceEntry doppelganger;
583 NamespaceEntry Doppelganger {
585 if (!IsImplicit && doppelganger == null)
586 doppelganger = new NamespaceEntry (ImplicitParent, file, ns);
591 public readonly int ID;
592 public readonly bool IsImplicit;
594 public Namespace NS {
598 public NamespaceEntry Parent {
599 get { return parent; }
602 public NamespaceEntry ImplicitParent {
606 if (implicit_parent == null) {
607 implicit_parent = (parent.NS == ns.Parent)
609 : new NamespaceEntry (parent, file, ns.Parent);
611 return implicit_parent;
616 /// Records a new namespace for resolving name references
618 public void Using (MemberName name, Location loc)
620 if (DeclarationFound){
621 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
627 if (name.Equals (ns.MemberName))
630 if (using_clauses == null)
631 using_clauses = new ArrayList ();
633 foreach (UsingEntry old_entry in using_clauses) {
634 if (name.Equals (old_entry.Name)) {
635 Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetName ());
640 UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
641 using_clauses.Add (ue);
644 public void UsingAlias (string name, MemberName alias, Location loc)
646 if (DeclarationFound){
647 Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
654 aliases = new Hashtable ();
656 if (aliases.Contains (name)) {
657 AliasEntry ae = (AliasEntry)aliases [name];
658 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
659 Report.Error (1537, loc, "The using alias `" + name +
660 "' appeared previously in this namespace");
664 if (RootContext.Version == LanguageVersion.Default &&
665 name == "global" && RootContext.WarningLevel >= 2)
666 Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
667 " the global namespace will be used instead");
669 aliases [name] = new LocalAliasEntry (Doppelganger, name, alias, loc);
672 public void UsingExternalAlias (string name, Location loc)
674 if (UsingFound || DeclarationFound) {
675 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
680 aliases = new Hashtable ();
682 if (aliases.Contains (name)) {
683 AliasEntry ae = (AliasEntry) aliases [name];
684 Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
685 Report.Error (1537, loc, "The using alias `" + name +
686 "' appeared previously in this namespace");
690 if (name == "global") {
691 Report.Error (1681, loc, "You cannot redefine the global extern alias");
695 aliases [name] = new ExternAliasEntry (Doppelganger, name, loc);
698 public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
700 // Precondition: Only simple names (no dots) will be looked up with this function.
701 FullNamedExpression resolved = null;
702 for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
703 if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
709 static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
711 Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
712 name, t1.FullName, t2.FullName);
715 // Looks-up a alias named @name in this and surrounding namespace declarations
716 public FullNamedExpression LookupAlias (string name)
718 AliasEntry entry = null;
719 // We use Parent rather than ImplicitParent since we know implicit namespace declarations
720 // cannot have using entries.
721 for (NamespaceEntry n = this; n != null; n = n.Parent) {
722 if (n.aliases == null)
724 entry = n.aliases [name] as AliasEntry;
726 return entry.Resolve ();
731 private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
734 // Check whether it's in the namespace.
736 FullNamedExpression fne = NS.Lookup (ds, name, loc);
746 if (aliases != null) {
747 AliasEntry entry = aliases [name] as AliasEntry;
749 return entry.Resolve ();
753 // Check using entries.
755 FullNamedExpression match = null;
756 foreach (Namespace using_ns in GetUsingTable ()) {
757 match = using_ns.Lookup (ds, name, loc);
758 if (match == null || !(match is TypeExpr))
762 Error_AmbiguousTypeReference (loc, name, fne, match);
771 // Our cached computation.
772 readonly Namespace [] empty_namespaces = new Namespace [0];
773 Namespace [] namespace_using_table;
774 Namespace [] GetUsingTable ()
776 if (namespace_using_table != null)
777 return namespace_using_table;
779 if (using_clauses == null) {
780 namespace_using_table = empty_namespaces;
781 return namespace_using_table;
784 ArrayList list = new ArrayList (using_clauses.Count);
786 foreach (UsingEntry ue in using_clauses) {
787 Namespace using_ns = ue.Resolve ();
788 if (using_ns == null)
794 namespace_using_table = new Namespace [list.Count];
795 list.CopyTo (namespace_using_table, 0);
796 return namespace_using_table;
799 readonly string [] empty_using_list = new string [0];
801 public int SymbolFileID {
803 if (symfile_id == 0 && file.SourceFileEntry != null) {
804 int parent_id = parent == null ? 0 : parent.SymbolFileID;
806 string [] using_list = empty_using_list;
807 if (using_clauses != null) {
808 using_list = new string [using_clauses.Count];
809 for (int i = 0; i < using_clauses.Count; i++)
810 using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
813 symfile_id = CodeGen.SymbolWriter.DefineNamespace (ns.Name, file.SourceFileEntry, using_list, parent_id);
819 static void MsgtryRef (string s)
821 Console.WriteLine (" Try using -r:" + s);
824 static void MsgtryPkg (string s)
826 Console.WriteLine (" Try using -pkg:" + s);
829 public static void Error_NamespaceNotFound (Location loc, string name)
831 Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
835 case "Gtk": case "GtkSharp":
836 MsgtryPkg ("gtk-sharp");
839 case "Gdk": case "GdkSharp":
840 MsgtryPkg ("gdk-sharp");
843 case "Glade": case "GladeSharp":
844 MsgtryPkg ("glade-sharp");
847 case "System.Drawing":
848 case "System.Web.Services":
851 case "System.Windows.Forms":
858 /// Used to validate that all the using clauses are correct
859 /// after we are finished parsing all the files.
863 if (using_clauses != null) {
864 foreach (UsingEntry ue in using_clauses)
868 if (aliases != null) {
869 foreach (DictionaryEntry de in aliases)
870 ((AliasEntry) de.Value).Resolve ();
875 /// Used to validate that all the using clauses are correct
876 /// after we are finished parsing all the files.
878 static public void VerifyAllUsing ()
880 foreach (NamespaceEntry entry in entries)
881 entry.VerifyUsing ();
884 public string GetSignatureForError ()
886 return ns.GetSignatureForError ();
889 public override string ToString ()
891 return ns.ToString ();