//
// Author:
// Miguel de Icaza (miguel@ximian.com)
+// Marek Safar (marek.safar@seznam.cz)
//
-// (C) 2001 Ximian, Inc.
+// Copyright 2001 Ximian, Inc.
+// Copyright 2003-2008 Novell, Inc.
//
using System;
using System.Collections;
+using System.Collections.Specialized;
+using System.Reflection;
namespace Mono.CSharp {
+ public class RootNamespace : Namespace {
+ //
+ // Points to Mono's GetNamespaces method, an
+ // optimization when running on Mono to fetch all the
+ // namespaces in an assembly
+ //
+ static MethodInfo get_namespaces_method;
+
+ string alias_name;
+ protected Assembly [] referenced_assemblies;
+
+ Hashtable all_namespaces;
+
+ static ListDictionary root_namespaces;
+ public static GlobalRootNamespace Global;
+
+ static RootNamespace ()
+ {
+ get_namespaces_method = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance | BindingFlags.NonPublic);
+
+ Reset ();
+ }
+
+ public static void Reset ()
+ {
+ root_namespaces = new ListDictionary ();
+ Global = new GlobalRootNamespace ();
+ root_namespaces ["global"] = Global;
+ }
+
+ protected RootNamespace (string alias_name)
+ : base (null, String.Empty)
+ {
+ this.alias_name = alias_name;
+ referenced_assemblies = new Assembly [0];
+
+ all_namespaces = new Hashtable ();
+ all_namespaces.Add ("", this);
+ }
+
+ public void AddAssemblyReference (Assembly a)
+ {
+ foreach (Assembly assembly in referenced_assemblies) {
+ if (a == assembly)
+ return;
+ }
+
+ // How to test whether attribute exists without loading the assembly :-(
+#if NET_2_1
+ const string SystemCore = "System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e";
+#else
+ const string SystemCore = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
+#endif
+ if (TypeManager.extension_attribute_type == null &&
+ a.FullName == SystemCore) {
+ TypeManager.extension_attribute_type = a.GetType("System.Runtime.CompilerServices.ExtensionAttribute");
+ }
+
+ int top = referenced_assemblies.Length;
+ Assembly [] n = new Assembly [top + 1];
+ referenced_assemblies.CopyTo (n, 0);
+ n [top] = a;
+ referenced_assemblies = n;
+ }
+
+ public static void DefineRootNamespace (string alias, Assembly assembly)
+ {
+ if (alias == "global") {
+ NamespaceEntry.Error_GlobalNamespaceRedefined (Location.Null);
+ return;
+ }
+
+ RootNamespace retval = GetRootNamespace (alias);
+ if (retval == null) {
+ retval = new RootNamespace (alias);
+ root_namespaces.Add (alias, retval);
+ }
+
+ retval.AddAssemblyReference (assembly);
+ }
+
+ public static RootNamespace GetRootNamespace (string name)
+ {
+ return (RootNamespace) root_namespaces [name];
+ }
+
+ public static void ComputeNamespaces ()
+ {
+ foreach (RootNamespace rn in root_namespaces.Values) {
+ foreach (Assembly a in rn.referenced_assemblies) {
+ try {
+ rn.ComputeNamespaces (a);
+ } catch (TypeLoadException e) {
+ Report.Error (11, Location.Null, e.Message);
+ } catch (System.IO.FileNotFoundException) {
+ Report.Error (12, Location.Null, "An assembly `{0}' is used without being referenced",
+ a.FullName);
+ }
+ }
+ }
+ }
+
+ public virtual Type LookupTypeReflection (string name, Location loc)
+ {
+ Type found_type = null;
+
+ foreach (Assembly a in referenced_assemblies) {
+ Type t = GetTypeInAssembly (a, name);
+ if (t == null)
+ continue;
+
+ if (found_type == null) {
+ found_type = t;
+ continue;
+ }
+
+ Report.SymbolRelatedToPreviousError (found_type);
+ Report.SymbolRelatedToPreviousError (t);
+ Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
+
+ return found_type;
+ }
+
+ return found_type;
+ }
+
+ public void RegisterNamespace (Namespace child)
+ {
+ if (child != this)
+ all_namespaces.Add (child.Name, child);
+ }
+
+ public bool IsNamespace (string name)
+ {
+ return all_namespaces.Contains (name);
+ }
+
+ protected void RegisterNamespace (string dotted_name)
+ {
+ if (dotted_name != null && dotted_name.Length != 0 && ! IsNamespace (dotted_name))
+ GetNamespace (dotted_name, true);
+ }
+
+ void RegisterExtensionMethodClass (Type t)
+ {
+ string n = t.Namespace;
+ Namespace ns = n == null ? Global : (Namespace)all_namespaces [n];
+ if (ns == null)
+ ns = GetNamespace (n, true);
+
+ ns.RegisterExternalExtensionMethodClass (t);
+ }
+
+ protected void ComputeNamespaces (Assembly assembly)
+ {
+ bool contains_extension_methods = TypeManager.extension_attribute_type != null &&
+ assembly.IsDefined(TypeManager.extension_attribute_type, false);
+
+ if (get_namespaces_method != null && !contains_extension_methods) {
+ string [] namespaces = (string []) get_namespaces_method.Invoke (assembly, null);
+ foreach (string ns in namespaces)
+ RegisterNamespace (ns);
+ return;
+ }
+
+ foreach (Type t in assembly.GetExportedTypes ()) {
+ if ((t.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute &&
+ contains_extension_methods && t.IsDefined (TypeManager.extension_attribute_type, false))
+ RegisterExtensionMethodClass (t);
+ else
+ RegisterNamespace (t.Namespace);
+ }
+ }
+
+ protected static Type GetTypeInAssembly (Assembly assembly, string name)
+ {
+ Type t = assembly.GetType (name);
+ if (t == null)
+ return null;
+
+ if (t.IsPointer)
+ throw new InternalErrorException ("Use GetPointerType() to get a pointer");
+
+ TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
+ if (ta == TypeAttributes.NestedPrivate)
+ return null;
+
+ if ((ta == TypeAttributes.NotPublic ||
+ ta == TypeAttributes.NestedAssembly ||
+ ta == TypeAttributes.NestedFamANDAssem) &&
+ !TypeManager.IsThisOrFriendAssembly (t.Assembly))
+ return null;
+
+ return t;
+ }
+
+ public override string ToString ()
+ {
+ return String.Format ("RootNamespace ({0}::)", alias_name);
+ }
+
+ public override string GetSignatureForError ()
+ {
+ return alias_name + "::";
+ }
+ }
+
+ public class GlobalRootNamespace : RootNamespace {
+ Module [] modules;
+
+ public GlobalRootNamespace ()
+ : base ("global")
+ {
+ }
+
+ public Assembly [] Assemblies {
+ get { return referenced_assemblies; }
+ }
+
+ public Module [] Modules {
+ get { return modules; }
+ }
+
+ public void AddModuleReference (Module m)
+ {
+ int top = modules != null ? modules.Length : 0;
+ Module [] n = new Module [top + 1];
+ if (modules != null)
+ modules.CopyTo (n, 0);
+ n [top] = m;
+ modules = n;
+
+ if (m == CodeGen.Module.Builder)
+ return;
+
+ foreach (Type t in m.GetTypes ())
+ RegisterNamespace (t.Namespace);
+ }
+
+ public override void Error_NamespaceDoesNotExist(DeclSpace ds, Location loc, string name)
+ {
+ Report.Error (400, loc, "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
+ name);
+ }
+
+ public override Type LookupTypeReflection (string name, Location loc)
+ {
+ Type found_type = base.LookupTypeReflection (name, loc);
+
+ if (modules != null) {
+ foreach (Module module in modules) {
+ Type t = module.GetType (name);
+ if (t == null)
+ continue;
+
+ if (found_type == null) {
+ found_type = t;
+ continue;
+ }
+
+ Report.SymbolRelatedToPreviousError (found_type);
+ if (loc.IsNull) {
+ DeclSpace ds = TypeManager.LookupDeclSpace (t);
+ Report.Warning (1685, 1, ds.Location, "The type `{0}' conflicts with the predefined type `{1}' and will be ignored",
+ ds.GetSignatureForError (), TypeManager.CSharpName (found_type));
+ return found_type;
+ }
+ Report.SymbolRelatedToPreviousError (t);
+ Report.Warning (436, 2, loc, "The type `{0}' conflicts with the imported type `{1}'. Ignoring the imported type definition",
+ TypeManager.CSharpName (t), TypeManager.CSharpName (found_type));
+ return t;
+ }
+ }
+
+ return found_type;
+ }
+ }
+
/// <summary>
/// Keeps track of the namespaces defined in the C# code.
///
/// This is an Expression to allow it to be referenced in the
/// compiler parse/intermediate tree during name resolution.
/// </summary>
- public class Namespace : FullNamedExpression, IAlias {
- static ArrayList all_namespaces;
- static Hashtable namespaces_map;
+ public class Namespace : FullNamedExpression {
Namespace parent;
string fullname;
- ArrayList entries;
- Hashtable namespaces;
- Hashtable defined_names;
+ IDictionary namespaces;
+ IDictionary declspaces;
Hashtable cached_types;
+ RootNamespace root;
+ ArrayList external_exmethod_classes;
public readonly MemberName MemberName;
- public static Namespace Root;
-
- static Namespace ()
- {
- Reset ();
- }
-
- public static void Reset ()
- {
- all_namespaces = new ArrayList ();
- namespaces_map = new Hashtable ();
-
- Root = new Namespace (null, "");
- }
-
/// <summary>
/// Constructor Takes the current namespace and the
/// name. This is bootstrapped with parent == null
{
// Expression members.
this.eclass = ExprClass.Namespace;
- this.Type = null;
+ this.Type = typeof (Namespace);
this.loc = Location.Null;
this.parent = parent;
- string pname = parent != null ? parent.Name : "";
+ if (parent != null)
+ this.root = parent.root;
+ else
+ this.root = this as RootNamespace;
+
+ if (this.root == null)
+ throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
+
+ string pname = parent != null ? parent.fullname : "";
if (pname == "")
fullname = name;
else
- fullname = parent.Name + "." + name;
+ fullname = parent.fullname + "." + name;
+
+ if (fullname == null)
+ throw new InternalErrorException ("Namespace has a null fullname");
if (parent != null && parent.MemberName != MemberName.Null)
MemberName = new MemberName (parent.MemberName, name);
- else if (name == "")
+ else if (name.Length == 0)
MemberName = MemberName.Null;
else
MemberName = new MemberName (name);
- entries = new ArrayList ();
- namespaces = new Hashtable ();
- defined_names = new Hashtable ();
+ namespaces = new HybridDictionary ();
cached_types = new Hashtable ();
- all_namespaces.Add (this);
- if (namespaces_map.Contains (fullname))
- return;
- namespaces_map [fullname] = true;
+ root.RegisterNamespace (this);
}
public override Expression DoResolve (EmitContext ec)
return this;
}
- public override void Emit (EmitContext ec)
+ public virtual void Error_NamespaceDoesNotExist (DeclSpace ds, Location loc, string name)
+ {
+ if (name.IndexOf ('`') > 0) {
+ FullNamedExpression retval = Lookup (ds, SimpleName.RemoveGenericArity (name), loc);
+ if (retval != null) {
+ Error_TypeArgumentsCannotBeUsed (retval.Type, loc);
+ return;
+ }
+ } else {
+ Type t = LookForAnyGenericType (name);
+ if (t != null) {
+ Error_InvalidNumberOfTypeArguments (t, loc);
+ return;
+ }
+ }
+
+ Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
+ name, GetSignatureForError ());
+ }
+
+ public static void Error_InvalidNumberOfTypeArguments (Type t, Location loc)
{
- throw new InternalErrorException ("Expression tree referenced namespace " + fullname + " during Emit ()");
+ Report.SymbolRelatedToPreviousError (t);
+ Report.Error (305, loc, "Using the generic type `{0}' requires `{1}' type argument(s)",
+ TypeManager.CSharpName(t), TypeManager.GetNumberOfTypeArguments(t).ToString());
}
- public static bool IsNamespace (string name)
+ public static void Error_TypeArgumentsCannotBeUsed (Type t, Location loc)
{
- return namespaces_map [name] != null;
+ Report.SymbolRelatedToPreviousError (t);
+ Error_TypeArgumentsCannotBeUsed (loc, "type", TypeManager.CSharpName (t));
+ }
+
+ public static void Error_TypeArgumentsCannotBeUsed (MethodBase mi, Location loc)
+ {
+ Report.SymbolRelatedToPreviousError (mi);
+ Error_TypeArgumentsCannotBeUsed (loc, "method", TypeManager.CSharpSignature (mi));
+ }
+
+ static void Error_TypeArgumentsCannotBeUsed (Location loc, string type, string name)
+ {
+ Report.Error(308, loc, "The non-generic {0} `{1}' cannot be used with the type arguments",
+ type, name);
+ }
+
+ public override string GetSignatureForError ()
+ {
+ return fullname;
}
public Namespace GetNamespace (string name, bool create)
return ns;
}
- public static Namespace LookupNamespace (string name, bool create)
+ public bool HasDefinition (string name)
{
- return Root.GetNamespace (name, create);
+ return declspaces != null && declspaces [name] != null;
}
- public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
+ TypeExpr LookupType (string name, Location loc)
{
- Namespace ns = GetNamespace (name, false);
- if (ns != null)
- return ns;
+ if (cached_types.Contains (name))
+ return cached_types [name] as TypeExpr;
- TypeExpr te;
- if (cached_types.Contains (name)) {
- te = (TypeExpr) cached_types [name];
- } else {
- Type t;
- DeclSpace tdecl = defined_names [name] as DeclSpace;
+ Type t = null;
+ if (declspaces != null) {
+ DeclSpace tdecl = declspaces [name] as DeclSpace;
if (tdecl != null) {
//
// Note that this is not:
//
tdecl.DefineType ();
t = tdecl.TypeBuilder;
- } else {
- string lookup = this == Namespace.Root ? name : fullname + "." + name;
- t = TypeManager.LookupTypeReflection (lookup);
+
+ if (RootContext.EvalMode){
+ // Replace the TypeBuilder with a System.Type, as
+ // Reflection.Emit fails otherwise (we end up pretty
+ // much with Random type definitions later on).
+ Type tt = t.Assembly.GetType (t.Name);
+ if (tt != null)
+ t = tt;
+ }
}
- te = t == null ? null : new TypeExpression (t, Location.Null);
- cached_types [name] = te;
}
+ string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
+ Type rt = root.LookupTypeReflection (lookup, loc);
- if (te != null && ds != null && !ds.CheckAccessLevel (te.Type))
- return null;
+ // HACK: loc.IsNull when the type is core type
+ if (t == null || (rt != null && loc.IsNull))
+ t = rt;
+ TypeExpr te = t == null ? null : new TypeExpression (t, Location.Null);
+ cached_types [name] = te;
return te;
}
- public void AddNamespaceEntry (NamespaceEntry entry)
+ ///
+ /// Used for better error reporting only
+ ///
+ public Type LookForAnyGenericType (string typeName)
{
- entries.Add (entry);
+ if (declspaces == null)
+ return null;
+
+ typeName = SimpleName.RemoveGenericArity (typeName);
+
+ foreach (DictionaryEntry de in declspaces) {
+ string type_item = (string) de.Key;
+ int pos = type_item.LastIndexOf ('`');
+ if (pos == typeName.Length && String.Compare (typeName, 0, type_item, 0, pos) == 0)
+ return ((DeclSpace) de.Value).TypeBuilder;
+ }
+ return null;
}
- public void DefineName (string name, IAlias o)
+ public FullNamedExpression Lookup (DeclSpace ds, string name, Location loc)
{
- defined_names.Add (name, o);
+ if (namespaces.Contains (name))
+ return (Namespace) namespaces [name];
+
+ return LookupType (name, loc);
}
- static public ArrayList UserDefinedNamespaces {
- get {
- return all_namespaces;
+ public void RegisterExternalExtensionMethodClass (Type type)
+ {
+ if (external_exmethod_classes == null)
+ external_exmethod_classes = new ArrayList ();
+
+ external_exmethod_classes.Add (type);
+ }
+
+ ///
+ /// Looks for extension method in this namespace
+ ///
+ public ArrayList LookupExtensionMethod (Type extensionType, ClassOrStruct currentClass, string name)
+ {
+ ArrayList found = null;
+
+ if (declspaces != null) {
+ IEnumerator e = declspaces.Values.GetEnumerator ();
+ e.Reset ();
+ while (e.MoveNext ()) {
+ Class c = e.Current as Class;
+ if (c == null)
+ continue;
+
+ if (!c.IsStaticClass)
+ continue;
+
+ ArrayList res = c.MemberCache.FindExtensionMethods (extensionType, name, c != currentClass);
+ if (res == null)
+ continue;
+
+ if (found == null)
+ found = res;
+ else
+ found.AddRange (res);
+ }
}
+
+ if (external_exmethod_classes == null)
+ return found;
+
+ foreach (Type t in external_exmethod_classes) {
+ MemberCache m = TypeHandle.GetMemberCache (t);
+ ArrayList res = m.FindExtensionMethods (extensionType, name, true);
+ if (res == null)
+ continue;
+
+ if (found == null)
+ found = res;
+ else
+ found.AddRange (res);
+ }
+
+ return found;
}
+ public void AddDeclSpace (string name, DeclSpace ds)
+ {
+ if (declspaces == null)
+ declspaces = new HybridDictionary ();
+ declspaces.Add (name, ds);
+ }
+
+ public void RemoveDeclSpace (string name)
+ {
+ declspaces.Remove (name);
+ }
+
/// <summary>
/// The qualified name of the current namespace
/// </summary>
public string Name {
- get {
- return fullname;
- }
- }
-
- public override string FullName {
- get {
- return fullname;
- }
+ get { return fullname; }
}
/// <summary>
/// the current namespace declaration
/// </summary>
public Namespace Parent {
- get {
- return parent;
- }
+ get { return parent; }
}
+ }
- public static void DefineNamespaces (SymbolWriter symwriter)
- {
- foreach (Namespace ns in all_namespaces) {
- foreach (NamespaceEntry entry in ns.entries)
- entry.DefineNamespace (symwriter);
+ //
+ // Namespace container as created by the parser
+ //
+ public class NamespaceEntry : IResolveContext {
+
+ class UsingEntry {
+ readonly MemberName name;
+ Namespace resolved;
+
+ public UsingEntry (MemberName name)
+ {
+ this.name = name;
}
- }
- /// <summary>
- /// Used to validate that all the using clauses are correct
- /// after we are finished parsing all the files.
- /// </summary>
- public static void VerifyUsing ()
- {
- foreach (Namespace ns in all_namespaces) {
- foreach (NamespaceEntry entry in ns.entries)
- entry.VerifyUsing ();
+ public string GetSignatureForError ()
+ {
+ return name.GetSignatureForError ();
}
- }
- public override string ToString ()
- {
- if (this == Root)
- return "Namespace (<root>)";
- else
- return String.Format ("Namespace ({0})", Name);
- }
+ public Location Location {
+ get { return name.Location; }
+ }
- bool IAlias.IsType {
- get { return false; }
- }
+ public MemberName MemberName {
+ get { return name; }
+ }
+
+ public string Name {
+ get { return GetSignatureForError (); }
+ }
- TypeExpr IAlias.ResolveAsType (EmitContext ec)
- {
- throw new InvalidOperationException ();
- }
- }
+ public Namespace Resolve (IResolveContext rc)
+ {
+ if (resolved != null)
+ return resolved;
- public class NamespaceEntry
- {
- Namespace ns;
- NamespaceEntry parent, implicit_parent;
- SourceFile file;
- int symfile_id;
- Hashtable aliases;
- ArrayList using_clauses;
- public bool DeclarationFound = false;
+ FullNamedExpression fne = name.GetTypeExpression ().ResolveAsTypeStep (rc, false);
+ if (fne == null)
+ return null;
- //
- // This class holds the location where a using definition is
- // done, and whether it has been used by the program or not.
- //
- // We use this to flag using clauses for namespaces that do not
- // exist.
- //
- public class UsingEntry {
- public MemberName Name;
- public Expression Expr;
- public readonly NamespaceEntry NamespaceEntry;
- public readonly Location Location;
-
- public UsingEntry (NamespaceEntry entry, MemberName name, Location loc)
+ resolved = fne as Namespace;
+ if (resolved == null) {
+ Report.SymbolRelatedToPreviousError (fne.Type);
+ Report.Error (138, Location,
+ "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
+ GetSignatureForError ());
+ }
+ return resolved;
+ }
+
+ public override string ToString ()
{
- Name = name;
- Expr = name.GetTypeExpression (loc);
- NamespaceEntry = entry;
- Location = loc;
+ return Name;
}
+ }
- internal FullNamedExpression resolved;
+ class UsingAliasEntry {
+ public readonly string Alias;
+ public Location Location;
- public Namespace Resolve ()
+ public UsingAliasEntry (string alias, Location loc)
{
- if (resolved != null)
- return resolved as Namespace;
+ this.Alias = alias;
+ this.Location = loc;
+ }
- DeclSpace root = RootContext.Tree.Types;
- root.NamespaceEntry = NamespaceEntry;
- resolved = Expr.ResolveAsTypeStep (root.EmitContext);
- root.NamespaceEntry = null;
+ public virtual FullNamedExpression Resolve (IResolveContext rc)
+ {
+ FullNamedExpression fne = RootNamespace.GetRootNamespace (Alias);
+ if (fne == null) {
+ Report.Error (430, Location,
+ "The extern alias `{0}' was not specified in -reference option",
+ Alias);
+ }
- return resolved as Namespace;
+ return fne;
}
- }
- public class AliasEntry {
- public readonly string Name;
- public readonly Expression Alias;
- public readonly NamespaceEntry NamespaceEntry;
- public readonly Location Location;
-
- public AliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc)
+ public override string ToString ()
{
- Name = name;
- Alias = alias.GetTypeExpression (loc);
- NamespaceEntry = entry;
- Location = loc;
+ return Alias;
}
+
+ }
- FullNamedExpression resolved;
+ class LocalUsingAliasEntry : UsingAliasEntry {
+ Expression resolved;
+ MemberName value;
- public FullNamedExpression Resolve ()
+ public LocalUsingAliasEntry (string alias, MemberName name, Location loc)
+ : base (alias, loc)
{
- if (resolved != null)
- return resolved;
+ this.value = name;
+ }
- DeclSpace root = RootContext.Tree.Types;
- root.NamespaceEntry = NamespaceEntry;
- resolved = Alias.ResolveAsTypeStep (root.EmitContext);
- root.NamespaceEntry = null;
+ public override FullNamedExpression Resolve (IResolveContext rc)
+ {
+ if (resolved != null || value == null)
+ return (FullNamedExpression)resolved;
- return resolved;
+ resolved = value.GetTypeExpression ().ResolveAsTypeStep (rc, false);
+ if (resolved == null) {
+ value = null;
+ return null;
+ }
+
+ // FIXME: This is quite wrong, the accessibility is not global
+ if (resolved.Type != null) {
+ TypeAttributes attr = resolved.Type.Attributes & TypeAttributes.VisibilityMask;
+ if (attr == TypeAttributes.NestedPrivate || attr == TypeAttributes.NestedFamily ||
+ ((attr == TypeAttributes.NestedFamORAssem || attr == TypeAttributes.NestedAssembly) &&
+ TypeManager.LookupDeclSpace (resolved.Type) == null)) {
+ Expression.ErrorIsInaccesible (resolved.Location, resolved.GetSignatureForError ());
+ return null;
+ }
+ }
+
+ return (FullNamedExpression)resolved;
+ }
+
+ public override string ToString ()
+ {
+ return String.Format ("{0} = {1}", Alias, value.GetSignatureForError ());
}
}
- public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name, Location loc)
+ Namespace ns;
+ NamespaceEntry parent, implicit_parent;
+ CompilationUnit file;
+ int symfile_id;
+
+ // Namespace using import block
+ ArrayList using_aliases;
+ ArrayList using_clauses;
+ public bool DeclarationFound = false;
+ // End
+
+ public readonly bool IsImplicit;
+ public readonly DeclSpace SlaveDeclSpace;
+ static readonly Namespace [] empty_namespaces = new Namespace [0];
+ Namespace [] namespace_using_table;
+
+ static ArrayList entries = new ArrayList ();
+
+ public static void Reset ()
+ {
+ entries = new ArrayList ();
+ }
+
+ public NamespaceEntry (NamespaceEntry parent, CompilationUnit file, string name)
{
this.parent = parent;
this.file = file;
- this.IsImplicit = false;
- this.ID = ++next_id;
+ entries.Add (this);
if (parent != null)
ns = parent.NS.GetNamespace (name, true);
else if (name != null)
- ns = Namespace.LookupNamespace (name, true);
+ ns = RootNamespace.Global.GetNamespace (name, true);
else
- ns = Namespace.Root;
- ns.AddNamespaceEntry (this);
+ ns = RootNamespace.Global;
+ SlaveDeclSpace = new RootDeclSpace (this);
}
-
- private NamespaceEntry (NamespaceEntry parent, SourceFile file, Namespace ns)
+ private NamespaceEntry (NamespaceEntry parent, CompilationUnit file, Namespace ns, bool slave)
{
this.parent = parent;
this.file = file;
this.IsImplicit = true;
- this.ID = ++next_id;
this.ns = ns;
+ this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
+ }
+
+ //
+ // Populates the Namespace with some using declarations, used by the
+ // eval mode.
+ //
+ public void Populate (ArrayList source_using_aliases, ArrayList source_using_clauses)
+ {
+ foreach (UsingAliasEntry uae in source_using_aliases){
+ if (using_aliases == null)
+ using_aliases = new ArrayList ();
+
+ using_aliases.Add (uae);
+ }
+
+ foreach (UsingEntry ue in source_using_clauses){
+ if (using_clauses == null)
+ using_clauses = new ArrayList ();
+
+ using_clauses.Add (ue);
+ }
}
+ //
+ // Extracts the using alises and using clauses into a couple of
+ // arrays that might already have the same information; Used by the
+ // C# Eval mode.
+ //
+ public void Extract (ArrayList out_using_aliases, ArrayList out_using_clauses)
+ {
+ if (using_aliases != null){
+ foreach (UsingAliasEntry uae in using_aliases){
+ bool replaced = false;
+
+ for (int i = 0; i < out_using_aliases.Count; i++){
+ UsingAliasEntry out_uea = (UsingAliasEntry) out_using_aliases [i];
+
+ if (out_uea.Alias == uae.Alias){
+ out_using_aliases [i] = uae;
+ replaced = true;
+ break;
+ }
+ }
+ if (!replaced)
+ out_using_aliases.Add (uae);
+ }
+ }
+
+ if (using_clauses != null){
+ foreach (UsingEntry ue in using_clauses){
+ bool found = false;
+
+ foreach (UsingEntry out_ue in out_using_clauses)
+ if (out_ue.Name == ue.Name){
+ found = true;
+ break;
+ }
+ if (!found)
+ out_using_clauses.Add (ue);
+ }
+ }
+ }
+
//
// According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
// resolved as if the immediately containing namespace body has no using-directives.
NamespaceEntry doppelganger;
NamespaceEntry Doppelganger {
get {
- if (!IsImplicit && doppelganger == null)
- doppelganger = new NamespaceEntry (ImplicitParent, file, ns);
+ if (!IsImplicit && doppelganger == null) {
+ doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
+ doppelganger.using_aliases = using_aliases;
+ }
return doppelganger;
}
}
- static int next_id = 0;
- public readonly int ID;
- public readonly bool IsImplicit;
-
public Namespace NS {
- get {
- return ns;
- }
+ get { return ns; }
}
public NamespaceEntry Parent {
- get {
- return parent;
- }
+ get { return parent; }
}
public NamespaceEntry ImplicitParent {
if (implicit_parent == null) {
implicit_parent = (parent.NS == ns.Parent)
? parent
- : new NamespaceEntry (parent, file, ns.Parent);
+ : new NamespaceEntry (parent, file, ns.Parent, false);
}
return implicit_parent;
}
}
- public void DefineName (string name, IAlias o)
- {
- ns.DefineName (name, o);
- }
-
/// <summary>
/// Records a new namespace for resolving name references
/// </summary>
- public void Using (MemberName name, Location loc)
+ public void AddUsing (MemberName name, Location loc)
{
if (DeclarationFound){
- Report.Error (1529, loc, "A using clause must precede all other namespace elements");
- return;
+ Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
}
- if (name.Equals (ns.MemberName))
- return;
-
- if (using_clauses == null)
+ if (using_clauses == null) {
using_clauses = new ArrayList ();
-
- foreach (UsingEntry old_entry in using_clauses) {
- if (name.Equals (old_entry.Name)) {
- if (RootContext.WarningLevel >= 3)
- Report.Warning (105, loc, "The using directive for '{0}' appeared previously in this namespace", name);
- return;
+ } else {
+ foreach (UsingEntry old_entry in using_clauses) {
+ if (name.Equals (old_entry.MemberName)) {
+ Report.SymbolRelatedToPreviousError (old_entry.Location, old_entry.GetSignatureForError ());
+ Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetSignatureForError ());
+ return;
+ }
}
}
-
- UsingEntry ue = new UsingEntry (Doppelganger, name, loc);
- using_clauses.Add (ue);
+ using_clauses.Add (new UsingEntry (name));
}
- public void UsingAlias (string name, MemberName alias, Location loc)
+ public void AddUsingAlias (string alias, MemberName name, Location loc)
{
+ // TODO: This is parser bussines
if (DeclarationFound){
- Report.Error (1529, loc, "A using clause must precede all other namespace elements");
- return;
+ Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
}
- if (aliases == null)
- aliases = new Hashtable ();
-
- if (aliases.Contains (name)){
- AliasEntry ae = (AliasEntry)aliases [name];
- Report.SymbolRelatedToPreviousError (ae.Location, ae.Name);
- Report.Error (1537, loc, "The using alias `" + name +
- "' appeared previously in this namespace");
+ if (RootContext.Version != LanguageVersion.ISO_1 && alias == "global")
+ Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
+ " the global namespace will be used instead");
+
+ AddUsingAlias (new LocalUsingAliasEntry (alias, name, loc));
+ }
+
+ public void AddUsingExternalAlias (string alias, Location loc)
+ {
+ // TODO: Do this in parser
+ bool not_first = using_clauses != null || DeclarationFound;
+ if (using_aliases != null && !not_first) {
+ foreach (UsingAliasEntry uae in using_aliases) {
+ if (uae is LocalUsingAliasEntry) {
+ not_first = true;
+ break;
+ }
+ }
+ }
+
+ if (not_first)
+ Report.Error (439, loc, "An extern alias declaration must precede all other elements");
+
+ if (alias == "global") {
+ Error_GlobalNamespaceRedefined (loc);
return;
}
- aliases [name] = new AliasEntry (Doppelganger, name, alias, loc);
+ AddUsingAlias (new UsingAliasEntry (alias, loc));
}
- public FullNamedExpression LookupAlias (string alias)
+ void AddUsingAlias (UsingAliasEntry uae)
{
- AliasEntry entry = null;
- if (aliases != null)
- entry = (AliasEntry) aliases [alias];
+ if (using_aliases == null) {
+ using_aliases = new ArrayList ();
+ } else {
+ foreach (UsingAliasEntry entry in using_aliases) {
+ if (uae.Alias == entry.Alias) {
+ Report.SymbolRelatedToPreviousError (uae.Location, uae.Alias);
+ Report.Error (1537, entry.Location, "The using alias `{0}' appeared previously in this namespace",
+ entry.Alias);
+ return;
+ }
+ }
+ }
- return entry == null ? null : entry.Resolve ();
+ using_aliases.Add (uae);
}
- static readonly char [] dot_array = { '.' };
-
- public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
+ ///
+ /// Does extension methods look up to find a method which matches name and extensionType.
+ /// Search starts from this namespace and continues hierarchically up to top level.
+ ///
+ public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, ClassOrStruct currentClass, string name, Location loc)
{
- FullNamedExpression resolved = null;
- string rest = null;
+ ArrayList candidates = null;
+ if (currentClass != null) {
+ candidates = ns.LookupExtensionMethod (extensionType, currentClass, name);
+ if (candidates != null)
+ return new ExtensionMethodGroupExpr (candidates, this, extensionType, loc);
+ }
- // If name is of the form `N.I', first lookup `N', then search a member `I' in it.
- int pos = name.IndexOf ('.');
- if (pos >= 0) {
- rest = name.Substring (pos + 1);
- name = name.Substring (0, pos);
+ foreach (Namespace n in GetUsingTable ()) {
+ ArrayList a = n.LookupExtensionMethod (extensionType, null, name);
+ if (a == null)
+ continue;
+
+ if (candidates == null)
+ candidates = a;
+ else
+ candidates.AddRange (a);
}
+ if (candidates != null)
+ return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
+
+ if (parent == null)
+ return null;
+
+ //
+ // Inspect parent namespaces in namespace expression
+ //
+ Namespace parent_ns = ns.Parent;
+ do {
+ candidates = parent_ns.LookupExtensionMethod (extensionType, null, name);
+ if (candidates != null)
+ return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
+
+ parent_ns = parent_ns.Parent;
+ } while (parent_ns != null);
+
+ //
+ // Continue in parent scope
+ //
+ return parent.LookupExtensionMethod (extensionType, currentClass, name, loc);
+ }
+
+ public FullNamedExpression LookupNamespaceOrType (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
+ {
+ // Precondition: Only simple names (no dots) will be looked up with this function.
+ FullNamedExpression resolved = null;
for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
if ((resolved = curr_ns.Lookup (ds, name, loc, ignore_cs0104)) != null)
break;
}
+ return resolved;
+ }
- if (resolved == null || rest == null)
- return resolved;
-
- // Now handle the rest of the the name.
- string [] elements = rest.Split (dot_array);
- int count = elements.Length;
- int i = 0;
- while (i < count && resolved != null && resolved is Namespace) {
- Namespace ns = resolved as Namespace;
- resolved = ns.Lookup (ds, elements [i++], loc);
- }
+ static void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
+ {
+ Report.SymbolRelatedToPreviousError (t1.Type);
+ Report.SymbolRelatedToPreviousError (t2.Type);
+ Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
+ name, t1.GetSignatureForError (), t2.GetSignatureForError ());
+ }
- if (resolved == null || resolved is Namespace)
- return resolved;
+ // Looks-up a alias named @name in this and surrounding namespace declarations
+ public FullNamedExpression LookupAlias (string name)
+ {
+ for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
+ if (n.using_aliases == null)
+ continue;
- Type t = ((TypeExpr) resolved).Type;
-
- while (t != null) {
- if (ds != null && !ds.CheckAccessLevel (t))
- break;
- if (i == count)
- return new TypeExpression (t, Location.Null);
- t = TypeManager.GetNestedType (t, elements [i++]);
+ foreach (UsingAliasEntry ue in n.using_aliases) {
+ if (ue.Alias == name)
+ return ue.Resolve (Doppelganger);
+ }
}
return null;
private FullNamedExpression Lookup (DeclSpace ds, string name, Location loc, bool ignore_cs0104)
{
- // Precondition: Only simple names (no dots) will be looked up with this function.
-
//
// Check whether it's in the namespace.
//
- FullNamedExpression o = NS.Lookup (ds, name, loc);
- if (o != null)
- return o;
-
- if (IsImplicit)
- return null;
+ FullNamedExpression fne = ns.Lookup (ds, name, loc);
//
- // Check aliases.
+ // Check aliases.
//
- o = LookupAlias (name);
- if (o != null)
- return o;
+ if (using_aliases != null) {
+ foreach (UsingAliasEntry ue in using_aliases) {
+ if (ue.Alias == name) {
+ if (fne != null) {
+ if (Doppelganger != null) {
+ // TODO: Namespace has broken location
+ //Report.SymbolRelatedToPreviousError (fne.Location, null);
+ Report.SymbolRelatedToPreviousError (ue.Location, null);
+ Report.Error (576, loc,
+ "Namespace `{0}' contains a definition with same name as alias `{1}'",
+ GetSignatureForError (), name);
+ } else {
+ return fne;
+ }
+ }
+
+ return ue.Resolve (Doppelganger);
+ }
+ }
+ }
+
+ if (fne != null)
+ return fne;
+
+ if (IsImplicit)
+ return null;
//
// Check using entries.
//
- FullNamedExpression t = null, match = null;
+ FullNamedExpression match = null;
foreach (Namespace using_ns in GetUsingTable ()) {
match = using_ns.Lookup (ds, name, loc);
- if ((match != null) && (match is TypeExpr)) {
- if (t != null) {
- if (!ignore_cs0104)
- DeclSpace.Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
-
- return null;
- } else {
- t = match;
- }
+ if (match == null || !(match is TypeExpr))
+ continue;
+ if (fne != null) {
+ if (!ignore_cs0104)
+ Error_AmbiguousTypeReference (loc, name, fne, match);
+ return null;
}
+ fne = match;
}
- return t;
+ return fne;
}
- // Our cached computation.
- Namespace [] namespace_using_table;
- public Namespace[] GetUsingTable ()
+ Namespace [] GetUsingTable ()
{
if (namespace_using_table != null)
return namespace_using_table;
if (using_clauses == null) {
- namespace_using_table = new Namespace [0];
+ namespace_using_table = empty_namespaces;
return namespace_using_table;
}
ArrayList list = new ArrayList (using_clauses.Count);
foreach (UsingEntry ue in using_clauses) {
- Namespace using_ns = ue.Resolve ();
+ Namespace using_ns = ue.Resolve (Doppelganger);
if (using_ns == null)
continue;
list.Add (using_ns);
}
- namespace_using_table = new Namespace [list.Count];
- list.CopyTo (namespace_using_table, 0);
+ namespace_using_table = (Namespace[])list.ToArray (typeof (Namespace));
return namespace_using_table;
}
- public void DefineNamespace (SymbolWriter symwriter)
- {
- if (symfile_id != 0)
- return;
- if (parent != null)
- parent.DefineNamespace (symwriter);
-
- string[] using_list;
- if (using_clauses != null) {
- using_list = new string [using_clauses.Count];
- for (int i = 0; i < using_clauses.Count; i++)
- using_list [i] = ((UsingEntry) using_clauses [i]).Name.ToString ();
- } else {
- using_list = new string [0];
- }
-
- int parent_id = parent != null ? parent.symfile_id : 0;
- if (file.SourceFileEntry == null)
- return;
-
- symfile_id = symwriter.DefineNamespace (
- ns.Name, file.SourceFileEntry, using_list, parent_id);
- }
+ static readonly string [] empty_using_list = new string [0];
public int SymbolFileID {
get {
+ if (symfile_id == 0 && file.SourceFileEntry != null) {
+ int parent_id = parent == null ? 0 : parent.SymbolFileID;
+
+ string [] using_list = empty_using_list;
+ if (using_clauses != null) {
+ using_list = new string [using_clauses.Count];
+ for (int i = 0; i < using_clauses.Count; i++)
+ using_list [i] = ((UsingEntry) using_clauses [i]).MemberName.GetName ();
+ }
+
+ symfile_id = SymbolWriter.DefineNamespace (ns.Name, file.CompileUnitEntry, using_list, parent_id);
+ }
return symfile_id;
}
}
{
Console.WriteLine (" Try using -r:" + s);
}
-
+
static void MsgtryPkg (string s)
{
Console.WriteLine (" Try using -pkg:" + s);
}
- protected void error246 (Location loc, string name)
+ public static void Error_GlobalNamespaceRedefined (Location loc)
+ {
+ Report.Error (1681, loc, "You cannot redefine the global extern alias");
+ }
+
+ public static void Error_NamespaceNotFound (Location loc, string name)
{
- Report.Error (246, loc, "The namespace `" + name +
- "' can not be found (missing assembly reference?)");
+ if (RootContext.EvalMode){
+ // Do not report this, it might be an error on the eval side, and we are lax there.
+ return;
+ }
+
+ Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
+ name);
switch (name) {
case "Gtk": case "GtkSharp":
/// Used to validate that all the using clauses are correct
/// after we are finished parsing all the files.
/// </summary>
- public void VerifyUsing ()
+ void VerifyUsing ()
{
- if (using_clauses != null){
- foreach (UsingEntry ue in using_clauses){
- if (ue.Resolve () != null)
- continue;
-
- if (ue.resolved == null)
- error246 (ue.Location, ue.Name.ToString ());
- else
- Report.Error (138, ue.Location, "The using keyword only lets you specify a namespace, " +
- "`" + ue.Name + "' is a class not a namespace.");
-
- }
+ if (using_aliases != null) {
+ foreach (UsingAliasEntry ue in using_aliases)
+ ue.Resolve (Doppelganger);
}
- if (aliases != null){
- foreach (DictionaryEntry de in aliases){
- AliasEntry alias = (AliasEntry) de.Value;
+ if (using_clauses != null) {
+ foreach (UsingEntry ue in using_clauses)
+ ue.Resolve (Doppelganger);
+ }
+ }
- if (alias.Resolve () != null)
- continue;
+ /// <summary>
+ /// Used to validate that all the using clauses are correct
+ /// after we are finished parsing all the files.
+ /// </summary>
+ static public void VerifyAllUsing ()
+ {
+ foreach (NamespaceEntry entry in entries)
+ entry.VerifyUsing ();
+ }
- error246 (alias.Location, alias.Alias.ToString ());
- }
- }
+ public string GetSignatureForError ()
+ {
+ return ns.GetSignatureForError ();
}
public override string ToString ()
{
- if (NS == Namespace.Root)
- return "NamespaceEntry (<root>)";
- else
- return String.Format ("NamespaceEntry ({0},{1},{2})", ns.Name, IsImplicit, ID);
+ return ns.ToString ();
}
+
+ #region IResolveContext Members
+
+ public DeclSpace DeclContainer {
+ get { return SlaveDeclSpace; }
+ }
+
+ public bool IsInObsoleteScope {
+ get { return SlaveDeclSpace.IsInObsoleteScope; }
+ }
+
+ public bool IsInUnsafeScope {
+ get { return SlaveDeclSpace.IsInUnsafeScope; }
+ }
+
+ public DeclSpace GenericDeclContainer {
+ get { return SlaveDeclSpace; }
+ }
+
+ #endregion
}
}