/// </summary>
public abstract class TypeContainer : DeclSpace, IMemberContainer {
- protected class CircularDepException: Exception
- {
- public TypeContainer Container;
- public CircularDepException (TypeContainer tc)
- {
- Container = tc;
- }
- }
-
public class MemberCoreArrayList: ArrayList
{
/// <summary>
public virtual void DefineContainerMembers ()
{
foreach (MemberCore mc in this) {
- mc.Define ();
+ try {
+ mc.Define ();
+ } catch (Exception e) {
+ throw new InternalErrorException (mc.Location, mc.GetSignatureForError (), e);
+ }
}
}
}
}
- public class MethodArrayList: MemberCoreArrayList
+ public class MethodArrayList : MemberCoreArrayList
{
[Flags]
enum CachedMethods {
{
base.DefineContainerMembers ();
- if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
- Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
+ if (HasEquals && !HasGetHashCode) {
+ Report.Warning (659, 3, container.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
}
}
-
}
- public sealed class IndexerArrayList: MemberCoreArrayList
+ public sealed class IndexerArrayList : MemberCoreArrayList
{
/// <summary>
/// The indexer name for this container
{
flags = f;
- ret_type = o.OperatorMethod.ReturnType;
- Type [] pt = o.OperatorMethod.ParameterTypes;
+ ret_type = o.MemberType;
+ Type [] pt = o.ParameterTypes;
type1 = pt [0];
type2 = pt [1];
op = o;
//
void CheckPairedOperators ()
{
- Hashtable pairs = new Hashtable (null, null);
+ IDictionary pairs = new HybridDictionary ();
Operator true_op = null;
Operator false_op = null;
bool has_equality_or_inequality = false;
int reg = 0;
// Skip erroneous code.
- if (op.OperatorMethod == null)
+ if (op.MethodBuilder == null)
continue;
switch (op.OperatorType){
if (true_op != null){
if (false_op == null)
- Report.Error (216, true_op.Location, "operator true requires a matching operator false");
+ Report.Error (216, true_op.Location, "The operator `{0}' requires a matching operator `false' to also be defined",
+ true_op.GetSignatureForError ());
} else if (false_op != null)
- Report.Error (216, false_op.Location, "operator false requires a matching operator true");
+ Report.Error (216, false_op.Location, "The operator `{0}' requires a matching operator `true' to also be defined",
+ false_op.GetSignatureForError ());
//
// Look for the mistakes.
break;
}
Report.Error (216, oe.op.Location,
- "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
+ "The operator `{0}' requires a matching operator `{1}' to also be defined",
+ oe.op.GetSignatureForError (), s);
}
if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
if (container.Methods == null || !container.Methods.HasEquals)
- Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
+ Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
if (container.Methods == null || !container.Methods.HasGetHashCode)
- Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
+ Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
}
}
public readonly Kind Kind;
// Holds a list of classes and structures
- ArrayList types;
+ protected ArrayList types;
// Holds the list of properties
MemberCoreArrayList properties;
// Holds the operators
MemberCoreArrayList operators;
- // Holds the iterators
- ArrayList iterators;
-
- // Holds the parts of a partial class;
- ArrayList parts;
+ // Holds the compiler generated classes
+ ArrayList compiler_generated;
//
// Pointers to the default constructor and the default static constructor
protected Constructor default_static_constructor;
//
- // Whether we have at least one non-static field
+ // Points to the first non-static field added to the container.
//
- bool have_nonstatic_fields = false;
-
+ // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
+ // and the first one's as good as any.
+ //
+ FieldBase first_nonstatic_field = null;
+
//
// This one is computed after we can distinguish interfaces
// from classes from the arraylist `type_bases'
//
- string base_class_name;
TypeExpr base_type;
+ TypeExpr[] iface_exprs;
+ Type GenericType;
ArrayList type_bases;
+ bool members_resolved;
+ bool members_resolved_ok;
bool members_defined;
bool members_defined_ok;
// The interfaces we implement.
- protected Type [] ifaces;
- protected Type ptype;
+ protected Type[] ifaces;
// The base member cache and our member cache
MemberCache base_cache;
public const string DefaultIndexerName = "Item";
- // This is used to catch recursive definitions in declarations.
- protected bool InTransit;
-
- public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
- Attributes attrs, Kind kind, Location l)
- : base (ns, parent, name, attrs, l)
+#if GMCS_SOURCE
+ GenericTypeParameterBuilder[] gen_params;
+#endif
+
+ ArrayList partial_parts;
+
+ /// <remarks>
+ /// The pending methods that need to be implemented
+ // (interfaces or abstract methods)
+ /// </remarks>
+ PendingImplementation pending;
+
+ public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
+ Attributes attrs, Kind kind)
+ : base (ns, parent, name, attrs)
{
- if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
+ if (parent != null && parent.NamespaceEntry != ns)
throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
this.Kind = kind;
-
- types = new ArrayList ();
-
- base_class_name = null;
+ this.PartialContainer = this;
}
- public bool AddToMemberContainer (MemberCore symbol)
+ public bool AddMember (MemberCore symbol)
{
- return AddToContainer (symbol, symbol.Name);
+ return AddToContainer (symbol, symbol.MemberName.MethodName);
}
- bool AddToTypeContainer (DeclSpace ds)
+ protected virtual bool AddMemberType (DeclSpace ds)
{
- // Parent == null ==> this == RootContext.Tree.Types
- return AddToContainer (ds, (Parent == null) ? ds.Name : ds.Basename);
+ return AddToContainer (ds, ds.Basename);
}
public void AddConstant (Const constant)
{
- if (!AddToMemberContainer (constant))
+ if (!AddMember (constant))
return;
if (constants == null)
public void AddEnum (Mono.CSharp.Enum e)
{
- if (!AddToTypeContainer (e))
+ if (!AddMemberType (e))
return;
if (enums == null)
enums.Add (e);
}
-
- public void AddClassOrStruct (TypeContainer c)
+
+ public TypeContainer AddTypeContainer (TypeContainer tc, bool is_interface)
{
- if (!AddToTypeContainer (c))
- return;
+ if (!AddMemberType (tc))
+ return tc;
+
+ if (is_interface) {
+ if (interfaces == null)
+ interfaces = new MemberCoreArrayList ();
+ interfaces.Add (tc);
+ } else {
+ if (types == null)
+ types = new ArrayList (2);
+ types.Add (tc);
+ }
+ return tc;
+ }
+
+ public virtual TypeContainer AddPartial (TypeContainer nextPart, bool is_interface)
+ {
+ return AddPartial (nextPart, nextPart.Basename, is_interface);
+ }
- types.Add (c);
+ protected TypeContainer AddPartial (TypeContainer nextPart, string name, bool is_interface)
+ {
+ nextPart.ModFlags |= Modifiers.PARTIAL;
+ TypeContainer tc = defined_names [name] as TypeContainer;
+
+ if (tc == null)
+ return AddTypeContainer (nextPart, is_interface);
+
+ if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
+ Report.SymbolRelatedToPreviousError (tc);
+ Error_MissingPartialModifier (nextPart);
+ return tc;
+ }
+
+ if (tc.Kind != nextPart.Kind) {
+ Report.SymbolRelatedToPreviousError (tc);
+ Report.Error (261, nextPart.Location,
+ "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
+ nextPart.GetSignatureForError ());
+ return tc;
+ }
+
+ if ((tc.ModFlags & Modifiers.Accessibility) != (nextPart.ModFlags & Modifiers.Accessibility) &&
+ ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
+ (nextPart.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
+ Report.SymbolRelatedToPreviousError (tc);
+ Report.Error (262, nextPart.Location,
+ "Partial declarations of `{0}' have conflicting accessibility modifiers",
+ nextPart.GetSignatureForError ());
+ return tc;
+ }
+
+ if (tc.MemberName.IsGeneric) {
+ TypeParameter[] tc_names = tc.TypeParameters;
+ TypeParameterName[] part_names = nextPart.MemberName.TypeArguments.GetDeclarations ();
+
+ for (int i = 0; i < tc_names.Length; ++i) {
+ if (tc_names[i].Name == part_names[i].Name)
+ continue;
+
+ Report.SymbolRelatedToPreviousError (part_names[i].Location, "");
+ Report.Error (264, tc.Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
+ tc.GetSignatureForError ());
+ return tc;
+ }
+ }
+
+ if (tc.partial_parts == null)
+ tc.partial_parts = new ArrayList (1);
+
+ tc.ModFlags |= nextPart.ModFlags;
+ if (nextPart.attributes != null) {
+ if (tc.attributes == null)
+ tc.attributes = nextPart.attributes;
+ else
+ tc.attributes.AddAttributes (nextPart.attributes.Attrs);
+ }
+
+ nextPart.PartialContainer = tc;
+ tc.partial_parts.Add (nextPart);
+ return tc;
}
public void AddDelegate (Delegate d)
{
- if (!AddToTypeContainer (d))
+ if (!AddMemberType (d))
return;
if (delegates == null)
delegates = new MemberCoreArrayList ();
-
+
delegates.Add (d);
}
public void AddMethod (Method method)
{
- if (!AddToMemberContainer (method))
+ if (!AddMember (method))
return;
if (methods == null)
methods.Add (method);
}
+ //
+ // Do not use this method: use AddMethod.
+ //
+ // This is only used by iterators.
+ //
+ public void AppendMethod (Method method)
+ {
+ if (!AddMember (method))
+ return;
+
+ if (methods == null)
+ methods = new MethodArrayList (this);
+
+ methods.Add (method);
+ }
+
public void AddConstructor (Constructor c)
{
- if (c.Name != Basename) {
+ if (c.Name != MemberName.Name) {
Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
}
if (is_static){
if (default_static_constructor != null) {
Report.SymbolRelatedToPreviousError (default_static_constructor);
- Report.Error (111, c.Location, Error111, Name, c.Name);
+ Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
return;
}
default_static_constructor = c;
} else {
- if (c.IsDefault ()){
+ if (c.Parameters.Empty){
if (default_constructor != null) {
Report.SymbolRelatedToPreviousError (default_constructor);
- Report.Error (111, c.Location, Error111, c.Location, Name, c.Name);
+ Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
return;
}
default_constructor = c;
internal static string Error111 {
get {
- return "Type '{0}' already defines a member called '{1}' with the same parameter types";
+ return "`{0}' is already defined. Rename this member or use different parameter types";
}
}
-
- public void AddInterface (TypeContainer iface)
- {
- if (!AddToTypeContainer (iface))
- return;
-
- if (interfaces == null) {
- interfaces = new MemberCoreArrayList ();
- }
-
- interfaces.Add (iface);
- }
- public void AddField (FieldMember field)
+ public void AddField (FieldBase field)
{
- if (!AddToMemberContainer (field))
+ if (!AddMember (field))
return;
if (fields == null)
fields = new MemberCoreArrayList ();
-
+
fields.Add (field);
- if (field.HasInitializer){
- if ((field.ModFlags & Modifiers.STATIC) != 0){
- if (initialized_static_fields == null)
- initialized_static_fields = new ArrayList ();
-
- initialized_static_fields.Add (field);
- } else {
- if (initialized_fields == null)
- initialized_fields = new ArrayList ();
-
- initialized_fields.Add (field);
- }
+ if ((field.ModFlags & Modifiers.STATIC) != 0)
+ return;
+
+ if (first_nonstatic_field == null) {
+ first_nonstatic_field = field;
+ return;
+ }
+
+ if (Kind == Kind.Struct &&
+ first_nonstatic_field.Parent != field.Parent &&
+ RootContext.WarningLevel >= 3) {
+ Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
+ Report.Warning (282, 3, field.Location,
+ "struct instance field `{0}' found in different declaration from instance field `{1}'",
+ field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
}
-
- if ((field.ModFlags & Modifiers.STATIC) == 0)
- have_nonstatic_fields = true;
}
public void AddProperty (Property prop)
{
- if (!AddToMemberContainer (prop) ||
- !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
+ if (!AddMember (prop) ||
+ !AddMember (prop.Get) || !AddMember (prop.Set))
return;
if (properties == null)
public void AddEvent (Event e)
{
- if (!AddToMemberContainer (e))
+ if (!AddMember (e))
return;
if (e is EventProperty) {
- if (!AddToMemberContainer (e.Add))
+ if (!AddMember (e.Add))
return;
- if (!AddToMemberContainer (e.Remove))
+ if (!AddMember (e.Remove))
return;
}
events.Add (e);
}
-
/// <summary>
/// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
/// </summary>
public void AddOperator (Operator op)
{
- if (!AddToMemberContainer (op))
+ if (!AddMember (op))
return;
if (operators == null)
operators.Add (op);
}
- public void AddIterator (Iterator i)
- {
- if (iterators == null)
- iterators = new ArrayList ();
-
- iterators.Add (i);
- }
-
- public void AddType (TypeContainer tc)
+ public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
{
- types.Add (tc);
- }
+ Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
- public void AddPart (ClassPart part)
- {
- if (parts == null)
- parts = new ArrayList ();
+ if (compiler_generated == null)
+ compiler_generated = new ArrayList ();
- parts.Add (part);
+ compiler_generated.Add (c);
}
public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
{
if (a.Type == TypeManager.default_member_type) {
if (Indexers != null) {
- Report.Error (646, a.Location,
- "Cannot specify the DefaultMember attribute on" +
- " a type containing an indexer");
+ Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
return;
}
}
public override AttributeTargets AttributeTargets {
get {
- switch (Kind) {
- case Kind.Class:
- return AttributeTargets.Class;
- case Kind.Struct:
- return AttributeTargets.Struct;
- case Kind.Interface:
- return AttributeTargets.Interface;
- default:
- throw new NotSupportedException ();
- }
+ throw new NotSupportedException ();
}
}
}
}
- public ArrayList Iterators {
+ public ArrayList CompilerGenerated {
get {
- return iterators;
+ return compiler_generated;
}
}
-
- public string Base {
+
+ protected Type BaseType {
get {
- return base_class_name;
+ return TypeBuilder.BaseType;
}
}
return delegates;
}
}
-
- public ArrayList Parts {
+
+ protected override TypeAttributes TypeAttr {
get {
- return parts;
+ return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
}
}
- protected override TypeAttributes TypeAttr {
+ public string IndexerName {
get {
- return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
+ return indexers == null ? DefaultIndexerName : indexers.IndexerName;
}
}
- public string IndexerName {
+ public bool IsComImport {
get {
- return indexers == null ? DefaultIndexerName : indexers.IndexerName;
+ if (OptAttributes == null)
+ return false;
+
+ return OptAttributes.Contains (TypeManager.comimport_attr_type);
+ }
+ }
+
+ public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
+ {
+ if ((field.ModFlags & Modifiers.STATIC) != 0){
+ if (initialized_static_fields == null)
+ initialized_static_fields = new ArrayList (4);
+
+ initialized_static_fields.Add (expression);
+ } else {
+ if (initialized_fields == null)
+ initialized_fields = new ArrayList (4);
+
+ initialized_fields.Add (expression);
}
}
//
// Emits the instance field initializers
//
- public virtual bool EmitFieldInitializers (EmitContext ec)
+ public bool EmitFieldInitializers (EmitContext ec)
{
ArrayList fields;
- Expression instance_expr;
if (ec.IsStatic){
fields = initialized_static_fields;
- instance_expr = null;
} else {
fields = initialized_fields;
- instance_expr = new This (Location.Null).Resolve (ec);
}
if (fields == null)
return true;
- foreach (Field f in fields){
- Expression e = f.GetInitializerExpression (ec);
- if (e == null)
- return false;
-
- Location l = f.Location;
- FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
- fe.InstanceExpression = instance_expr;
- ExpressionStatement a = new Assign (fe, e, l);
-
- a = a.ResolveStatement (ec);
- if (a == null)
- return false;
-
- Constant c = e as Constant;
- if (c != null) {
- if (c.IsDefaultValue)
- continue;
- }
-
- a.EmitStatement (ec);
+ foreach (FieldInitializer f in fields) {
+ f.EmitStatement (ec);
}
-
return true;
}
- //
- // Defines the default constructors
- //
- protected void DefineDefaultConstructor (bool is_static)
- {
- Constructor c;
-
- // The default constructor is public
- // If the class is abstract, the default constructor is protected
- // The default static constructor is private
+ public override string DocComment {
+ get {
+ return comment;
+ }
+ set {
+ if (value == null)
+ return;
- int mods = Modifiers.PUBLIC;
- if (is_static)
- mods = Modifiers.STATIC | Modifiers.PRIVATE;
- else if ((ModFlags & Modifiers.ABSTRACT) != 0)
- mods = Modifiers.PROTECTED;
-
- TypeContainer constructor_parent = this;
- if (Parts != null)
- constructor_parent = (TypeContainer) Parts [0];
-
- c = new Constructor (constructor_parent, Basename, mods,
- Parameters.EmptyReadOnlyParameters,
- new ConstructorBaseInitializer (
- null, Parameters.EmptyReadOnlyParameters,
- Location),
- Location);
-
- AddConstructor (c);
-
- c.Block = new ToplevelBlock (null, Location);
-
+ comment += value;
+ }
}
- /// <remarks>
- /// The pending methods that need to be implemented
- // (interfaces or abstract methods)
- /// </remarks>
- public PendingImplementation Pending;
-
- public abstract PendingImplementation GetPendingImplementations ();
+ public PendingImplementation PendingImplementations {
+ get { return pending; }
+ }
- TypeExpr[] GetPartialBases (out TypeExpr base_class)
+ public override bool GetClsCompliantAttributeValue ()
{
- ArrayList ifaces = new ArrayList ();
-
- base_class = null;
- Location base_loc = Location.Null;
-
- foreach (ClassPart part in parts) {
- TypeExpr new_base_class;
- TypeExpr[] new_ifaces;
-
- new_ifaces = part.GetClassBases (out new_base_class);
- if (new_ifaces == null && base_type != null)
- return null;
-
- if ((base_class != null) && (new_base_class != null) &&
- !base_class.Equals (new_base_class)) {
- Report.Error (263, part.Location,
- "Partial declarations of `{0}' must " +
- "not specify different base classes",
- Name);
-
- if (!Location.IsNull (base_loc))
- Report.LocationOfPreviousError (base_loc);
-
- return null;
- }
-
- if ((base_class == null) && (new_base_class != null)) {
- base_class = new_base_class;
- base_loc = part.Location;
- }
-
- if (new_ifaces == null)
- continue;
-
- foreach (TypeExpr iface in new_ifaces) {
- bool found = false;
- foreach (TypeExpr old_iface in ifaces) {
- if (old_iface.Equals (iface)) {
- found = true;
- break;
- }
- }
+ if (PartialContainer != this)
+ return PartialContainer.GetClsCompliantAttributeValue ();
- if (!found)
- ifaces.Add (iface);
- }
- }
+ return base.GetClsCompliantAttributeValue ();
+ }
- TypeExpr[] retval = new TypeExpr [ifaces.Count];
- ifaces.CopyTo (retval, 0);
- return retval;
+ public void AddBasesForPart (DeclSpace part, ArrayList bases)
+ {
+ // FIXME: get rid of partial_parts and store lists of bases of each part here
+ // assumed, not verified: 'part' is in 'partial_parts'
+ ((TypeContainer) part).Bases = bases;
}
TypeExpr[] GetNormalBases (out TypeExpr base_class)
{
base_class = null;
+ if (Bases == null)
+ return null;
int count = Bases.Count;
int start = 0, i, j;
if (Kind == Kind.Class){
- TypeExpr name = ResolveBaseTypeExpr (
- (Expression) Bases [0], false, Location);
+ TypeExpr name = ((Expression) Bases [0]).ResolveAsBaseTerminal (this, false);
if (name == null){
return null;
TypeExpr [] ifaces = new TypeExpr [count-start];
for (i = start, j = 0; i < count; i++, j++){
- TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
+ TypeExpr resolved = ((Expression) Bases [i]).ResolveAsBaseTerminal (this, false);
if (resolved == null) {
return null;
}
ifaces [j] = resolved;
}
- return ifaces;
+ return ifaces.Length == 0 ? null : ifaces;
+ }
+
+
+ TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
+ {
+ ArrayList ifaces = new ArrayList (0);
+ if (iface_exprs != null)
+ ifaces.AddRange (iface_exprs);
+
+ foreach (TypeContainer part in partial_parts) {
+ TypeExpr new_base_class;
+ TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
+ if (new_base_class != TypeManager.system_object_expr) {
+ if (base_class == TypeManager.system_object_expr)
+ base_class = new_base_class;
+ else {
+ if (new_base_class != null && !new_base_class.Equals (base_class)) {
+ Report.SymbolRelatedToPreviousError (base_class.Location, "");
+ Report.Error (263, part.Location,
+ "Partial declarations of `{0}' must not specify different base classes",
+ part.GetSignatureForError ());
+
+ return null;
+ }
+ }
+ }
+
+ if (new_ifaces == null)
+ continue;
+
+ foreach (TypeExpr iface in new_ifaces) {
+ if (ifaces.Contains (iface))
+ continue;
+
+ ifaces.Add (iface);
+ }
+ }
+
+ if (ifaces.Count == 0)
+ return null;
+
+ return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
}
/// <summary>
/// The @base_class argument is set to the base object or null
/// if this is `System.Object'.
/// </summary>
- TypeExpr [] GetClassBases (out TypeExpr base_class)
+ public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
{
- int i;
-
- TypeExpr[] ifaces;
-
- if (parts != null)
- ifaces = GetPartialBases (out base_class);
- else if (Bases == null){
- base_class = null;
- return null;
- } else
- ifaces = GetNormalBases (out base_class);
-
- if (ifaces == null)
- return null;
-
- if ((base_class != null) && (Kind == Kind.Class)){
-
- if (base_class.Type.IsArray || base_class.Type.IsPointer) {
- Report.Error (1521, base_class.Location, "Invalid base type");
- return null;
- }
-
- if (base_class.IsSealed){
- Report.SymbolRelatedToPreviousError (base_class.Type);
- if (base_class.Type.IsAbstract) {
- Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
- } else {
- Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
- }
- return null;
- }
-
- if (!base_class.CanInheritFrom ()){
- Report.Error (644, Location,
- "`{0}' cannot inherit from special class `{1}'",
- Name, base_class.Name);
- return null;
- }
-
- if (!base_class.AsAccessible (this, ModFlags)) {
- Report.SymbolRelatedToPreviousError (base_class.Type);
- Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
- TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
- }
- }
-
- if (base_class != null)
- base_class_name = base_class.Name;
+ TypeExpr[] ifaces = GetNormalBases (out base_class);
if (ifaces == null)
return null;
- int count = ifaces != null ? ifaces.Length : 0;
+ int count = ifaces.Length;
- for (i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
TypeExpr iface = (TypeExpr) ifaces [i];
if (!iface.IsInterface) {
if (Kind != Kind.Class) {
// TODO: location of symbol related ....
- Error_TypeInListIsNotInterface (Location, iface.FullName);
+ Error_TypeInListIsNotInterface (Location, iface.GetSignatureForError ());
}
else if (base_class != null)
- Report.Error (1721, Location,
- "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
- Name, iface.Name);
+ Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
+ GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
else {
- Report.Error (1722, Location,
- "In Class `{0}', `{1}' is not " +
- "an interface, a base class must be listed first", Name, iface.Name);
+ Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
+ GetSignatureForError (), iface.GetSignatureForError ());
}
return null;
}
if (iface.Equals (ifaces [x])) {
Report.Error (528, Location,
"`{0}' is already listed in " +
- "interface list", iface.Name);
+ "interface list", iface.GetSignatureForError ());
return null;
}
}
return ifaces;
}
- protected void Error_TypeInListIsNotInterface (Location loc, string type)
+ bool CheckGenericInterfaces (Type[] ifaces)
{
- Report.Error (527, loc, "'{0}': type in interface list is not an interface", type);
- }
+#if GMCS_SOURCE
+ ArrayList already_checked = new ArrayList ();
- //
- // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
- //
- public override TypeBuilder DefineType ()
- {
- if (TypeBuilder != null)
- return TypeBuilder;
-
- InTransit = true;
+ for (int i = 0; i < ifaces.Length; i++) {
+ Type iface = ifaces [i];
+ foreach (Type t in already_checked) {
+ if (iface == t)
+ continue;
- TypeExpr[] iface_exprs = GetClassBases (out base_type);
- if (iface_exprs == null && base_type != null) {
- InTransit = false;
- return null;
- }
+ Type[] inferred = new Type [CountTypeParameters];
+ if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
+ continue;
- if (base_type == null) {
- if (Kind == Kind.Class){
- if (RootContext.StdLib)
- base_type = TypeManager.system_object_expr;
- else if (Name != "System.Object")
- base_type = TypeManager.system_object_expr;
- } else if (Kind == Kind.Struct) {
- //
- // If we are compiling our runtime,
- // and we are defining ValueType, then our
- // base is `System.Object'.
- //
- if (!RootContext.StdLib && Name == "System.ValueType")
- base_type = TypeManager.system_object_expr;
- else
- base_type = TypeManager.system_valuetype_expr;
+ Report.Error (695, Location,
+ "`{0}' cannot implement both `{1}' and `{2}' " +
+ "because they may unify for some type parameter substitutions",
+ TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
+ TypeManager.CSharpName (t));
+ return false;
}
+
+ already_checked.Add (iface);
}
+#endif
- if ((Kind == Kind.Struct) && TypeManager.value_type == null)
- throw new Exception ();
+ return true;
+ }
- TypeAttributes type_attributes = TypeAttr;
-
- if (base_type != null) {
- // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
- // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
- ptype = base_type.ResolveType (TypeResolveEmitContext);
- if (ptype == null) {
- InTransit = false;
- return null;
- }
- }
+ bool error = false;
+
+ protected void Error_TypeInListIsNotInterface (Location loc, string type)
+ {
+ Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
+ }
+ bool DefineTypeBuilder ()
+ {
try {
if (IsTopLevel){
if (TypeManager.NamespaceClash (Name, Location)) {
- InTransit = false;
- return null;
+ return false;
}
-
+
ModuleBuilder builder = CodeGen.Module.Builder;
+ Type default_parent = null;
+ if (Kind == Kind.Struct)
+ default_parent = TypeManager.value_type;
TypeBuilder = builder.DefineType (
- Name, type_attributes, ptype, null);
-
+ Name, TypeAttr, default_parent, null);
} else {
TypeBuilder builder = Parent.TypeBuilder;
- if (builder == null) {
- InTransit = false;
- return null;
- }
-
+
TypeBuilder = builder.DefineNestedType (
- Basename, type_attributes, ptype, null);
+ Basename, TypeAttr, null, null);
}
- }
- catch (ArgumentException) {
+ } catch (ArgumentException) {
Report.RuntimeMissingSupport (Location, "static classes");
- InTransit = false;
- return null;
+ return false;
}
- if (Parts != null) {
- ec = null;
- foreach (ClassPart part in Parts) {
- part.TypeBuilder = TypeBuilder;
- part.ptype = ptype;
- part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
- part.ec.ContainerType = TypeBuilder;
- }
+ TypeManager.AddUserType (this);
+
+#if GMCS_SOURCE
+ if (IsGeneric) {
+ string[] param_names = new string [TypeParameters.Length];
+ for (int i = 0; i < TypeParameters.Length; i++)
+ param_names [i] = TypeParameters [i].Name;
+
+ gen_params = TypeBuilder.DefineGenericParameters (param_names);
+
+ int offset = CountTypeParameters - CurrentTypeParameters.Length;
+ for (int i = offset; i < gen_params.Length; i++)
+ CurrentTypeParameters [i - offset].Define (gen_params [i]);
}
- else {
- ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
- ec.ContainerType = TypeBuilder;
+#endif
+
+ iface_exprs = GetClassBases (out base_type);
+ if (partial_parts != null) {
+ iface_exprs = GetNormalPartialBases (ref base_type);
+ }
+
+ //
+ // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
+ // which in turn should have called DefineType()s on base types if necessary.
+ //
+ // None of the code below should trigger DefineType()s on classes that we depend on.
+ // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
+ //
+ // Let's do it as soon as possible, since code below can call DefineType() on classes
+ // that depend on us to be populated before they are.
+ //
+ if (!(this is CompilerGeneratedClass))
+ RootContext.RegisterOrder (this);
+
+ if (IsGeneric && base_type != null && TypeManager.IsAttributeType (base_type.Type)) {
+ Report.Error (698, base_type.Location,
+ "A generic type cannot derive from `{0}' because it is an attribute class",
+ base_type.Name);
+ return false;
+ }
+
+ if (!CheckRecursiveDefinition (this))
+ return false;
+
+ if (base_type != null) {
+ TypeBuilder.SetParent (base_type.Type);
+
+ ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
+ if (obsolete_attr != null && !IsInObsoleteScope)
+ AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
}
// add interfaces that were not added at type creation
if (iface_exprs != null) {
- // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
- // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
- TypeResolveEmitContext.ContainerType = TypeBuilder;
- ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
- if (ifaces == null) {
- InTransit = false;
- return null;
- }
+ ifaces = TypeManager.ExpandInterfaces (iface_exprs);
+ if (ifaces == null)
+ return false;
foreach (Type itype in ifaces)
- TypeBuilder.AddInterfaceImplementation (itype);
+ TypeBuilder.AddInterfaceImplementation (itype);
+
+ foreach (TypeExpr ie in iface_exprs) {
+ ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (ie.Type);
+ if ((oa != null) && !IsInObsoleteScope)
+ AttributeTester.Report_ObsoleteMessage (
+ oa, ie.GetSignatureForError (), Location);
+ }
+
+ if (!CheckGenericInterfaces (ifaces))
+ return false;
TypeManager.RegisterBuilder (TypeBuilder, ifaces);
}
- TypeManager.AddUserType (Name, TypeBuilder, this);
+ return true;
+ }
- if (!(this is Iterator))
- RootContext.RegisterOrder (this);
+ //
+ // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
+ //
+ public override TypeBuilder DefineType ()
+ {
+ if (TypeBuilder != null)
+ return TypeBuilder;
+
+ if (error)
+ return null;
+
+ if (!DefineTypeBuilder ()) {
+ error = true;
+ return null;
+ }
+
+ if (partial_parts != null) {
+ foreach (TypeContainer part in partial_parts)
+ part.TypeBuilder = TypeBuilder;
+ }
- InTransit = false;
+ if (!(this is CompilerGeneratedClass)) {
+ if (!ResolveMembers ()) {
+ error = true;
+ return null;
+ }
+ }
if (!DefineNestedTypes ()) {
+ error = true;
return null;
}
return TypeBuilder;
}
+ public bool ResolveMembers ()
+ {
+ if (members_resolved)
+ return members_resolved_ok;
+
+ members_resolved_ok = DoResolveMembers ();
+ members_resolved = true;
+
+ return members_resolved_ok;
+ }
+
+ protected virtual bool DoResolveMembers ()
+ {
+ if (methods != null) {
+ foreach (Method method in methods) {
+ if (!method.ResolveMembers ())
+ return false;
+ }
+ }
+
+ if (instance_constructors != null) {
+ foreach (Constructor c in instance_constructors) {
+ if (!c.ResolveMembers ())
+ return false;
+ }
+ }
+
+ if (default_static_constructor != null) {
+ if (!default_static_constructor.ResolveMembers ())
+ return false;
+ }
+
+ if (operators != null) {
+ foreach (Operator o in operators) {
+ if (!o.ResolveMembers ())
+ return false;
+ }
+ }
+
+ if (properties != null) {
+ foreach (PropertyBase p in properties) {
+ if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
+ return false;
+ if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
+ return false;
+ }
+ }
+
+ if (indexers != null) {
+ foreach (PropertyBase p in indexers) {
+ if (!p.Get.IsDummy && !p.Get.ResolveMembers ())
+ return false;
+ if (!p.Set.IsDummy && !p.Set.ResolveMembers ())
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ Constraints [] constraints;
+ public override void SetParameterInfo (ArrayList constraints_list)
+ {
+ if (PartialContainer == this) {
+ base.SetParameterInfo (constraints_list);
+ return;
+ }
+
+ if (constraints_list == null)
+ return;
+
+ constraints = new Constraints [PartialContainer.CountCurrentTypeParameters];
+
+ TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
+ for (int i = 0; i < constraints.Length; i++) {
+ foreach (Constraints constraint in constraints_list) {
+ if (constraint.TypeParameter == current_params [i].Name) {
+ constraints [i] = constraint;
+ break;
+ }
+ }
+ }
+ }
+
+ bool UpdateTypeParameterConstraints ()
+ {
+ if (constraints == null)
+ return true;
+
+ TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
+ for (int i = 0; i < current_params.Length; i++) {
+ if (!current_params [i].UpdateConstraints (this, constraints [i])) {
+ Report.SymbolRelatedToPreviousError (Location, "");
+ Report.Error (265, PartialContainer.Location,
+ "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
+ PartialContainer.GetSignatureForError (), current_params [i].Name);
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public bool ResolveType ()
+ {
+ if (!DoResolveType ())
+ return false;
+
+ if (compiler_generated != null) {
+ foreach (CompilerGeneratedClass c in compiler_generated)
+ if (!c.ResolveType ())
+ return false;
+ }
+
+ return true;
+ }
+
+ protected virtual bool DoResolveType ()
+ {
+ if ((base_type != null) &&
+ (base_type.ResolveAsTypeTerminal (this, false) == null)) {
+ error = true;
+ return false;
+ }
+
+ if (!IsGeneric)
+ return true;
+
+ if (PartialContainer != this)
+ throw new InternalErrorException ();
+
+ TypeExpr current_type = null;
+
+ foreach (TypeParameter type_param in CurrentTypeParameters) {
+ if (!type_param.Resolve (this)) {
+ error = true;
+ return false;
+ }
+ }
+
+ if (partial_parts != null) {
+ foreach (TypeContainer part in partial_parts) {
+ if (!part.UpdateTypeParameterConstraints ()) {
+ error = true;
+ return false;
+ }
+ }
+ }
+
+ foreach (TypeParameter type_param in TypeParameters) {
+ if (!type_param.DefineType (this)) {
+ error = true;
+ return false;
+ }
+ }
+
+ current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
+
+ foreach (TypeParameter type_param in TypeParameters)
+ if (!type_param.CheckDependencies ()) {
+ error = true;
+ return false;
+ }
+
+ if (current_type != null) {
+ current_type = current_type.ResolveAsTypeTerminal (this, false);
+ if (current_type == null) {
+ error = true;
+ return false;
+ }
+
+ CurrentType = current_type.Type;
+ }
+
+ return true;
+ }
+
protected virtual bool DefineNestedTypes ()
{
if (Interfaces != null) {
return false;
}
+ if (compiler_generated != null) {
+ foreach (CompilerGeneratedClass c in compiler_generated) {
+ if (c.DefineType () == null)
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ TypeContainer InTransit;
+
+ protected bool CheckRecursiveDefinition (TypeContainer tc)
+ {
+ if (InTransit != null) {
+ Report.SymbolRelatedToPreviousError (this);
+ if (this is Interface)
+ Report.Error (
+ 529, tc.Location, "Inherited interface `{0}' causes a " +
+ "cycle in the interface hierarchy of `{1}'",
+ GetSignatureForError (), tc.GetSignatureForError ());
+ else
+ Report.Error (
+ 146, tc.Location, "Circular base class dependency " +
+ "involving `{0}' and `{1}'",
+ tc.GetSignatureForError (), GetSignatureForError ());
+ return false;
+ }
+
+ InTransit = tc;
+
+ if (base_type != null) {
+ Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
+ TypeContainer ptc = TypeManager.LookupTypeContainer (t);
+ if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
+ return false;
+ }
+
+ if (iface_exprs != null) {
+ foreach (TypeExpr iface in iface_exprs) {
+ Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
+ TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
+ if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
+ return false;
+ }
+ }
+
+ if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
+ return false;
+
+ InTransit = null;
return true;
}
- static void Error_KeywordNotAllowed (Location loc)
+ public static void Error_KeywordNotAllowed (Location loc)
{
- Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
+ Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
}
/// <summary>
/// Populates our TypeBuilder with fields and methods
/// </summary>
- public override bool DefineMembers (TypeContainer container)
+ public override bool DefineMembers ()
{
if (members_defined)
return members_defined_ok;
+ if (!base.DefineMembers ())
+ return false;
+
members_defined_ok = DoDefineMembers ();
members_defined = true;
return members_defined_ok;
}
- bool DoDefineMembers ()
- {
- if (IsTopLevel) {
- if ((ModFlags & Modifiers.NEW) != 0)
- Error_KeywordNotAllowed (Location);
- } else {
- MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
- if (conflict_symbol == null) {
- if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
- Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
- } else {
- if ((ModFlags & Modifiers.NEW) == 0) {
- Report.SymbolRelatedToPreviousError (conflict_symbol);
- Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
- }
- }
- }
-
- DefineContainerMembers (constants);
- DefineContainerMembers (fields);
-
- if ((Kind == Kind.Class) && !(this is ClassPart)){
- if ((instance_constructors == null) &&
- !(this is StaticClass)) {
- if (default_constructor == null)
- DefineDefaultConstructor (false);
+ protected virtual bool DoDefineMembers ()
+ {
+ if (iface_exprs != null) {
+ foreach (TypeExpr iface in iface_exprs) {
+ ConstructedType ct = iface as ConstructedType;
+ if ((ct != null) && !ct.CheckConstraints (this))
+ return false;
}
-
- if (initialized_static_fields != null &&
- default_static_constructor == null)
- DefineDefaultConstructor (true);
}
- if (Kind == Kind.Struct){
- //
- // Structs can not have initialized instance
- // fields
- //
- if (initialized_static_fields != null &&
- default_static_constructor == null)
- DefineDefaultConstructor (true);
+ if (base_type != null) {
+ ConstructedType ct = base_type as ConstructedType;
+ if ((ct != null) && !ct.CheckConstraints (this))
+ return false;
+ }
- if (initialized_fields != null)
- ReportStructInitializedInstanceError ();
+ if (!IsTopLevel) {
+ MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
+ if (conflict_symbol == null) {
+ if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
+ Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
+ } else {
+ if ((ModFlags & Modifiers.NEW) == 0) {
+ Report.SymbolRelatedToPreviousError (conflict_symbol);
+ Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
+ GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
+ }
+ }
}
- Pending = GetPendingImplementations ();
+ DefineContainerMembers (constants);
+ DefineContainerMembers (fields);
- if (parts != null) {
- foreach (ClassPart part in parts) {
- if (!part.DefineMembers (this))
- return false;
- }
+ if (Kind == Kind.Struct || Kind == Kind.Class) {
+ pending = PendingImplementation.GetPendingImplementations (this);
}
//
//
DefineContainerMembers (instance_constructors);
- if (default_static_constructor != null)
- default_static_constructor.Define ();
-
DefineContainerMembers (properties);
DefineContainerMembers (events);
DefineContainerMembers (indexers);
DefineContainerMembers (methods);
DefineContainerMembers (operators);
DefineContainerMembers (enums);
- DefineContainerMembers (delegates);
-
-#if CACHE
- if (!(this is ClassPart))
- member_cache = new MemberCache (this);
-#endif
+ DefineContainerMembers (delegates);
- if (parts != null) {
- foreach (ClassPart part in parts)
- part.member_cache = member_cache;
+ if (CurrentType != null) {
+ GenericType = CurrentType;
}
- if (iterators != null) {
- foreach (Iterator iterator in iterators) {
- if (iterator.DefineType () == null)
- return false;
- }
- foreach (Iterator iterator in iterators) {
- if (!iterator.DefineMembers (this))
- return false;
- }
+#if CACHE
+ member_cache = new MemberCache (this);
+ if (partial_parts != null) {
+ foreach (TypeContainer part in partial_parts)
+ part.member_cache = member_cache;
}
+#endif
return true;
}
- void ReportStructInitializedInstanceError ()
- {
- string n = TypeBuilder.FullName;
-
- foreach (Field f in initialized_fields){
- Report.Error (
- 573, Location,
- "`" + n + "." + f.Name + "': can not have " +
- "instance field initializers in structs");
- }
- }
-
protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
{
if (mcal != null)
public override bool Define ()
{
- if (parts != null) {
- foreach (ClassPart part in parts) {
- if (!part.Define ())
+ if (compiler_generated != null) {
+ foreach (CompilerGeneratedClass c in compiler_generated) {
+ if (!c.Define ())
return false;
}
}
public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
{
- return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
+ return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
}
/// <summary>
{
ArrayList members = new ArrayList ();
- DefineMembers (null);
+ DefineMembers ();
if (methods != null) {
int len = methods.Count;
for (int i = 0; i < len; i++) {
Operator o = (Operator) operators [i];
- members.Add (o.OperatorMethodBuilder);
+ members.Add (o.MethodBuilder);
}
}
}
// Indicated whether container has StructLayout attribute set Explicit
- public virtual bool HasExplicitLayout {
- get {
- return false;
- }
+ public bool HasExplicitLayout {
+ get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
+ set { caching_flags |= Flags.HasExplicitLayout; }
}
- public override Type FindNestedType (string name)
+ //
+ // Return the nested type with name @name. Ensures that the nested type
+ // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
+ //
+ public Type FindNestedType (string name)
{
+ if (PartialContainer != this)
+ throw new InternalErrorException ("should not happen");
+
ArrayList [] lists = { types, enums, delegates, interfaces };
for (int j = 0; j < lists.Length; ++j) {
for (int i = 0; i < len; ++i) {
DeclSpace ds = (DeclSpace) list [i];
if (ds.Basename == name) {
- ds.DefineType ();
- return ds.TypeBuilder;
+ return ds.DefineType ();
}
}
}
if (fields != null) {
int len = fields.Count;
for (int i = 0; i < len; i++) {
- FieldMember f = (FieldMember) fields [i];
+ FieldBase f = (FieldBase) fields [i];
if ((f.ModFlags & modflags) == 0)
continue;
if ((o.ModFlags & static_mask) != static_flags)
continue;
- MethodBuilder ob = o.OperatorMethodBuilder;
+ MethodBuilder ob = o.MethodBuilder;
if (ob != null && filter (ob, criteria) == true) {
if (members == null)
members = new ArrayList ();
}
}
- if (properties != null) {
+ if (events != null) {
+ foreach (Event e in events) {
+ if ((e.ModFlags & modflags) == 0)
+ continue;
+ if ((e.ModFlags & static_mask) != static_flags)
+ continue;
+
+ MethodBuilder b = e.AddBuilder;
+ if (b != null && filter (b, criteria)) {
+ if (members == null)
+ members = new ArrayList (4);
+
+ members.Add (b);
+ }
+
+ b = e.RemoveBuilder;
+ if (b != null && filter (b, criteria)) {
+ if (members == null)
+ members = new ArrayList (4);
+
+ members.Add (b);
+ }
+ }
+ }
+
+ if (properties != null) {
int len = properties.Count;
for (int i = 0; i < len; i++) {
Property p = (Property) properties [i];
members.AddRange (list);
}
}
- if (ifaces != null) {
- foreach (Type base_type in ifaces) {
- MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
-
- if (list.Count > 0) {
- if (members == null)
- members = new ArrayList ();
- members.AddRange (list);
- }
- }
- }
}
Timer.StopTimer (TimerType.TcFindMembers);
return ds.FindMembers (mt, bf, filter, criteria);
else
return new MemberList (t.FindMembers (mt, bf, filter, criteria));
-
}
- //
- // FindMethods will look for methods not only in the type `t', but in
- // any interfaces implemented by the type.
- //
- public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
- MemberFilter filter, object criteria)
- {
- return null;
- }
-
/// <summary>
/// Emits the values for the constants
/// </summary>
return;
}
- void CheckMemberUsage (MemberCoreArrayList al, string member_type)
+ static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
{
if (al == null)
return;
continue;
if (!mc.IsUsed) {
- Report.Warning (169, mc.Location, "The private {0} '{1}' is never used", member_type, mc.GetSignatureForError ());
+ Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
}
}
}
CheckMemberUsage (constants, "constant");
if (fields != null){
- foreach (FieldMember f in fields) {
+ foreach (FieldBase f in fields) {
if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
continue;
if (!f.IsUsed){
- Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
+ if ((f.caching_flags & Flags.IsAssigned) == 0)
+ Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
+ else {
+#if NET_2_0
+ const int error_code = 414;
+#else
+ const int error_code = 169;
+#endif
+ Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
+ f.GetSignatureForError ());
+ }
continue;
}
if (RootContext.WarningLevel < 4)
continue;
- if ((f.status & Field.Status.ASSIGNED) != 0)
+ if ((f.caching_flags & Flags.IsAssigned) != 0)
continue;
- Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
+ Constant c = New.Constantify (f.Type.Type);
+ Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
+ f.GetSignatureForError (), c == null ? "null" : c.AsString ());
}
}
}
}
+ // TODO: move to ClassOrStruct
+ void EmitConstructors ()
+ {
+ if (instance_constructors == null)
+ return;
+
+ if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
+ bool has_compliant_args = false;
+
+ foreach (Constructor c in instance_constructors) {
+ c.Emit ();
+
+ if (has_compliant_args)
+ continue;
+
+ has_compliant_args = c.HasCompliantArgs;
+ }
+ if (!has_compliant_args)
+ Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
+ } else {
+ foreach (Constructor c in instance_constructors)
+ c.Emit ();
+ }
+ }
+
/// <summary>
/// Emits the code, this step is performed after all
/// the types, enumerations, constructors
/// </summary>
- public void EmitType ()
+ public virtual void EmitType ()
{
if (OptAttributes != null)
- OptAttributes.Emit (ec, this);
-
+ OptAttributes.Emit ();
+
+#if GMCS_SOURCE
+ if (IsGeneric) {
+ int offset = CountTypeParameters - CurrentTypeParameters.Length;
+ for (int i = offset; i < gen_params.Length; i++)
+ CurrentTypeParameters [i - offset].EmitAttributes ();
+ }
+#endif
+
//
// Structs with no fields need to have at least one byte.
// The right thing would be to set the PackingSize in a DefineType
// be specified.
//
- if ((Kind == Kind.Struct) && !have_nonstatic_fields){
+ if (Kind == Kind.Struct && first_nonstatic_field == null){
FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
FieldAttributes.Private);
Emit ();
- if (instance_constructors != null) {
- if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
- bool has_compliant_args = false;
-
- foreach (Constructor c in instance_constructors) {
- c.Emit ();
-
- if (has_compliant_args)
- continue;
-
- has_compliant_args = c.HasCompliantArgs;
- }
- if (!has_compliant_args)
- Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
- } else {
- foreach (Constructor c in instance_constructors)
- c.Emit ();
- }
- }
+ EmitConstructors ();
+ // Can not continue if constants are broken
EmitConstants ();
+ if (Report.Errors > 0)
+ return;
if (default_static_constructor != null)
default_static_constructor.Emit ();
- if (methods != null)
+ if (methods != null){
foreach (Method m in methods)
m.Emit ();
+ }
if (operators != null)
foreach (Operator o in operators)
}
if (fields != null)
- foreach (FieldMember f in fields)
+ foreach (FieldBase f in fields)
f.Emit ();
if (events != null){
}
}
- if (parts != null) {
- foreach (ClassPart part in parts)
- part.EmitType ();
- }
-
- if ((Pending != null) && !(this is ClassPart))
- if (Pending.VerifyPendingMethods ())
+ if (pending != null)
+ if (pending.VerifyPendingMethods ())
return;
- if (iterators != null)
- foreach (Iterator iterator in iterators)
- iterator.EmitType ();
-
-// if (types != null)
-// foreach (TypeContainer tc in types)
-// tc.Emit ();
- }
+ if (Report.Errors > 0)
+ return;
+ if (compiler_generated != null) {
+ foreach (CompilerGeneratedClass c in compiler_generated) {
+ if (!c.DefineMembers ())
+ throw new InternalErrorException ();
+ }
+ foreach (CompilerGeneratedClass c in compiler_generated)
+ c.EmitType ();
+ }
+ }
+
public override void CloseType ()
{
if ((caching_flags & Flags.CloseTypeCreated) != 0)
foreach (Delegate d in Delegates)
d.CloseType ();
- if (Iterators != null)
- foreach (Iterator i in Iterators)
- i.CloseType ();
-
+ if (CompilerGenerated != null)
+ foreach (CompilerGeneratedClass c in CompilerGenerated)
+ c.CloseType ();
+
types = null;
properties = null;
enums = null;
events = null;
indexers = null;
operators = null;
- iterators = null;
- ec = null;
+ compiler_generated = null;
default_constructor = null;
default_static_constructor = null;
type_bases = null;
member_cache = null;
}
- // TODO: make it obsolete and use GetSignatureForError
- public string MakeName (string n)
- {
- return "`" + Name + "." + n + "'";
- }
-
//
// Performs the validation on a Method's modifiers (properties have
// the same properties).
//
if ((flags & Modifiers.STATIC) != 0){
if ((flags & vao) != 0){
- Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
- GetSignatureForError ());
+ Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
+ mc.GetSignatureForError ());
ok = false;
}
}
}
if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
- Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
+ Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
+ mc.GetSignatureForError ());
ok = false;
}
if ((flags & Modifiers.ABSTRACT) != 0){
if ((flags & Modifiers.EXTERN) != 0){
Report.Error (
- 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
+ 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
ok = false;
}
if ((flags & Modifiers.SEALED) != 0) {
- Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
+ Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
ok = false;
}
if ((flags & Modifiers.VIRTUAL) != 0){
- Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
+ Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
ok = false;
}
if ((ModFlags & Modifiers.ABSTRACT) == 0){
- Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
+ Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
ok = false;
}
}
if ((flags & Modifiers.PRIVATE) != 0){
if ((flags & vao) != 0){
- Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
+ Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
ok = false;
}
}
if ((flags & Modifiers.SEALED) != 0){
if ((flags & Modifiers.OVERRIDE) == 0){
- Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
+ Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
ok = false;
}
}
return ok;
}
- public bool UserDefinedStaticConstructor {
- get {
- return default_static_constructor != null;
- }
- }
-
public Constructor DefaultStaticConstructor {
get { return default_static_constructor; }
}
- protected override bool VerifyClsCompliance (DeclSpace ds)
+ protected override bool VerifyClsCompliance ()
{
- if (!base.VerifyClsCompliance (ds))
+ if (!base.VerifyClsCompliance ())
return false;
VerifyClsName ();
Type base_type = TypeBuilder.BaseType;
if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
- Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
- }
-
- if (!Parent.IsClsCompliaceRequired (ds)) {
- Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
- GetSignatureForError (), Parent.GetSignatureForError ());
+ Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
}
return true;
}
foreach (DictionaryEntry entry in defined_names) {
MemberCore mc = (MemberCore)entry.Value;
- if (!mc.IsClsCompliaceRequired (this))
+ if (!mc.IsClsComplianceRequired ())
continue;
- string name = (string)entry.Key;
+ string name = (string) entry.Key;
string basename = name.Substring (name.LastIndexOf ('.') + 1);
string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
continue;
if (found is MemberInfo) {
- if (basename == ((MemberInfo)found).Name)
+ if (basename == ((MemberInfo) found).Name)
continue;
- Report.SymbolRelatedToPreviousError ((MemberInfo)found);
+ Report.SymbolRelatedToPreviousError ((MemberInfo) found);
} else {
Report.SymbolRelatedToPreviousError ((MemberCore) found);
}
- Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
+#if GMCS_SOURCE
+ Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
+#else
+ Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
+#endif
}
}
/// checks whether the `interface_type' is a base inteface implementation.
/// Then it checks whether `name' exists in the interface type.
/// </summary>
- public virtual bool VerifyImplements (Type interface_type, string full,
- string name, Location loc)
+ public virtual bool VerifyImplements (InterfaceMemberBase mb)
{
- bool found = false;
-
- if (ifaces != null){
+ if (ifaces != null) {
foreach (Type t in ifaces){
- if (t == interface_type){
- found = true;
- break;
- }
+ if (t == mb.InterfaceType)
+ return true;
}
}
- if (!found){
- Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
- full, interface_type.FullName);
- return false;
- }
-
- return true;
+ Report.SymbolRelatedToPreviousError (mb.InterfaceType);
+ Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
+ mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
+ return false;
}
- protected override void VerifyObsoleteAttribute()
+ public void Mark_HasEquals ()
{
- CheckUsageOfObsoleteAttribute (ptype);
-
- if (ifaces == null)
- return;
-
- foreach (Type iface in ifaces) {
- CheckUsageOfObsoleteAttribute (iface);
- }
+ Methods.HasEquals = true;
}
+ public void Mark_HasGetHashCode ()
+ {
+ Methods.HasGetHashCode = true;
+ }
//
// IMemberContainer
MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
{
- return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
+ BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
+
+ if (GenericType != null)
+ return TypeManager.FindMembers (GenericType, mt, new_bf,
+ null, null);
+ else
+ return FindMembers (mt, new_bf, null, null);
}
//
}
}
- public class PartialContainer : TypeContainer {
-
- public readonly Namespace Namespace;
- public readonly int OriginalModFlags;
- public readonly int AllowedModifiers;
- public readonly TypeAttributes DefaultTypeAttributes;
+ public abstract class ClassOrStruct : TypeContainer {
+ ListDictionary declarative_security;
- static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
- MemberName member_name, int mod_flags, Kind kind,
- Location loc)
+ public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
+ MemberName name, Attributes attrs, Kind kind)
+ : base (ns, parent, name, attrs, kind)
{
- PartialContainer pc;
- DeclSpace ds = RootContext.Tree.GetDecl (member_name);
- if (ds != null) {
- pc = ds as PartialContainer;
-
- if (pc == null) {
- Report.Error (
- 260, ds.Location, "Missing partial modifier " +
- "on declaration of type `{0}'; another " +
- "partial implementation of this type exists",
- member_name.GetPartialName());
-
- Report.LocationOfPreviousError (loc);
- return null;
- }
-
- if (pc.Kind != kind) {
- Report.Error (
- 261, loc, "Partial declarations of `{0}' " +
- "must be all classes, all structs or " +
- "all interfaces", member_name.GetPartialName ());
- return null;
- }
+ }
- if (pc.OriginalModFlags != mod_flags) {
- Report.Error (
- 262, loc, "Partial declarations of `{0}' " +
- "have conflicting accessibility modifiers",
- member_name.GetPartialName ());
- return null;
+ protected override bool AddToContainer (MemberCore symbol, string name)
+ {
+ if (name == MemberName.Name) {
+ if (symbol is TypeParameter) {
+ Report.Error (694, symbol.Location,
+ "Type parameter `{0}' has same name as " +
+ "containing type, or method", name);
+ return false;
}
- return pc;
+ Report.SymbolRelatedToPreviousError (this);
+ Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
+ symbol.GetSignatureForError ());
+ return false;
}
- if (parent is ClassPart)
- parent = ((ClassPart) parent).PartialContainer;
+ return base.AddToContainer (symbol, name);
+ }
- pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind, loc);
- RootContext.Tree.RecordDecl (member_name, pc);
+ public override void VerifyMembers ()
+ {
+ base.VerifyMembers ();
- if (kind == Kind.Interface)
- parent.AddInterface (pc);
- else if (kind == Kind.Class || kind == Kind.Struct)
- parent.AddClassOrStruct (pc);
- else
- throw new InvalidOperationException ();
+ if ((events != null) && (RootContext.WarningLevel >= 3)) {
+ foreach (Event e in events){
+ if ((e.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
+ continue;
- return pc;
+ if ((e.caching_flags & Flags.IsUsed) == 0)
+ Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
+ }
+ }
}
- public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
- MemberName name, int mod, Attributes attrs,
- Kind kind, Location loc)
+ public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
{
- PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
- if (pc == null) {
- // An error occured; create a dummy container, but don't
- // register it.
- pc = new PartialContainer (ns.NS, parent, name, mod, kind, loc);
+ if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
+ if (declarative_security == null)
+ declarative_security = new ListDictionary ();
+
+ a.ExtractSecurityPermissionSet (declarative_security);
+ return;
+ }
+
+ if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
+ HasExplicitLayout = true;
}
- ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind, loc);
- pc.AddPart (part);
- return part;
+ base.ApplyAttributeBuilder (a, cb);
}
- protected PartialContainer (Namespace ns, TypeContainer parent,
- MemberName name, int mod, Kind kind, Location l)
- : base (null, parent, name, null, kind, l)
+ /// <summary>
+ /// Defines the default constructors
+ /// </summary>
+ protected void DefineDefaultConstructor (bool is_static)
{
- this.Namespace = ns;
-
- switch (kind) {
- case Kind.Class:
- AllowedModifiers = Class.AllowedModifiers;
- DefaultTypeAttributes = Class.DefaultTypeAttributes;
- break;
-
- case Kind.Struct:
- AllowedModifiers = Struct.AllowedModifiers;
- DefaultTypeAttributes = Struct.DefaultTypeAttributes;
- break;
-
- case Kind.Interface:
- AllowedModifiers = Interface.AllowedModifiers;
- DefaultTypeAttributes = Interface.DefaultTypeAttributes;
- break;
+ // The default instance constructor is public
+ // If the class is abstract, the default constructor is protected
+ // The default static constructor is private
- default:
- throw new InvalidOperationException ();
+ int mods;
+ if (is_static) {
+ mods = Modifiers.STATIC | Modifiers.PRIVATE;
+ } else {
+ mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
}
- int accmods;
- if (parent.Parent == null)
- accmods = Modifiers.INTERNAL;
- else
- accmods = Modifiers.PRIVATE;
-
- this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
- this.OriginalModFlags = mod;
+ Constructor c = new Constructor (this, MemberName.Name, mods,
+ Parameters.EmptyReadOnlyParameters,
+ new GeneratedBaseInitializer (Location),
+ Location);
+
+ AddConstructor (c);
+ c.Block = new ToplevelBlock (null, Location);
}
- public override PendingImplementation GetPendingImplementations ()
+ void DefineFieldInitializers ()
{
- return PendingImplementation.GetPendingImplementations (this);
- }
+ if (initialized_fields != null) {
+ EmitContext ec = new EmitContext (this, this, Location, null, null, ModFlags);
+ ec.IsFieldInitializer = true;
- protected override TypeAttributes TypeAttr {
- get {
- return base.TypeAttr | DefaultTypeAttributes;
+ for (int i = 0; i < initialized_fields.Count; ++i) {
+ FieldInitializer fi = (FieldInitializer)initialized_fields[i];
+ fi.ResolveStatement (ec);
+ if (fi.IsDefaultInitializer && RootContext.Optimize) {
+ // Field is re-initialized to its default value => removed
+ initialized_fields.RemoveAt (i);
+ --i;
+ }
+ }
}
- }
- }
- public class ClassPart : TypeContainer, IMemberContainer {
- public readonly PartialContainer PartialContainer;
- public readonly bool IsPartial;
+ if (initialized_static_fields != null) {
+ bool has_complex_initializer = false;
+ EmitContext ec = new EmitContext (this, this, Location, null, null, ModFlags);
+ ec.IsStatic = true;
+ ec.IsFieldInitializer = true;
- public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
- int mod, Attributes attrs, Kind kind, Location l)
- : base (ns, parent, pc.MemberName, attrs, kind, l)
- {
- this.PartialContainer = pc;
- this.IsPartial = true;
+ foreach (FieldInitializer fi in initialized_static_fields) {
+ fi.ResolveStatement (ec);
+ if (!fi.IsComplexInitializer)
+ continue;
- int accmods;
- if (parent == null || parent == RootContext.Tree.Types)
- accmods = Modifiers.INTERNAL;
- else
- accmods = Modifiers.PRIVATE;
+ has_complex_initializer = true;
+ }
- this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, l);
- }
+ // Need special check to not optimize code like this
+ // static int a = b = 5;
+ // static int b = 0;
+ if (!has_complex_initializer && RootContext.Optimize) {
+ for (int i = 0; i < initialized_static_fields.Count; ++i) {
+ FieldInitializer fi = (FieldInitializer)initialized_static_fields[i];
+ if (fi.IsDefaultInitializer) {
+ initialized_static_fields.RemoveAt (i);
+ --i;
+ }
+ }
+ }
- public override PendingImplementation GetPendingImplementations ()
- {
- return PartialContainer.Pending;
- }
+ if (default_static_constructor == null && initialized_static_fields.Count > 0) {
+ DefineDefaultConstructor (true);
+ }
+ }
- public override bool VerifyImplements (Type interface_type, string full,
- string name, Location loc)
- {
- return PartialContainer.VerifyImplements (
- interface_type, full, name, loc);
}
- public override bool EmitFieldInitializers (EmitContext ec)
+ public override bool Define ()
{
- return PartialContainer.EmitFieldInitializers (ec);
+ DefineFieldInitializers ();
+
+ if (default_static_constructor != null)
+ default_static_constructor.Define ();
+
+ return base.Define ();
}
- public override Type FindNestedType (string name)
+ public override void Emit ()
{
- return PartialContainer.FindNestedType (name);
+ base.Emit ();
+
+ if (declarative_security != null) {
+ foreach (DictionaryEntry de in declarative_security) {
+ TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
+ }
+ }
}
- public override MemberCache BaseCache {
+ protected override TypeAttributes TypeAttr {
get {
- return PartialContainer.BaseCache;
+ if (default_static_constructor == null)
+ return base.TypeAttr | TypeAttributes.BeforeFieldInit;
+
+ return base.TypeAttr;
}
}
}
- public abstract class ClassOrStruct : TypeContainer {
- bool has_explicit_layout = false;
- ListDictionary declarative_security;
- public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
- MemberName name, Attributes attrs, Kind kind,
- Location l)
- : base (ns, parent, name, attrs, kind, l)
- {
- }
+ // TODO: should be sealed
+ public class Class : ClassOrStruct {
+ const int AllowedModifiers =
+ Modifiers.NEW |
+ Modifiers.PUBLIC |
+ Modifiers.PROTECTED |
+ Modifiers.INTERNAL |
+ Modifiers.PRIVATE |
+ Modifiers.ABSTRACT |
+ Modifiers.SEALED |
+ Modifiers.STATIC |
+ Modifiers.UNSAFE;
- public override PendingImplementation GetPendingImplementations ()
+ public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
+ Attributes attrs)
+ : base (ns, parent, name, attrs, Kind.Class)
{
- return PendingImplementation.GetPendingImplementations (this);
- }
+ int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
+ this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
- public override bool HasExplicitLayout {
- get {
- return has_explicit_layout;
+ if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
+ Report.FeatureIsNotISO1 (Location, "static classes");
}
}
- public override void VerifyMembers ()
+ public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
{
- base.VerifyMembers ();
-
- if ((events != null) && (RootContext.WarningLevel >= 3)) {
- foreach (Event e in events){
- if (e.status == 0)
- Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
+ if (a.Type == TypeManager.attribute_usage_type) {
+ if (BaseType != TypeManager.attribute_type && !BaseType.IsSubclassOf (TypeManager.attribute_type) &&
+ TypeBuilder.FullName != "System.Attribute") {
+ Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
}
}
- }
-
- public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
- {
- if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
- if (declarative_security == null)
- declarative_security = new ListDictionary ();
- a.ExtractSecurityPermissionSet (declarative_security);
+ if (a.Type == TypeManager.conditional_attribute_type &&
+ !(BaseType == TypeManager.attribute_type || BaseType.IsSubclassOf (TypeManager.attribute_type))) {
+ Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
return;
}
- if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
- has_explicit_layout = true;
+ if (a.Type == TypeManager.comimport_attr_type &&
+ !attributes.Contains (TypeManager.guid_attr_type)) {
+ a.Error_MissingGuidAttribute ();
+ return;
+ }
+
+ if (AttributeTester.IsAttributeExcluded (a.Type))
+ return;
base.ApplyAttributeBuilder (a, cb);
}
- public override void Emit()
- {
- base.Emit ();
-
- if (declarative_security != null) {
- foreach (DictionaryEntry de in declarative_security) {
- TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
- }
- }
- }
- }
-
- /// <summary>
- /// Class handles static classes declaration
- /// </summary>
- public sealed class StaticClass: Class {
- public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
- Attributes attrs, Location l)
- : base (ns, parent, name, mod, attrs, l)
- {
- if (RootContext.Version == LanguageVersion.ISO_1) {
- Report.FeatureIsNotStandardized (l, "static classes");
- }
- }
-
- protected override int AllowedModifiersProp {
- get {
- return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
- Modifiers.STATIC | Modifiers.UNSAFE;
+ public override AttributeTargets AttributeTargets {
+ get {
+ return AttributeTargets.Class;
}
}
if (list == null)
return;
+ if (!IsStatic) {
+ base.DefineContainerMembers (list);
+ return;
+ }
+
foreach (MemberCore m in list) {
if (m is Operator) {
- Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
+ Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
+ continue;
+ }
+
+ if (m is Destructor) {
+ Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
continue;
}
- if ((m.ModFlags & Modifiers.PROTECTED) != 0)
- Report.Warning (628, 4, m.Location, "'{0}': new protected member declared in static class", m.GetSignatureForError (this));
+ if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
+ Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
+ continue;
+ }
if (m is Indexer) {
- Report.Error (720, m.Location, "'{0}': cannot declare indexers in a static class", m.GetSignatureForError (this));
+ Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
continue;
}
continue;
if (m is Constructor) {
- Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
- continue;
- }
-
- if (m is Destructor) {
- Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
+ Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
continue;
}
- Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
+ Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
}
base.DefineContainerMembers (list);
}
- public override TypeBuilder DefineType()
+ public override TypeBuilder DefineType ()
{
- if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
- Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
+ if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
+ Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
return null;
}
- TypeBuilder tb = base.DefineType ();
- if (tb == null)
- return null;
-
- if (ptype != TypeManager.object_type) {
- Report.Error (713, Location, "Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
+ if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
+ Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
return null;
}
- if (ifaces != null) {
- foreach (Type t in ifaces)
- Report.SymbolRelatedToPreviousError (t);
- Report.Error (714, Location, "'{0}': static classes cannot implement interfaces", GetSignatureForError ());
- }
- return tb;
- }
-
- protected override TypeAttributes TypeAttr {
- get {
- return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
- }
+ return base.DefineType ();
}
- }
-
- public class Class : ClassOrStruct {
- // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
- public const int AllowedModifiers =
- Modifiers.NEW |
- Modifiers.PUBLIC |
- Modifiers.PROTECTED |
- Modifiers.INTERNAL |
- Modifiers.PRIVATE |
- Modifiers.ABSTRACT |
- Modifiers.SEALED |
- Modifiers.UNSAFE;
- bool WasTransitError;
-
- public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
- Attributes attrs, Location l)
- : base (ns, parent, name, attrs, Kind.Class, l)
+ protected override bool DoDefineMembers ()
{
- this.ModFlags = mod;
- }
+ if (InstanceConstructors == null && !IsStatic)
+ DefineDefaultConstructor (false);
- virtual protected int AllowedModifiersProp {
- get {
- return AllowedModifiers;
- }
+ return base.DoDefineMembers ();
}
- public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
+ public override TypeExpr[] GetClassBases (out TypeExpr base_class)
{
- if (a.Type == TypeManager.attribute_usage_type) {
- if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
- TypeBuilder.FullName != "System.Attribute") {
- Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
- }
- }
-
- if (a.Type == TypeManager.conditional_attribute_type &&
- !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
- Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
- return;
- }
+ TypeExpr[] ifaces = base.GetClassBases (out base_class);
- if (AttributeTester.IsAttributeExcluded (a.Type))
- return;
+ if (base_class == null) {
+ if (RootContext.StdLib)
+ base_class = TypeManager.system_object_expr;
+ else if (Name != "System.Object")
+ base_class = TypeManager.system_object_expr;
+ } else {
+ if (Kind == Kind.Class && base_class is TypeParameterExpr){
+ Report.Error (
+ 689, base_class.Location,
+ "Cannot derive from `{0}' because it is a type parameter",
+ base_class.GetSignatureForError ());
+ return ifaces;
+ }
- base.ApplyAttributeBuilder (a, cb);
- }
+ if (base_class.Type.IsArray || base_class.Type.IsPointer) {
+ Report.Error (1521, base_class.Location, "Invalid base type");
+ return ifaces;
+ }
- public const TypeAttributes DefaultTypeAttributes =
- TypeAttributes.AutoLayout | TypeAttributes.Class;
+ if (base_class.IsSealed){
+ Report.SymbolRelatedToPreviousError (base_class.Type);
+ if (base_class.Type.IsAbstract) {
+ Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
+ GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
+ } else {
+ Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
+ GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
+ }
+ return ifaces;
+ }
- public override TypeBuilder DefineType()
- {
- if (InTransit) {
- if (WasTransitError)
- return null;
- throw new CircularDepException (this);
- }
+ if (!base_class.CanInheritFrom ()){
+ Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
+ GetSignatureForError (), base_class.GetSignatureForError ());
+ return ifaces;
+ }
- if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
- Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
- return null;
+ if (!base_class.AsAccessible (this, ModFlags)) {
+ Report.SymbolRelatedToPreviousError (base_class.Type);
+ Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
+ TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
+ }
}
- int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
- ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
+ if (IsStatic) {
+ if (base_class != TypeManager.system_object_expr) {
+ Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
+ GetSignatureForError (), base_class.GetSignatureForError ());
+ return ifaces;
+ }
- try {
- return base.DefineType ();
- }
- catch (CircularDepException e) {
- Report.SymbolRelatedToPreviousError (e.Container);
- Report.Error (146, Location, "Circular base class dependency involving '{0}' and '{1}'",
- GetSignatureForError (), e.Container.GetSignatureForError ());
- WasTransitError = true;
- return null;
+ if (ifaces != null) {
+ foreach (TypeExpr t in ifaces)
+ Report.SymbolRelatedToPreviousError (t.Type);
+ Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
+ }
}
+
+ return ifaces;
}
/// Search for at least one defined condition in ConditionalAttribute of attribute class
if (OptAttributes == null)
return false;
- Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
+ Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
if (attrs == null)
return false;
foreach (Attribute a in attrs) {
- string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
+ string condition = a.GetConditionalAttributeValue ();
if (RootContext.AllDefines.Contains (condition))
return false;
}
return true;
}
+ bool IsStatic {
+ get {
+ return (ModFlags & Modifiers.STATIC) != 0;
+ }
+ }
+
//
// FIXME: How do we deal with the user specifying a different
// layout?
//
protected override TypeAttributes TypeAttr {
get {
- return base.TypeAttr | DefaultTypeAttributes;
+ TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
+ if (IsStatic)
+ ta |= TypeAttributes.Abstract | TypeAttributes.Sealed;
+ return ta;
}
}
}
- public class Struct : ClassOrStruct {
+ public sealed class Struct : ClassOrStruct {
// <summary>
// Modifiers allowed in a struct declaration
// </summary>
- public const int AllowedModifiers =
+ const int AllowedModifiers =
Modifiers.NEW |
Modifiers.PUBLIC |
Modifiers.PROTECTED |
Modifiers.UNSAFE |
Modifiers.PRIVATE;
- public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
- int mod, Attributes attrs, Location l)
- : base (ns, parent, name, attrs, Kind.Struct, l)
+ public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
+ int mod, Attributes attrs)
+ : base (ns, parent, name, attrs, Kind.Struct)
{
int accmods;
else
accmods = Modifiers.PRIVATE;
- this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
+ this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
this.ModFlags |= Modifiers.SEALED;
}
- public const TypeAttributes DefaultTypeAttributes =
+ public override AttributeTargets AttributeTargets {
+ get {
+ return AttributeTargets.Struct;
+ }
+ }
+
+ const TypeAttributes DefaultTypeAttributes =
TypeAttributes.SequentialLayout |
TypeAttributes.Sealed |
TypeAttributes.BeforeFieldInit;
+
+ public override TypeExpr[] GetClassBases (out TypeExpr base_class)
+ {
+ TypeExpr[] ifaces = base.GetClassBases (out base_class);
+ //
+ // If we are compiling our runtime,
+ // and we are defining ValueType, then our
+ // base is `System.Object'.
+ //
+ if (base_class == null) {
+ if (!RootContext.StdLib && Name == "System.ValueType")
+ base_class = TypeManager.system_object_expr;
+ else
+ base_class = TypeManager.system_valuetype_expr;
+ }
+
+ return ifaces;
+ }
+
//
// FIXME: Allow the user to specify a different set of attributes
// in some cases (Sealed for example is mandatory for a class,
}
}
- public override TypeBuilder DefineType()
+ public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
{
- if (InTransit) {
- InTransit = false;
- throw new CircularDepException (this);
- }
-
- try {
- return base.DefineType ();
- }
- catch (CircularDepException e) {
- InTransit = false;
- Report.SymbolRelatedToPreviousError (this);
- Error_TypeInListIsNotInterface (e.Container.Location, GetSignatureForError ());
- return null;
+ if ((field.ModFlags & Modifiers.STATIC) == 0) {
+ Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
+ field.GetSignatureForError ());
+ return;
}
+ base.RegisterFieldForInitialization (field, expression);
}
+
}
/// <summary>
/// Interfaces
/// </summary>
- public class Interface : TypeContainer, IMemberContainer {
-
- bool WasTransitError;
+ public sealed class Interface : TypeContainer, IMemberContainer {
/// <summary>
/// Modifiers allowed in a class declaration
Modifiers.UNSAFE |
Modifiers.PRIVATE;
- public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
- Attributes attrs, Location l)
- : base (ns, parent, name, attrs, Kind.Interface, l)
+ public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
+ Attributes attrs)
+ : base (ns, parent, name, attrs, Kind.Interface)
{
int accmods;
else
accmods = Modifiers.PRIVATE;
- this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
+ this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
}
- public override PendingImplementation GetPendingImplementations ()
+ public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
{
- return null;
+ if (a.Type == TypeManager.comimport_attr_type &&
+ !attributes.Contains (TypeManager.guid_attr_type)) {
+ a.Error_MissingGuidAttribute ();
+ return;
+ }
+ base.ApplyAttributeBuilder (a, cb);
+ }
+
+
+ public override AttributeTargets AttributeTargets {
+ get {
+ return AttributeTargets.Interface;
+ }
}
- public const TypeAttributes DefaultTypeAttributes =
+ const TypeAttributes DefaultTypeAttributes =
TypeAttributes.AutoLayout |
TypeAttributes.Abstract |
TypeAttributes.Interface;
}
}
- public override TypeBuilder DefineType()
+ protected override bool VerifyClsCompliance ()
{
- if (InTransit) {
- if (WasTransitError)
- return null;
- throw new CircularDepException (this);
- }
+ if (!base.VerifyClsCompliance ())
+ return false;
- try {
- return base.DefineType ();
+ if (ifaces != null) {
+ foreach (Type t in ifaces) {
+ if (AttributeTester.IsClsCompliant (t))
+ continue;
+
+ Report.SymbolRelatedToPreviousError (t);
+ Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
+ GetSignatureForError (), TypeManager.CSharpName (t));
+ }
}
- catch (CircularDepException e) {
- Report.SymbolRelatedToPreviousError (e.Container);
- Report.Error (529, Location, "Inherited interface '{0}' causes a cycle in the interface hierarchy of '{1}'",
- e.Container.GetSignatureForError (), GetSignatureForError ());
- WasTransitError = true;
- return null;
+
+ return true;
+ }
+ }
+
+ // It is used as a base class for all property based members
+ // This includes properties, indexers, and events
+ public abstract class PropertyBasedMember : InterfaceMemberBase
+ {
+ public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
+ Expression type, int mod, int allowed_mod, bool is_iface,
+ MemberName name, Attributes attrs)
+ : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
+ {
+ }
+
+ protected override bool CheckForDuplications ()
+ {
+ throw new NotSupportedException ();
+ }
+
+ protected override bool VerifyClsCompliance ()
+ {
+ if (!base.VerifyClsCompliance ())
+ return false;
+
+ if (!AttributeTester.IsClsCompliant (MemberType)) {
+ Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
+ GetSignatureForError ());
}
+ return true;
}
}
- public abstract class MethodCore : MemberBase {
+
+ public abstract class MethodCore : InterfaceMemberBase
+ {
public readonly Parameters Parameters;
protected ToplevelBlock block;
-
- //
- // Parameters, cached for semantic analysis.
- //
- protected InternalParameters parameter_info;
- protected Type [] parameter_types;
- // Whether this is an operator method.
- public bool IsOperator;
-
- //
- // The method we're overriding if this is an override method.
- //
- protected MethodInfo base_method = null;
-
- static string[] attribute_targets = new string [] { "method", "return" };
-
- public MethodCore (TypeContainer parent, Expression type, int mod,
- int allowed_mod, bool is_interface, MemberName name,
- Attributes attrs, Parameters parameters, Location loc)
- : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
- attrs, loc)
+ public MethodCore (DeclSpace parent, GenericMethod generic,
+ Expression type, int mod, int allowed_mod, bool is_iface,
+ MemberName name, Attributes attrs, Parameters parameters)
+ : base (parent, generic, type, mod, allowed_mod, is_iface, name, attrs)
{
Parameters = parameters;
- IsInterface = is_interface;
}
-
+
//
// Returns the System.Type array for the parameters of this method
//
public Type [] ParameterTypes {
get {
- return parameter_types;
+ return Parameters.Types;
}
}
- public InternalParameters ParameterInfo
+ public Parameters ParameterInfo
{
get {
- return parameter_info;
+ return Parameters;
}
}
}
}
- protected override bool CheckBase ()
+ protected bool DoDefineParameters ()
{
- if (!base.CheckBase ())
+ IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
+
+ // Check if arguments were correct
+ if (!Parameters.Resolve (rc))
return false;
-
+
+ return CheckParameters (Parameters);
+ }
+
+ protected override bool CheckBase ()
+ {
// Check whether arguments were correct.
if (!DoDefineParameters ())
return false;
- if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
+ if (!base.CheckBase ())
return false;
- if (IsExplicitImpl)
- return true;
-
- // Is null for System.Object while compiling corlib and base interfaces
- if (Parent.BaseCache == null) {
- if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
- Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
- }
- return true;
- }
+ return true;
+ }
- Type base_ret_type = null;
- base_method = FindOutBaseMethod (Parent, ref base_ret_type);
+ // TODO: create a special method for operators only to make code better
+ protected bool IsDuplicateImplementation (MethodCore method)
+ {
+ if (method == this)
+ return false;
- // method is override
- if (base_method != null) {
+ Operator op2 = null;
+ Operator op1 = null;
- if (!CheckMethodAgainstBase ())
+ if (!(method.MemberName.Equals (MemberName)))
+ {
+ op1 = this as Operator;
+ if (op1 == null || !(op1.OperatorType == Operator.OpType.Explicit || op1.OperatorType == Operator.OpType.Implicit))
return false;
- if ((ModFlags & Modifiers.NEW) == 0) {
- if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
- Report.SymbolRelatedToPreviousError (base_method);
- if (this is PropertyBase) {
- Report.Error (1715, Location, "'{0}': type must be '{1}' to match overridden member '{2}'",
- GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
- }
- else {
- Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
- "change return type when overriding inherited member");
- }
- return false;
- }
- } else {
- if (base_method.IsAbstract && !IsInterface) {
- Report.SymbolRelatedToPreviousError (base_method);
- Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
- return false;
- }
- }
-
- if (base_method.IsSpecialName && !(this is PropertyBase)) {
- Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
+ op2 = method as Operator;
+ if (op2 == null || !(op2.OperatorType == Operator.OpType.Explicit || op2.OperatorType == Operator.OpType.Implicit))
return false;
- }
-
- if (RootContext.WarningLevel > 2) {
- if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
- Parent.Methods.HasEquals = true;
- else if (Name == "GetHashCode" && parameter_types.Length == 0)
- Parent.Methods.HasGetHashCode = true;
- }
+ } else {
+ op1 = this as Operator;
+ op2 = method as Operator;
+ }
- if ((ModFlags & Modifiers.OVERRIDE) != 0) {
- ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
- if (oa != null) {
- EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
- if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
- Report.SymbolRelatedToPreviousError (base_method);
- Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
- }
- }
- }
+ Type[] param_types = method.ParameterTypes;
+ // This never happen. Rewrite this as Equal
+ if (param_types == null && ParameterTypes == null)
return true;
- }
+ if (param_types == null || ParameterTypes == null)
+ return false;
- MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
- if ((ModFlags & Modifiers.OVERRIDE) != 0) {
- if (conflict_symbol != null) {
- Report.SymbolRelatedToPreviousError (conflict_symbol);
- if (this is PropertyBase)
- Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
- else
- Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
- } else
- Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
+ if (param_types.Length != ParameterTypes.Length)
return false;
- }
- if (conflict_symbol == null) {
- if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
- Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
- }
- return true;
+ if (method.Parameters.HasArglist != Parameters.HasArglist)
+ return false;
+
+ bool equal = true;
+
+ for (int i = 0; i < param_types.Length; i++) {
+ if (param_types [i] != ParameterTypes [i])
+ equal = false;
}
- if ((ModFlags & Modifiers.NEW) == 0) {
- if (this is Method && conflict_symbol is MethodBase)
- return true;
+ if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
+ equal = false;
- Report.SymbolRelatedToPreviousError (conflict_symbol);
- Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
+ // TODO: make operator compatible with MethodCore to avoid this
+ if (op1 != null && op2 != null) {
+ if (MemberType != method.MemberType)
+ equal = false;
+ }
+
+ if (equal) {
+ //
+ // Try to report 663: method only differs on out/ref
+ //
+ Parameters info = ParameterInfo;
+ Parameters other_info = method.ParameterInfo;
+ for (int i = 0; i < info.Count; i++){
+ if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
+ Report.SymbolRelatedToPreviousError (method);
+ Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
+ GetSignatureForError ());
+ return false;
+ }
+ }
+
+ Report.SymbolRelatedToPreviousError (method);
+ if (this is Operator && method is Operator)
+ Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
+ else
+ Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
+
+ return true;
+ }
+
+ return false;
+ }
+
+ //
+ // Returns a string that represents the signature for this
+ // member which should be used in XML documentation.
+ //
+ public override string GetDocCommentName (DeclSpace ds)
+ {
+ return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
+ }
+
+ //
+ // Raised (and passed an XmlElement that contains the comment)
+ // when GenerateDocComment is writing documentation expectedly.
+ //
+ // FIXME: with a few effort, it could be done with XmlReader,
+ // that means removal of DOM use.
+ //
+ internal override void OnGenerateDocComment (XmlElement el)
+ {
+ DocUtil.OnMethodGenerateDocComment (this, el);
+ }
+
+ //
+ // Represents header string for documentation comment.
+ //
+ public override string DocCommentHeader
+ {
+ get { return "M:"; }
+ }
+
+ public virtual void SetYields ()
+ {
+ ModFlags |= Modifiers.METHOD_YIELDS;
+ }
+
+ protected override bool VerifyClsCompliance ()
+ {
+ if (!base.VerifyClsCompliance ())
+ return false;
+
+ if (Parameters.HasArglist) {
+ Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
}
+ if (!AttributeTester.IsClsCompliant (MemberType)) {
+ Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
+ GetSignatureForError ());
+ }
+
+ Parameters.VerifyClsCompliance ();
return true;
}
+ }
+
+ public abstract class InterfaceMemberBase : MemberBase {
+ //
+ // Whether this is an interface member.
+ //
+ public bool IsInterface;
+
+ //
+ // If true, this is an explicit interface implementation
+ //
+ public bool IsExplicitImpl;
+
+ //
+ // The interface type we are explicitly implementing
+ //
+ public Type InterfaceType;
+
+ //
+ // The method we're overriding if this is an override method.
+ //
+ protected MethodInfo base_method;
+
+ readonly int explicit_mod_flags;
+ public MethodAttributes flags;
+
+ public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
+ Expression type, int mod, int allowed_mod, bool is_iface,
+ MemberName name, Attributes attrs)
+ : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
+ name, attrs)
+ {
+ IsInterface = is_iface;
+ IsExplicitImpl = (MemberName.Left != null);
+ explicit_mod_flags = mod;
+ }
+
+ protected override bool CheckBase ()
+ {
+ if (!base.CheckBase ())
+ return false;
+
+ if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
+ return false;
+
+ if (IsExplicitImpl)
+ return true;
+
+ // Is null for System.Object while compiling corlib and base interfaces
+ if (Parent.PartialContainer.BaseCache == null) {
+ if ((ModFlags & Modifiers.NEW) != 0) {
+ Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
+ }
+ return true;
+ }
+
+ Type base_ret_type = null;
+ base_method = FindOutBaseMethod (ref base_ret_type);
+
+ // method is override
+ if (base_method != null) {
+ if (!CheckMethodAgainstBase (base_ret_type))
+ return false;
+
+ if ((ModFlags & Modifiers.OVERRIDE) != 0) {
+ ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
+ if (oa != null) {
+ if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
+ Report.SymbolRelatedToPreviousError (base_method);
+ Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
+ GetSignatureForError (), TypeManager.CSharpSignature (base_method));
+ }
+ } else {
+ if (OptAttributes != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
+ Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
+ GetSignatureForError (), TypeManager.CSharpSignature (base_method));
+ }
+ }
+ }
+ return true;
+ }
+
+ MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
+ if ((ModFlags & Modifiers.OVERRIDE) != 0) {
+ if (conflict_symbol != null) {
+ Report.SymbolRelatedToPreviousError (conflict_symbol);
+ if (this is Event)
+ Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
+ else if (this is PropertyBase)
+ Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
+ else
+ Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
+ } else {
+ Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
+ GetSignatureForError (), SimpleName.GetMemberType (this));
+ }
+ return false;
+ }
+
+ if (conflict_symbol == null) {
+ if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
+ Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
+ }
+ return true;
+ }
+
+ if ((ModFlags & Modifiers.NEW) == 0) {
+ if (this is Method && conflict_symbol is MethodBase)
+ return true;
+
+ Report.SymbolRelatedToPreviousError (conflict_symbol);
+ Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
+ GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
+ }
+
+ return true;
+ }
//
// Performs various checks on the MethodInfo `mb' regarding the modifier flags
// `name' is the user visible name for reporting errors (this is used to
// provide the right name regarding method names and properties)
//
- bool CheckMethodAgainstBase ()
+ bool CheckMethodAgainstBase (Type baseMethodType)
{
bool ok = true;
- // TODO: replace with GetSignatureForError
- string name = base_method.DeclaringType.Name + "." + base_method.Name;
-
if ((ModFlags & Modifiers.OVERRIDE) != 0){
if (!(base_method.IsAbstract || base_method.IsVirtual)){
- Report.Error (
- 506, Location, Parent.MakeName (Name) +
- ": cannot override inherited member `" +
- name + "' because it is not " +
- "virtual, abstract or override");
+ Report.Error (506, Location,
+ "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
+ GetSignatureForError (), TypeManager.CSharpSignature (base_method));
ok = false;
}
if (base_method.IsFinal) {
Report.SymbolRelatedToPreviousError (base_method);
- Report.Error (239, Location, "'{0}': cannot override inherited member '{1}' because it is sealed",
+ Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
GetSignatureForError (), TypeManager.CSharpSignature (base_method));
ok = false;
}
MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
- Error_CannotChangeAccessModifiers (Parent, base_method, name);
+ Error_CannotChangeAccessModifiers (base_method, base_classp, null);
+ ok = false;
+ }
+
+ if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (baseMethodType))) {
+ Report.SymbolRelatedToPreviousError (base_method);
+ if (this is PropertyBasedMember) {
+ Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
+ GetSignatureForError (), TypeManager.CSharpName (baseMethodType), TypeManager.CSharpSignature (base_method));
+ }
+ else {
+ Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
+ GetSignatureForError (), TypeManager.CSharpName (baseMethodType), TypeManager.CSharpSignature (base_method));
+ }
ok = false;
}
}
- if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
- ModFlags |= Modifiers.NEW;
- Report.SymbolRelatedToPreviousError (base_method);
- if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
- if (RootContext.WarningLevel >= 2)
- Report.Warning (114, Location, "'{0}' hides inherited member '{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword", GetSignatureForError (Parent), TypeManager.CSharpSignature (base_method));
- } else
- Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
+ if ((ModFlags & Modifiers.NEW) == 0) {
+ if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
+ ModFlags |= Modifiers.NEW;
+ Report.SymbolRelatedToPreviousError (base_method);
+ if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
+ Report.Warning (114, 2, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword",
+ GetSignatureForError (), TypeManager.CSharpSignature (base_method));
+ } else {
+ Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
+ GetSignatureForError (), TypeManager.CSharpSignature (base_method));
+ }
+ }
+ } else {
+ if (base_method.IsAbstract && !IsInterface) {
+ Report.SymbolRelatedToPreviousError (base_method);
+ Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
+ GetSignatureForError (), TypeManager.CSharpSignature (base_method));
+ return ok = false;
+ }
}
return ok;
//
return false;
}
- return true;
- } else {
- return (thisp == base_classp);
+ return true;
+ } else {
+ return (thisp == base_classp);
+ }
+ }
+
+ public bool CheckAbstractAndExtern (bool has_block)
+ {
+ if (Parent.PartialContainer.Kind == Kind.Interface)
+ return true;
+
+ if (has_block) {
+ if ((ModFlags & Modifiers.EXTERN) != 0) {
+ Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
+ GetSignatureForError ());
+ return false;
+ }
+
+ if ((ModFlags & Modifiers.ABSTRACT) != 0) {
+ Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
+ GetSignatureForError ());
+ return false;
+ }
+ } else {
+ if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
+ Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
+ GetSignatureForError ());
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ protected bool CheckParameters (Parameters parameters)
+ {
+ bool error = false;
+
+ foreach (Type partype in parameters.Types){
+ if (partype.IsPointer){
+ if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
+ error = true;
+ }
+
+ if (ds.AsAccessible (partype, ModFlags))
+ continue;
+
+ Report.SymbolRelatedToPreviousError (partype);
+ if (this is Indexer)
+ Report.Error (55, Location,
+ "Inconsistent accessibility: parameter type `" +
+ TypeManager.CSharpName (partype) + "' is less " +
+ "accessible than indexer `" + GetSignatureForError () + "'");
+ else if (this is Operator)
+ Report.Error (57, Location,
+ "Inconsistent accessibility: parameter type `" +
+ TypeManager.CSharpName (partype) + "' is less " +
+ "accessible than operator `" + GetSignatureForError () + "'");
+ else
+ Report.Error (51, Location,
+ "Inconsistent accessibility: parameter type `" +
+ TypeManager.CSharpName (partype) + "' is less " +
+ "accessible than method `" + GetSignatureForError () + "'");
+ error = true;
+ }
+
+ return !error;
+ }
+
+ protected override bool DoDefine()
+ {
+ if (!base.DoDefine ())
+ return false;
+
+ if (IsExplicitImpl) {
+ Expression expr = MemberName.Left.GetTypeExpression ();
+ TypeExpr texpr = expr.ResolveAsTypeTerminal (this, false);
+ if (texpr == null)
+ return false;
+
+ InterfaceType = texpr.Type;
+
+ if (!InterfaceType.IsInterface) {
+ Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
+ return false;
+ }
+
+ if (!Parent.PartialContainer.VerifyImplements (this))
+ return false;
+
+ }
+ return true;
+ }
+
+ protected virtual bool DoDefineBase ()
+ {
+ if (Name == null)
+ throw new InternalErrorException ();
+
+ if (IsInterface) {
+ ModFlags = Modifiers.PUBLIC |
+ Modifiers.ABSTRACT |
+ Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
+
+ flags = MethodAttributes.Public |
+ MethodAttributes.Abstract |
+ MethodAttributes.HideBySig |
+ MethodAttributes.NewSlot |
+ MethodAttributes.Virtual;
+ } else {
+ if (!Parent.PartialContainer.MethodModifiersValid (this))
+ return false;
+
+ flags = Modifiers.MethodAttr (ModFlags);
+ }
+
+ if (IsExplicitImpl) {
+ Expression expr = MemberName.Left.GetTypeExpression ();
+ TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (this, false);
+ if (iface_texpr == null)
+ return false;
+
+ InterfaceType = iface_texpr.Type;
+
+ if (!InterfaceType.IsInterface) {
+ Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
+ return false;
+ }
+
+ if (!Parent.PartialContainer.VerifyImplements (this))
+ return false;
+
+ Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
+ }
+
+ return true;
+ }
+
+ protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
+ {
+ Report.SymbolRelatedToPreviousError (base_method);
+ string base_name = TypeManager.GetFullNameSignature (base_method);
+ string this_name = GetSignatureForError ();
+ if (suffix != null) {
+ base_name += suffix;
+ this_name += suffix;
+ }
+
+ Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
+ this_name, Modifiers.GetDescription (ma), base_name);
+ }
+
+ protected static string Error722 {
+ get {
+ return "`{0}': static types cannot be used as return types";
+ }
+ }
+
+ /// <summary>
+ /// For custom member duplication search in a container
+ /// </summary>
+ protected abstract bool CheckForDuplications ();
+
+ /// <summary>
+ /// Gets base method and its return type
+ /// </summary>
+ protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
+
+ //
+ // The "short" name of this property / indexer / event. This is the
+ // name without the explicit interface.
+ //
+ public string ShortName
+ {
+ get { return MemberName.Name; }
+ set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
+ }
+
+ protected override bool VerifyClsCompliance ()
+ {
+ if (!base.VerifyClsCompliance ()) {
+ if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
+ Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
+ }
+
+ if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
+ Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
+ }
+ return false;
+ }
+
+ if (GenericMethod != null)
+ GenericMethod.VerifyClsCompliance ();
+
+ return true;
+ }
+
+ public override bool IsUsed
+ {
+ get { return IsExplicitImpl || base.IsUsed; }
+ }
+
+ }
+
+ public abstract class MethodOrOperator : MethodCore, IMethodData
+ {
+ public MethodBuilder MethodBuilder;
+ ReturnParameter return_attributes;
+ ListDictionary declarative_security;
+ protected MethodData MethodData;
+
+ Iterator iterator;
+ ArrayList anonymous_methods;
+
+ static string[] attribute_targets = new string [] { "method", "return" };
+
+ protected MethodOrOperator (DeclSpace parent, GenericMethod generic, Expression type, int mod,
+ int allowed_mod, bool is_interface, MemberName name,
+ Attributes attrs, Parameters parameters)
+ : base (parent, generic, type, mod, allowed_mod, is_interface, name,
+ attrs, parameters)
+ {
+ }
+
+ public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+ {
+ if (a.Target == AttributeTargets.ReturnValue) {
+ if (return_attributes == null)
+ return_attributes = new ReturnParameter (MethodBuilder, Location);
+
+ return_attributes.ApplyAttributeBuilder (a, cb);
+ return;
+ }
+
+ if (a.Type == TypeManager.methodimpl_attr_type &&
+ (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
+ MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
+ }
+
+ if (a.Type == TypeManager.dllimport_type) {
+ const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
+ if ((ModFlags & extern_static) != extern_static) {
+ Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
+ }
+
+ return;
}
- }
-
- void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
- {
- //
- // FIXME: report the old/new permissions?
- //
- Report.Error (
- 507, Location, parent.MakeName (Name) +
- ": can't change the access modifiers when overriding inherited " +
- "member `" + name + "'");
+
+ if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
+ if (declarative_security == null)
+ declarative_security = new ListDictionary ();
+ a.ExtractSecurityPermissionSet (declarative_security);
+ return;
+ }
+
+ MethodBuilder.SetCustomAttribute (cb);
}
- protected static string Error722 {
+ public override AttributeTargets AttributeTargets {
get {
- return "'{0}': static types cannot be used as return types";
+ return AttributeTargets.Method;
}
}
- /// <summary>
- /// For custom member duplication search in a container
- /// </summary>
- protected abstract bool CheckForDuplications ();
+ public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
+ {
+ return new EmitContext (
+ this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
+ }
- /// <summary>
- /// Gets base method and its return type
- /// </summary>
- protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
+ public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
+ {
+ if (anonymous_methods == null)
+ anonymous_methods = new ArrayList ();
+ anonymous_methods.Add (anonymous);
+ }
- protected virtual bool DoDefineParameters ()
+ protected bool DefineGenericMethod ()
{
- EmitContext ec = Parent.EmitContext;
- if (ec == null)
- throw new InternalErrorException ("DoDefineParameters invoked too early");
+ if (!DoDefineBase ())
+ return false;
- bool old_unsafe = ec.InUnsafe;
- ec.InUnsafe = InUnsafe;
- // Check if arguments were correct
- parameter_types = Parameters.GetParameterInfo (ec);
- ec.InUnsafe = old_unsafe;
+#if GMCS_SOURCE
+ if (GenericMethod != null) {
+ string method_name = MemberName.Name;
- if ((parameter_types == null) ||
- !CheckParameters (Parent, parameter_types))
- return false;
+ if (IsExplicitImpl) {
+ method_name = TypeManager.CSharpName (InterfaceType) +
+ '.' + method_name;
+ }
- parameter_info = new InternalParameters (parameter_types, Parameters);
+ MethodBuilder = Parent.TypeBuilder.DefineMethod (method_name, flags);
- Parameter array_param = Parameters.ArrayParameter;
- if ((array_param != null) &&
- (!array_param.ParameterType.IsArray ||
- (array_param.ParameterType.GetArrayRank () != 1))) {
- Report.Error (225, Location, "params parameter has to be a single dimensional array");
- return false;
+ if (!GenericMethod.Define (MethodBuilder, block))
+ return false;
}
+#endif
return true;
}
- public override string[] ValidAttributeTargets {
- get {
- return attribute_targets;
- }
- }
-
- protected override bool VerifyClsCompliance (DeclSpace ds)
+ public bool ResolveMembers ()
{
- if (!base.VerifyClsCompliance (ds)) {
- if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
- Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
- }
+ if (!DefineGenericMethod ())
return false;
- }
- if (Parameters.HasArglist) {
- Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
+ if ((ModFlags & Modifiers.METHOD_YIELDS) != 0) {
+ iterator = Iterator.CreateIterator (this, Parent, GenericMethod, ModFlags);
+ if (iterator == null)
+ return false;
}
- if (!AttributeTester.IsClsCompliant (MemberType)) {
- if (this is PropertyBase)
- Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
- GetSignatureForError ());
- else
- Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
- GetSignatureForError ());
+ if (anonymous_methods != null) {
+ foreach (AnonymousMethodExpression ame in anonymous_methods) {
+ if (!ame.CreateAnonymousHelpers ())
+ return false;
+ }
}
- AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
-
return true;
}
- protected bool IsDuplicateImplementation (MethodCore method)
+ public override bool Define ()
{
- if ((method == this) || (method.Name != Name))
+ if (!DoDefine ())
return false;
- Type[] param_types = method.ParameterTypes;
- if (param_types == null)
+ if (!CheckAbstractAndExtern (block != null))
return false;
- if (param_types.Length != ParameterTypes.Length)
+ if (!CheckBase ())
return false;
- for (int i = 0; i < param_types.Length; i++)
- if (param_types [i] != ParameterTypes [i])
- return false;
+ MethodData = new MethodData (
+ this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
- // TODO: make operator compatible with MethodCore to avoid this
- if (this is Operator && method is Operator) {
- if (MemberType != method.MemberType)
- return false;
- }
+ if (!MethodData.Define (Parent.PartialContainer))
+ return false;
- //
- // Try to report 663: method only differs on out/ref
- //
- ParameterData info = ParameterInfo;
- ParameterData other_info = method.ParameterInfo;
- for (int i = 0; i < info.Count; i++){
- if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
- Report.Error (663, Location, "Overload method only differs in parameter modifier");
- return false;
- }
+ MethodBuilder = MethodData.MethodBuilder;
+
+ if (MemberType.IsAbstract && MemberType.IsSealed) {
+ Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
+ return false;
}
- Report.SymbolRelatedToPreviousError (method);
- if (this is Operator && method is Operator)
- Report.Error (557, Location, "Duplicate user-defined conversion in type '{0}'", Parent.Name);
- else
- Report.Error (111, Location, TypeContainer.Error111, Parent.Name, Name);
return true;
}
- public override bool IsUsed
+ public override void Emit ()
{
- get {
- if (IsExplicitImpl)
- return true;
+ if (OptAttributes != null)
+ OptAttributes.Emit ();
- return base.IsUsed;
+ if (declarative_security != null) {
+ foreach (DictionaryEntry de in declarative_security) {
+ MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
+ }
}
+
+ base.Emit ();
}
- //
- // Returns a string that represents the signature for this
- // member which should be used in XML documentation.
- //
- public override string GetDocCommentName (DeclSpace ds)
+ protected void Error_ConditionalAttributeIsNotValid ()
{
- return DocUtil.GetMethodDocCommentName (this, ds);
+ Report.Error (577, Location,
+ "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
+ GetSignatureForError ());
}
- //
- // Raised (and passed an XmlElement that contains the comment)
- // when GenerateDocComment is writing documentation expectedly.
- //
- // FIXME: with a few effort, it could be done with XmlReader,
- // that means removal of DOM use.
- //
- internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
+ public override bool MarkForDuplicationCheck ()
{
- DocUtil.OnMethodGenerateDocComment (this, ds, el);
+ caching_flags |= Flags.TestMethodDuplication;
+ return true;
}
- //
- // Represents header string for documentation comment.
- //
- public override string DocCommentHeader {
- get { return "M:"; }
+ public override string[] ValidAttributeTargets {
+ get {
+ return attribute_targets;
+ }
+ }
+
+ #region IMethodData Members
+
+ public CallingConventions CallingConventions {
+ get {
+ CallingConventions cc = Parameters.CallingConvention;
+ if (Parameters.HasArglist)
+ block.HasVarargs = true;
+
+ if (!IsInterface)
+ if ((ModFlags & Modifiers.STATIC) == 0)
+ cc |= CallingConventions.HasThis;
+
+ // FIXME: How is `ExplicitThis' used in C#?
+
+ return cc;
+ }
+ }
+
+ public Type ReturnType {
+ get {
+ return MemberType;
+ }
+ }
+
+ public MemberName MethodName {
+ get {
+ return MemberName;
+ }
+ }
+
+ public Iterator Iterator {
+ get { return iterator; }
+ }
+
+ public new Location Location {
+ get {
+ return base.Location;
+ }
}
- protected override void VerifyObsoleteAttribute()
+ protected override bool CheckBase ()
{
- base.VerifyObsoleteAttribute ();
+ if (!base.CheckBase ())
+ return false;
- if (parameter_types == null)
- return;
+ // TODO: Destructor should derive from MethodCore
+ if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
+ base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
+ Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
+ return false;
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
+ /// </summary>
+ public bool IsExcluded () {
+ if ((caching_flags & Flags.Excluded_Undetected) == 0)
+ return (caching_flags & Flags.Excluded) != 0;
+
+ caching_flags &= ~Flags.Excluded_Undetected;
+
+ if (base_method == null) {
+ if (OptAttributes == null)
+ return false;
+
+ Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
+
+ if (attrs == null)
+ return false;
+
+ foreach (Attribute a in attrs) {
+ string condition = a.GetConditionalAttributeValue ();
+ if (condition == null)
+ return false;
+
+ if (RootContext.AllDefines.Contains (condition))
+ return false;
+ }
+
+ caching_flags |= Flags.Excluded;
+ return true;
+ }
+
+ IMethodData md = TypeManager.GetMethod (base_method);
+ if (md == null) {
+ if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
+ caching_flags |= Flags.Excluded;
+ return true;
+ }
+ return false;
+ }
+
+ if (md.IsExcluded ()) {
+ caching_flags |= Flags.Excluded;
+ return true;
+ }
+ return false;
+ }
- foreach (Type type in parameter_types) {
- CheckUsageOfObsoleteAttribute (type);
+ GenericMethod IMethodData.GenericMethod {
+ get {
+ return GenericMethod;
}
}
+
+ #endregion
+
}
public class SourceMethod : ISourceMethod
{
- TypeContainer container;
+ DeclSpace parent;
MethodBase builder;
- protected SourceMethod (TypeContainer container, MethodBase builder,
+ protected SourceMethod (DeclSpace parent, MethodBase builder,
ISourceFile file, Location start, Location end)
{
- this.container = container;
+ this.parent = parent;
this.builder = builder;
- CodeGen.SymbolWriter.OpenMethod (
- file, this, start.Row, 0, end.Row, 0);
+ CodeGen.SymbolWriter.OpenMethod (file, this, start.Row, start.Column, end.Row, start.Column);
}
public string Name {
}
public int NamespaceID {
- get { return container.NamespaceEntry.SymbolFileID; }
+ get { return parent.NamespaceEntry.SymbolFileID; }
}
public int Token {
CodeGen.SymbolWriter.CloseMethod ();
}
- public static SourceMethod Create (TypeContainer parent,
- MethodBase builder, Block block)
+ public static SourceMethod Create (DeclSpace parent, MethodBase builder, Block block)
{
if (CodeGen.SymbolWriter == null)
return null;
return null;
Location start_loc = block.StartLocation;
- if (Location.IsNull (start_loc))
+ if (start_loc.IsNull)
return null;
Location end_loc = block.EndLocation;
- if (Location.IsNull (end_loc))
+ if (end_loc.IsNull)
return null;
ISourceFile file = start_loc.SourceFile;
}
}
- public class Method : MethodCore, IIteratorContainer, IMethodData {
- public MethodBuilder MethodBuilder;
- public MethodData MethodData;
- ReturnParameter return_attributes;
- ListDictionary declarative_security;
+ public class Method : MethodOrOperator, IAnonymousHost {
/// <summary>
/// Modifiers allowed in a class declaration
//
// return_type can be "null" for VOID values.
//
- public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
- MemberName name, Parameters parameters, Attributes attrs,
- Location l)
- : base (ds, return_type, mod,
+ public Method (DeclSpace parent, GenericMethod generic,
+ Expression return_type, int mod, bool is_iface,
+ MemberName name, Parameters parameters, Attributes attrs)
+ : base (parent, generic, return_type, mod,
is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
- is_iface, name, attrs, parameters, l)
+ is_iface, name, attrs, parameters)
{
}
-
- public override AttributeTargets AttributeTargets {
- get {
- return AttributeTargets.Method;
- }
- }
public override string GetSignatureForError()
{
- if (MethodBuilder == null) {
- return GetSignatureForError (Parent);
- }
- return TypeManager.CSharpSignature (MethodBuilder);
+ return base.GetSignatureForError () + Parameters.GetSignatureForError ();
}
- /// <summary>
- /// Use this method when MethodBuilder is null
- /// </summary>
- public override string GetSignatureForError (TypeContainer tc)
+ void Error_DuplicateEntryPoint (MethodInfo b, Location location)
{
- // TODO: get params from somewhere
- if (parameter_info == null)
- return base.GetSignatureForError (tc);
-
- // TODO: move to parameters
- System.Text.StringBuilder args = new System.Text.StringBuilder ();
- if (parameter_info.Parameters.FixedParameters != null) {
- for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
- Parameter p = parameter_info.Parameters.FixedParameters [i];
- args.Append (p.GetSignatureForError ());
-
- if (i < parameter_info.Parameters.FixedParameters.Length - 1)
- args.Append (',');
- }
- }
-
- return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
+ Report.Error (17, location,
+ "Program `{0}' has more than one entry point defined: `{1}'",
+ CodeGen.FileName, TypeManager.CSharpSignature(b));
}
- void DuplicateEntryPoint (MethodInfo b, Location location)
- {
- Report.Error (
- 17, location,
- "Program `" + CodeGen.FileName +
- "' has more than one entry point defined: `" +
- TypeManager.CSharpSignature(b) + "'");
- }
-
- public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
- {
- if (b.ReturnType != TypeManager.void_type &&
- b.ReturnType != TypeManager.int32_type)
- return false;
-
- if (pinfo.Count == 0)
- return true;
-
- if (pinfo.Count > 1)
- return false;
-
- Type t = pinfo.ParameterType(0);
- if (t.IsArray &&
- (t.GetArrayRank() == 1) &&
- (TypeManager.GetElementType(t) == TypeManager.string_type) &&
- (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
- return true;
- else
- return false;
- }
-
- public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
- {
- if (a.Target == AttributeTargets.ReturnValue) {
- if (return_attributes == null)
- return_attributes = new ReturnParameter (MethodBuilder, Location);
-
- return_attributes.ApplyAttributeBuilder (a, cb);
- return;
- }
-
- if (a.Type == TypeManager.methodimpl_attr_type &&
- (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
- MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
- }
-
- if (a.Type == TypeManager.dllimport_type) {
- const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
- if ((ModFlags & extern_static) != extern_static) {
- Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
- }
+ bool IsEntryPoint (Parameters pinfo)
+ {
+ if (ReturnType != TypeManager.void_type &&
+ ReturnType != TypeManager.int32_type)
+ return false;
- return;
- }
+ if (pinfo.Count == 0)
+ return true;
- if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
- if (declarative_security == null)
- declarative_security = new ListDictionary ();
- a.ExtractSecurityPermissionSet (declarative_security);
- return;
- }
+ if (pinfo.Count > 1)
+ return false;
+
+ Type t = pinfo.ParameterType (0);
+ if (t.IsArray &&
+ (t.GetArrayRank () == 1) &&
+ (TypeManager.GetElementType (t) == TypeManager.string_type) &&
+ (pinfo.ParameterModifier (0) == Parameter.Modifier.NONE))
+ return true;
+ else
+ return false;
+ }
+ public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+ {
if (a.Type == TypeManager.conditional_attribute_type) {
- if (IsOperator || IsExplicitImpl) {
- Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
+ if (IsExplicitImpl) {
+ Error_ConditionalAttributeIsNotValid ();
return;
}
if (ReturnType != TypeManager.void_type) {
- Report.Error (578, Location, "Conditional not valid on '{0}' because its return type is not void", GetSignatureForError ());
+ Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
return;
}
if ((ModFlags & Modifiers.OVERRIDE) != 0) {
- Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
+ Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
return;
}
return;
}
- if (MethodData.IsImplementing) {
- Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
+ if (MethodData.implementing != null) {
+ Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
+ GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
return;
}
- for (int i = 0; i < parameter_info.Count; ++i) {
- if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
- Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
+ for (int i = 0; i < ParameterInfo.Count; ++i) {
+ if ((ParameterInfo.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
+ Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
return;
}
}
}
- MethodBuilder.SetCustomAttribute (cb);
+ base.ApplyAttributeBuilder (a, cb);
}
protected override bool CheckForDuplications ()
{
- ArrayList ar = Parent.Methods;
+ ArrayList ar = Parent.PartialContainer.Methods;
if (ar != null) {
int arLen = ar.Count;
}
}
- ar = Parent.Properties;
+ ar = Parent.PartialContainer.Properties;
if (ar != null) {
for (int i = 0; i < ar.Count; ++i) {
PropertyBase pb = (PropertyBase) ar [i];
}
}
- ar = Parent.Indexers;
+ ar = Parent.PartialContainer.Indexers;
if (ar != null) {
for (int i = 0; i < ar.Count; ++i) {
PropertyBase pb = (PropertyBase) ar [i];
}
}
- ar = Parent.Events;
+ ar = Parent.PartialContainer.Events;
if (ar != null) {
for (int i = 0; i < ar.Count; ++i) {
Event ev = (Event) ar [i];
//
public override bool Define ()
{
- if (!DoDefine ())
+ if (!base.Define ())
return false;
if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
return false;
}
- if (!CheckBase ())
- return false;
-
- if (IsOperator)
- flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
-
- MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
-
- if (!MethodData.Define (Parent))
- return false;
-
- //
- // Setup iterator if we are one
- //
- if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
- Iterator iterator = new Iterator (
- Parent, Name, MemberType,
- ParameterInfo, ModFlags, block, Location);
-
- if (!iterator.DefineIterator ())
- return false;
+ if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
+ Name == "Finalize" && !(this is Destructor)) {
+ Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
+ }
- block = iterator.Block;
+ if (base_method != null) {
+ if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
+ Parent.PartialContainer.Mark_HasEquals ();
+ else if (Parameters.Empty && Name == "GetHashCode")
+ Parent.PartialContainer.Mark_HasGetHashCode ();
}
- MethodBuilder = MethodData.MethodBuilder;
-
//
// This is used to track the Entry Point,
//
- if (Name == "Main" &&
- ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
- (RootContext.MainClass == null ||
- RootContext.MainClass == Parent.TypeBuilder.FullName)){
- if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
- IMethodData md = TypeManager.GetMethod (MethodBuilder);
- md.SetMemberIsUsed ();
-
- if (RootContext.EntryPoint == null) {
- RootContext.EntryPoint = MethodBuilder;
- RootContext.EntryPointLocation = Location;
- } else {
- DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
- DuplicateEntryPoint (MethodBuilder, Location);
- }
- } else {
- if (RootContext.WarningLevel >= 4)
- Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
- }
- }
+ if (RootContext.NeedsEntryPoint && ((ModFlags & Modifiers.STATIC) != 0) &&
+ Name == "Main" &&
+ (RootContext.MainClass == null ||
+ RootContext.MainClass == Parent.TypeBuilder.FullName)){
+ if (IsEntryPoint (ParameterInfo)) {
+
+ if (RootContext.EntryPoint == null) {
+ if (Parent.IsGeneric || MemberName.IsGeneric) {
+ Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
+ GetSignatureForError ());
+ } else {
+ IMethodData md = TypeManager.GetMethod (MethodBuilder);
+ md.SetMemberIsUsed ();
- if (MemberType.IsAbstract && MemberType.IsSealed) {
- Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
- return false;
+ RootContext.EntryPoint = MethodBuilder;
+ RootContext.EntryPointLocation = Location;
+ }
+ } else {
+ Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
+ Error_DuplicateEntryPoint (MethodBuilder, Location);
+ }
+ } else {
+ Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
+ GetSignatureForError ());
+ }
}
return true;
//
public override void Emit ()
{
- MethodData.Emit (Parent, this);
+ Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
+ MethodData.Emit (Parent);
base.Emit ();
- if (declarative_security != null) {
- foreach (DictionaryEntry de in declarative_security) {
- MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
- }
- }
-
Block = null;
MethodData = null;
}
public static void Error1599 (Location loc, Type t)
{
- Report.Error (1599, loc, "Method or delegate cannot return type '{0}'", TypeManager.CSharpName (t));
+ Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
}
- protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
+ protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
{
- MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
- container.TypeBuilder, Name, ParameterTypes, false);
+ MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
+ Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
if (mi == null)
return null;
+ if (mi.IsSpecialName)
+ return null;
+
base_ret_type = mi.ReturnType;
return mi;
}
- public override bool MarkForDuplicationCheck ()
- {
- caching_flags |= Flags.TestMethodDuplication;
- return true;
- }
-
- protected override bool VerifyClsCompliance(DeclSpace ds)
+ protected override bool VerifyClsCompliance ()
{
- if (!base.VerifyClsCompliance (ds))
+ if (!base.VerifyClsCompliance ())
return false;
- if (parameter_types.Length > 0) {
- ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
+ if (ParameterInfo.Count > 0) {
+ ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
if (al.Count > 1)
- ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
- }
-
- return true;
- }
-
-
- void IIteratorContainer.SetYields ()
- {
- ModFlags |= Modifiers.METHOD_YIELDS;
- }
-
- #region IMethodData Members
-
- public CallingConventions CallingConventions {
- get {
- CallingConventions cc = Parameters.GetCallingConvention ();
- if (Parameters.HasArglist)
- block.HasVarargs = true;
-
- if (!IsInterface)
- if ((ModFlags & Modifiers.STATIC) == 0)
- cc |= CallingConventions.HasThis;
-
- // FIXME: How is `ExplicitThis' used in C#?
-
- return cc;
- }
- }
-
- public Type ReturnType {
- get {
- return MemberType;
- }
- }
-
- public MemberName MethodName {
- get {
- return MemberName;
- }
- }
-
- public new Location Location {
- get {
- return base.Location;
- }
- }
-
- protected override bool CheckBase() {
- if (!base.CheckBase ())
- return false;
-
- // TODO: Destructor should derive from MethodCore
- if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
- base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
- Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
- return false;
+ MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
}
return true;
}
-
- public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
- {
- return new EmitContext (
- tc, Parent, Location, ig, ReturnType, ModFlags, false);
- }
-
- public ObsoleteAttribute GetObsoleteAttribute ()
- {
- return GetObsoleteAttribute (Parent);
- }
-
- /// <summary>
- /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
- /// </summary>
- public bool IsExcluded (EmitContext ec)
- {
- if ((caching_flags & Flags.Excluded_Undetected) == 0)
- return (caching_flags & Flags.Excluded) != 0;
-
- caching_flags &= ~Flags.Excluded_Undetected;
-
- if (base_method == null) {
- if (OptAttributes == null)
- return false;
-
- Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
-
- if (attrs == null)
- return false;
-
- foreach (Attribute a in attrs) {
- string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
- if (RootContext.AllDefines.Contains (condition))
- return false;
- }
-
- caching_flags |= Flags.Excluded;
- return true;
- }
-
- IMethodData md = TypeManager.GetMethod (base_method);
- if (md == null) {
- if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
- caching_flags |= Flags.Excluded;
- return true;
- }
- return false;
- }
-
- if (md.IsExcluded (ec)) {
- caching_flags |= Flags.Excluded;
- return true;
- }
- return false;
- }
-
- #endregion
}
public abstract class ConstructorInitializer {
ArrayList argument_list;
protected ConstructorInfo base_constructor;
- Parameters parameters;
Location loc;
- public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
- Location loc)
+ public ConstructorInitializer (ArrayList argument_list, Location loc)
{
this.argument_list = argument_list;
- this.parameters = parameters;
this.loc = loc;
}
}
}
- public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
+ public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
{
Expression base_constructor_group;
Type t;
bool error = false;
- ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
+ ec.CurrentBlock = block;
if (argument_list != null){
foreach (Argument a in argument_list){
t = ec.ContainerType.BaseType;
if (ec.ContainerType.IsValueType) {
Report.Error (522, loc,
- "structs cannot call base class constructors");
+ "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
return false;
}
- } else
+ } else {
+ //
+ // It is legal to have "this" initializers that take no arguments
+ // in structs, they are just no-ops.
+ //
+ // struct D { public D (int a) : this () {}
+ //
+ if (ec.ContainerType.IsValueType && argument_list == null)
+ return true;
+
t = ec.ContainerType;
+ }
base_constructor_group = Expression.MemberLookup (
- ec, t, ".ctor", MemberTypes.Constructor,
+ ec.ContainerType, t, ".ctor", MemberTypes.Constructor,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
loc);
if (base_constructor_group == null){
error = true;
base_constructor_group = Expression.MemberLookup (
- ec, t, null, t, ".ctor", MemberTypes.Constructor,
+ t, null, t, ".ctor", MemberTypes.Constructor,
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
loc);
}
if (base_constructor == null) {
if (errors == Report.Errors)
- Report.Error (1501, loc, "Can not find a constructor for this argument list");
+ Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
+ argument_list == null ? 0 : argument_list.Count);
return false;
}
if (error) {
- Report.Error (122, loc, "`{0}' is inaccessible due to its protection level",
- TypeManager.CSharpSignature (base_constructor));
+ Report.SymbolRelatedToPreviousError (base_constructor);
+ Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
base_constructor = null;
return false;
}
-
+
if (base_constructor == caller_builder){
- Report.Error (516, loc, "Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder));
+ Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
return false;
}
return true;
}
- public void Emit (EmitContext ec)
+ public virtual void Emit (EmitContext ec)
{
if (base_constructor != null){
ec.Mark (loc, false);
Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
}
}
-
- /// <summary>
- /// Method search for base ctor. (We do not cache it).
- /// </summary>
- Constructor GetOverloadedConstructor (TypeContainer tc)
- {
- if (tc.InstanceConstructors == null)
- return null;
-
- foreach (Constructor c in tc.InstanceConstructors) {
- if (Arguments == null) {
- if (c.ParameterTypes.Length == 0)
- return c;
-
- continue;
- }
-
- bool ok = true;
-
- int count = c.ParameterInfo.Count;
- if ((count > 0) &&
- c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
- for (int i = 0; i < count-1; i++)
- if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
- ok = false;
- break;
- }
- } else {
- if (c.ParameterTypes.Length != Arguments.Count)
- continue;
-
- for (int i = 0; i < Arguments.Count; ++i)
- if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
- ok = false;
- break;
- }
- }
-
- if (!ok)
- continue;
-
- return c;
- }
-
- return null;
- }
-
- //TODO: implement caching when it will be necessary
- public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
- {
- Constructor ctor = GetOverloadedConstructor (tc);
- if (ctor == null)
- return;
-
- ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
- if (oa == null)
- return;
-
- AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
- }
}
public class ConstructorBaseInitializer : ConstructorInitializer {
- public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
- base (argument_list, pars, l)
+ public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
+ base (argument_list, l)
{
}
+ }
- public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
- if (base_constructor == null)
- return;
-
- TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
- if (type_ds == null) {
- ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (base_constructor);
-
- if (oa != null)
- AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (base_constructor), loc);
-
- return;
- }
-
- base.CheckObsoleteAttribute (type_ds, loc);
+ class GeneratedBaseInitializer: ConstructorBaseInitializer {
+ public GeneratedBaseInitializer (Location loc):
+ base (null, loc)
+ {
}
-
}
public class ConstructorThisInitializer : ConstructorInitializer {
- public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
- base (argument_list, pars, l)
+ public ConstructorThisInitializer (ArrayList argument_list, Location l) :
+ base (argument_list, l)
{
}
}
- public class Constructor : MethodCore, IMethodData {
+ public class Constructor : MethodCore, IMethodData, IAnonymousHost {
public ConstructorBuilder ConstructorBuilder;
public ConstructorInitializer Initializer;
ListDictionary declarative_security;
+ ArrayList anonymous_methods;
// <summary>
// Modifiers allowed for a constructor.
Modifiers.EXTERN |
Modifiers.PRIVATE;
+ static string[] attribute_targets = new string [] { "method" };
+
+ public Iterator Iterator {
+ get { return null; }
+ }
+
bool has_compliant_args = false;
//
// The spec claims that static is not permitted, but
// my very own code has static constructors.
//
- public Constructor (TypeContainer ds, string name, int mod, Parameters args,
- ConstructorInitializer init, Location l)
- : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
- null, args, l)
+ public Constructor (DeclSpace parent, string name, int mod, Parameters args,
+ ConstructorInitializer init, Location loc)
+ : base (parent, null, null, mod, AllowedModifiers, false,
+ new MemberName (name, loc), null, args)
{
Initializer = init;
}
- public override string GetSignatureForError()
- {
- if (ConstructorBuilder == null)
- return GetSignatureForError (Parent);
-
- return TypeManager.CSharpSignature (ConstructorBuilder);
- }
-
public bool HasCompliantArgs {
- get {
- return has_compliant_args;
- }
+ get { return has_compliant_args; }
}
public override AttributeTargets AttributeTargets {
- get {
- return AttributeTargets.Constructor;
- }
+ get { return AttributeTargets.Constructor; }
}
public bool IsDefault ()
{
if ((ModFlags & Modifiers.STATIC) != 0)
- return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
- (Parameters.ArrayParameter == null ? true : Parameters.Empty);
+ return Parameters.Empty;
- else
- return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
- (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
+ return Parameters.Empty &&
(Initializer is ConstructorBaseInitializer) &&
(Initializer.Arguments == null);
}
- public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+ public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+ {
+ if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
+ if (declarative_security == null) {
+ declarative_security = new ListDictionary ();
+ }
+ a.ExtractSecurityPermissionSet (declarative_security);
+ return;
+ }
+
+ if (a.Type == TypeManager.methodimpl_attr_type &&
+ (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
+ ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
+ }
+
+ ConstructorBuilder.SetCustomAttribute (cb);
+ }
+
+ public void AddAnonymousMethod (AnonymousMethodExpression anonymous)
+ {
+ if (anonymous_methods == null)
+ anonymous_methods = new ArrayList ();
+ anonymous_methods.Add (anonymous);
+ }
+
+ public bool ResolveMembers ()
{
- if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
- if (declarative_security == null) {
- declarative_security = new ListDictionary ();
+ if (anonymous_methods != null) {
+ foreach (AnonymousMethodExpression ame in anonymous_methods) {
+ if (!ame.CreateAnonymousHelpers ())
+ return false;
}
- a.ExtractSecurityPermissionSet (declarative_security);
- return;
}
- ConstructorBuilder.SetCustomAttribute (cb);
+ return true;
}
-
+
protected override bool CheckForDuplications ()
- {
- ArrayList ar = Parent.InstanceConstructors;
+ {
+ ArrayList ar = Parent.PartialContainer.InstanceConstructors;
if (ar != null) {
int arLen = ar.Count;
protected override bool CheckBase ()
{
+ if ((ModFlags & Modifiers.STATIC) != 0) {
+ if (!Parameters.Empty) {
+ Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
+ GetSignatureForError ());
+ return false;
+ }
+
+ // the rest can be ignored
+ return true;
+ }
+
// Check whether arguments were correct.
if (!DoDefineParameters ())
return false;
- // TODO: skip the rest for generated ctor
- if ((ModFlags & Modifiers.STATIC) != 0)
- return true;
-
if (!CheckForDuplications ())
return false;
- if (Parent.Kind == Kind.Struct) {
+ if (Parent.PartialContainer.Kind == Kind.Struct) {
if (ParameterTypes.Length == 0) {
Report.Error (568, Location,
- "Structs can not contain explicit parameterless " +
- "constructors");
+ "Structs cannot contain explicit parameterless constructors");
return false;
}
if ((ModFlags & Modifiers.PROTECTED) != 0) {
- Report.Error (666, Location, "Protected member in struct declaration");
+ Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
return false;
}
}
if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
- Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
+ Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
}
return true;
//
public override bool Define ()
{
+ if (ConstructorBuilder != null)
+ return true;
+
MethodAttributes ca = (MethodAttributes.RTSpecialName |
MethodAttributes.SpecialName);
ca |= MethodAttributes.Family;
} else if ((ModFlags & Modifiers.INTERNAL) != 0)
ca |= MethodAttributes.Assembly;
- else if (IsDefault ())
- ca |= MethodAttributes.Public;
else
ca |= MethodAttributes.Private;
}
+
+ if (!CheckAbstractAndExtern (block != null))
+ return false;
// Check if arguments were correct.
if (!CheckBase ())
if ((ModFlags & Modifiers.UNSAFE) != 0)
ConstructorBuilder.InitLocals = false;
+
+ if (Parent.PartialContainer.IsComImport) {
+ if (!IsDefault ()) {
+ Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
+ Parent.GetSignatureForError ());
+ return false;
+ }
+ ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
+ }
TypeManager.AddMethod (ConstructorBuilder, this);
- //
- // HACK because System.Reflection.Emit is lame
- //
- TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
-
return true;
}
//
public override void Emit ()
{
+ if (OptAttributes != null)
+ OptAttributes.Emit ();
+
EmitContext ec = CreateEmitContext (null, null);
- //
- // extern methods have no bodies
- //
- if ((ModFlags & Modifiers.EXTERN) != 0) {
- if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
- Report.Error (
- 179, Location, "External constructor `" +
- TypeManager.CSharpSignature (ConstructorBuilder) +
- "' can not have a body");
- return;
- }
- } else if (block == null) {
- Report.Error (
- 501, Location, "Constructor `" +
- TypeManager.CSharpSignature (ConstructorBuilder) +
- "' must declare a body since it is not marked extern");
- return;
+ if (block != null) {
+ // If this is a non-static `struct' constructor and doesn't have any
+ // initializer, it must initialize all of the struct's fields.
+ if ((Parent.PartialContainer.Kind == Kind.Struct) &&
+ ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
+ block.AddThisVariable (Parent, Location);
+
+ if (!block.ResolveMeta (ec, ParameterInfo))
+ block = null;
}
if ((ModFlags & Modifiers.STATIC) == 0){
- if (Parent.Kind == Kind.Class && Initializer == null)
- Initializer = new ConstructorBaseInitializer (
- null, Parameters.EmptyReadOnlyParameters, Location);
+ if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
+ Initializer = new GeneratedBaseInitializer (Location);
//
// `this' access
//
ec.IsStatic = true;
- if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
+ if ((Initializer != null) &&
+ !Initializer.Resolve (ConstructorBuilder, block, ec))
return;
ec.IsStatic = false;
}
- Parameters.LabelParameters (ec, ConstructorBuilder, Location);
+ Parameters.ApplyAttributes (ConstructorBuilder);
SourceMethod source = SourceMethod.Create (
Parent, ConstructorBuilder, block);
//
// Classes can have base initializers and instance field initializers.
//
- if (Parent.Kind == Kind.Class){
+ if (Parent.PartialContainer.Kind == Kind.Class){
if ((ModFlags & Modifiers.STATIC) == 0){
//
// do not emit field initializers, they are initialized in the other constructor
//
if (!(Initializer != null && Initializer is ConstructorThisInitializer))
- Parent.EmitFieldInitializers (ec);
+ Parent.PartialContainer.EmitFieldInitializers (ec);
+ }
+ }
+
+ bool unreachable = false;
+ if (block != null) {
+ ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable);
+ ec.EmitMeta (block);
+
+ if (block.ScopeInfo != null) {
+ ExpressionStatement init = block.ScopeInfo.GetScopeInitializer (ec);
+ init.EmitStatement (ec);
}
}
+
if (Initializer != null) {
- if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent) == null)
- Initializer.CheckObsoleteAttribute (Parent, Location);
- else
- ec.TestObsoleteMethodUsage = false;
Initializer.Emit (ec);
}
if ((ModFlags & Modifiers.STATIC) != 0)
- Parent.EmitFieldInitializers (ec);
-
- if (OptAttributes != null)
- OptAttributes.Emit (ec, this);
+ Parent.PartialContainer.EmitFieldInitializers (ec);
- // If this is a non-static `struct' constructor and doesn't have any
- // initializer, it must initialize all of the struct's fields.
- if ((Parent.Kind == Kind.Struct) &&
- ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
- Block.AddThisVariable (Parent, Location);
-
- ec.EmitTopBlock (block, ParameterInfo, Location);
+ if (block != null)
+ ec.EmitResolvedTopBlock (block, unreachable);
if (source != null)
source.CloseMethod ();
}
// Is never override
- protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
+ protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
{
return null;
}
- protected override bool VerifyClsCompliance (DeclSpace ds)
+ public override string GetSignatureForError()
+ {
+ return base.GetSignatureForError () + Parameters.GetSignatureForError ();
+ }
+
+ public override string[] ValidAttributeTargets {
+ get {
+ return attribute_targets;
+ }
+ }
+
+ protected override bool VerifyClsCompliance ()
{
- if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
+ if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
return false;
}
- if (parameter_types.Length > 0) {
- ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
+ if (ParameterInfo.Count > 0) {
+ ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
if (al.Count > 3)
- ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
+ MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
- if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
- foreach (Type param in parameter_types) {
+ if (Parent.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
+ foreach (Type param in ParameterTypes) {
if (param.IsArray) {
return true;
}
public System.Reflection.CallingConventions CallingConventions {
get {
- CallingConventions cc = Parameters.GetCallingConvention ();
+ CallingConventions cc = Parameters.CallingConvention;
- if (Parent.Kind == Kind.Class)
+ if (Parent.PartialContainer.Kind == Kind.Class)
if ((ModFlags & Modifiers.STATIC) == 0)
cc |= CallingConventions.HasThis;
}
}
- public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
+ public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
{
ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
- return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
+ return new EmitContext (this, Parent, Location, ig_, null, ModFlags, true);
}
- public ObsoleteAttribute GetObsoleteAttribute ()
+ public bool IsExcluded()
{
- return null;
+ return false;
}
- public bool IsExcluded(EmitContext ec)
- {
- return false;
+ GenericMethod IMethodData.GenericMethod {
+ get {
+ return null;
+ }
}
#endregion
CallingConventions CallingConventions { get; }
Location Location { get; }
MemberName MethodName { get; }
- Type[] ParameterTypes { get; }
Type ReturnType { get; }
+ GenericMethod GenericMethod { get; }
+ Parameters ParameterInfo { get; }
+
+ Iterator Iterator { get; }
Attributes OptAttributes { get; }
- ToplevelBlock Block { get; }
+ ToplevelBlock Block { get; set; }
- EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
+ EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
ObsoleteAttribute GetObsoleteAttribute ();
- string GetSignatureForError (TypeContainer tc);
- bool IsExcluded (EmitContext ec);
- bool IsClsCompliaceRequired (DeclSpace ds);
+ string GetSignatureForError ();
+ bool IsExcluded ();
+ bool IsClsComplianceRequired ();
void SetMemberIsUsed ();
}
readonly IMethodData method;
- //
- // The return type of this method
- //
- public readonly InternalParameters ParameterInfo;
+ public readonly GenericMethod GenericMethod;
//
// Are we implementing an interface ?
//
- public bool IsImplementing = false;
+ public MethodInfo implementing;
//
// Protected data.
//
- protected MemberBase member;
+ protected InterfaceMemberBase member;
protected int modifiers;
protected MethodAttributes flags;
+ protected Type declaring_type;
+ protected MethodInfo parent_method;
MethodBuilder builder = null;
public MethodBuilder MethodBuilder {
}
}
- public MethodData (MemberBase member, InternalParameters parameters,
+ public Type DeclaringType {
+ get {
+ return declaring_type;
+ }
+ }
+
+ public MethodData (InterfaceMemberBase member,
int modifiers, MethodAttributes flags, IMethodData method)
{
this.member = member;
- this.ParameterInfo = parameters;
this.modifiers = modifiers;
this.flags = flags;
this.method = method;
}
- public bool Define (TypeContainer container)
+ public MethodData (InterfaceMemberBase member,
+ int modifiers, MethodAttributes flags,
+ IMethodData method, MethodBuilder builder,
+ GenericMethod generic, MethodInfo parent_method)
+ : this (member, modifiers, flags, method)
{
- MethodInfo implementing = null;
+ this.builder = builder;
+ this.GenericMethod = generic;
+ this.parent_method = parent_method;
+ }
- string name = method.MethodName.Name;
- string method_name = name;
+ public bool Define (DeclSpace parent)
+ {
+ string name = method.MethodName.Basename;
+ string method_name = method.MethodName.FullName;
- Type[] ParameterTypes = method.ParameterTypes;
+ TypeContainer container = parent.PartialContainer;
- if (container.Pending != null){
+ PendingImplementation pending = container.PendingImplementations;
+ if (pending != null){
if (member is Indexer) // TODO: test it, but it should work without this IF
- implementing = container.Pending.IsInterfaceIndexer (
- member.InterfaceType, method.ReturnType, ParameterInfo);
+ implementing = pending.IsInterfaceIndexer (
+ member.InterfaceType, method.ReturnType, method.ParameterInfo);
else
- implementing = container.Pending.IsInterfaceMethod (
- member.InterfaceType, name, method.ReturnType, ParameterInfo);
+ implementing = pending.IsInterfaceMethod (
+ member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
if (member.InterfaceType != null){
if (implementing == null){
if (member is PropertyBase) {
- Report.Error (550, method.Location, "'{0}' is an accessor not found in interface member '{1}'",
- method.GetSignatureForError (container), member.Name);
+ Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
+ method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
+ member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
} else {
Report.Error (539, method.Location,
- "'{0}' in explicit interface declaration is not a member of interface", member.GetSignatureForError () );
+ "`{0}.{1}' in explicit interface declaration is not a member of interface",
+ TypeManager.CSharpName (member.InterfaceType), member.ShortName);
}
return false;
}
- if (implementing.IsSpecialName && !((member is PropertyBase || member is EventProperty))) {
+ if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
Report.SymbolRelatedToPreviousError (implementing);
- Report.Error (683, method.Location, "'{0}' explicit method implementation cannot implement '{1}' because it is an accessor",
+ Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
return false;
}
- method_name = member.InterfaceType.FullName + "." + name;
+
+ method_name = TypeManager.GetFullName (member.InterfaceType) +
+ '.' + method_name;
} else {
- if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
- Report.SymbolRelatedToPreviousError (implementing);
- Report.Error (686, method.Location, "Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation",
- method.GetSignatureForError (container), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
- return false;
+ if (implementing != null) {
+ AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
+ if (prop_method == null) {
+ if (implementing.IsSpecialName) {
+ Report.SymbolRelatedToPreviousError (implementing);
+ Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
+ method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
+ implementing.Name.StartsWith ("get_") ? "get" : "set");
+ return false;
+ }
+ } else if (implementing.DeclaringType.IsInterface) {
+ if (!implementing.IsSpecialName) {
+ Report.SymbolRelatedToPreviousError (implementing);
+ Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
+ method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
+ return false;
+ }
+ PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
+ if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
+ Report.SymbolRelatedToPreviousError (implementing);
+ Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
+ method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
+ return false;
+ }
+ }
}
}
}
// but it wont get cleared
//
if (member.IsExplicitImpl){
- if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
- Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
- implementing = null;
+ if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
+ Report.SymbolRelatedToPreviousError (implementing);
+ Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
+ method.GetSignatureForError ());
+ return false;
}
- } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
- if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
+ } else {
+ if (implementing.DeclaringType.IsInterface) {
//
// If this is an interface method implementation,
// check for public accessibility
//
- implementing = null;
+ if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
+ implementing = null;
} else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
// We may never be private.
implementing = null;
//
implementing = null;
}
- }
+ }
//
// Static is not allowed
//
if ((modifiers & Modifiers.STATIC) != 0){
implementing = null;
- Modifiers.Error_InvalidModifier (method.Location, "static");
}
}
// Set Final unless we're virtual, abstract or already overriding a method.
if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
flags |= MethodAttributes.Final;
-
- IsImplementing = true;
}
EmitContext ec = method.CreateEmitContext (container, null);
- DefineMethodBuilder (ec, container, method_name, ParameterTypes);
+ DefineMethodBuilder (container, method_name, method.ParameterInfo.Types);
if (builder == null)
return false;
+ if (container.CurrentType != null)
+ declaring_type = container.CurrentType;
+ else
+ declaring_type = container.TypeBuilder;
+
if ((modifiers & Modifiers.UNSAFE) != 0)
builder.InitLocals = false;
- if (IsImplementing){
+ if (implementing != null){
//
// clear the pending implemntation flag
//
if (member is Indexer) {
- container.Pending.ImplementIndexer (
+ pending.ImplementIndexer (
member.InterfaceType, builder, method.ReturnType,
- ParameterInfo, member.IsExplicitImpl);
+ method.ParameterInfo, member.IsExplicitImpl);
} else
- container.Pending.ImplementMethod (
+ pending.ImplementMethod (
member.InterfaceType, name, method.ReturnType,
- ParameterInfo, member.IsExplicitImpl);
+ method.ParameterInfo, member.IsExplicitImpl);
if (member.IsExplicitImpl)
container.TypeBuilder.DefineMethodOverride (
}
- TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
TypeManager.AddMethod (builder, method);
+ if (GenericMethod != null) {
+ bool is_override = member.IsExplicitImpl |
+ ((modifiers & Modifiers.OVERRIDE) != 0);
+
+ if (implementing != null)
+ parent_method = implementing;
+
+ if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
+ return false;
+ }
+
return true;
}
/// <summary>
/// Create the MethodBuilder for the method
/// </summary>
- void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
+ void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
{
- const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
-
- if ((modifiers & extern_static) == extern_static) {
+ if ((modifiers & Modifiers.EXTERN) != 0) {
if (method.OptAttributes != null) {
- Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
+ Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type);
if (dllimport_attribute != null) {
flags |= MethodAttributes.PinvokeImpl;
builder = dllimport_attribute.DefinePInvokeMethod (
- ec, container.TypeBuilder, method_name, flags,
+ container.TypeBuilder, method_name, flags,
method.ReturnType, ParameterTypes);
return;
// for extern static method must be specified either DllImport attribute or MethodImplAttribute.
// We are more strict than Microsoft and report CS0626 like error
if (method.OptAttributes == null ||
- !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
- Report.Error (626, method.Location, "Method, operator, or accessor '{0}' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation", method.GetSignatureForError (container));
+ !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type)) {
+ Report.Error (626, method.Location,
+ "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
+ member.GetSignatureForError ());
return;
}
}
- builder = container.TypeBuilder.DefineMethod (
- method_name, flags, method.CallingConventions,
+ if (builder == null) {
+ builder = container.TypeBuilder.DefineMethod (
+ method_name, flags, method.CallingConventions,
+ method.ReturnType, ParameterTypes);
+ return;
+ }
+
+#if GMCS_SOURCE && !MS_COMPATIBLE
+ builder.SetGenericMethodSignature (
+ flags, method.CallingConventions,
method.ReturnType, ParameterTypes);
+#endif
}
//
// Emits the code
//
- public void Emit (TypeContainer container, Attributable kind)
+ public void Emit (DeclSpace parent)
{
EmitContext ec;
if ((flags & MethodAttributes.PinvokeImpl) == 0)
- ec = method.CreateEmitContext (container, builder.GetILGenerator ());
+ ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
else
- ec = method.CreateEmitContext (container, null);
-
- if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
- ec.TestObsoleteMethodUsage = false;
+ ec = method.CreateEmitContext (parent, null);
- Location loc = method.Location;
- Attributes OptAttributes = method.OptAttributes;
-
- if (OptAttributes != null)
- OptAttributes.Emit (ec, kind);
+ method.ParameterInfo.ApplyAttributes (MethodBuilder);
- if (member is MethodCore)
- ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
+ if (GenericMethod != null)
+ GenericMethod.EmitAttributes ();
ToplevelBlock block = method.Block;
- //
- // abstract or extern methods have no bodies
- //
- if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
- if (block == null)
- return;
-
- //
- // abstract or extern methods have no bodies.
- //
- if ((modifiers & Modifiers.ABSTRACT) != 0)
- Report.Error (
- 500, method.Location, "Abstract method `" +
- TypeManager.CSharpSignature (builder) +
- "' can not have a body");
-
- if ((modifiers & Modifiers.EXTERN) != 0)
- Report.Error (
- 179, method.Location, "External method `" +
- TypeManager.CSharpSignature (builder) +
- "' can not have a body");
-
- return;
- }
-
- //
- // Methods must have a body unless they're extern or abstract
- //
- if (block == null) {
- Report.Error (
- 501, method.Location, "Method `" +
- TypeManager.CSharpSignature (builder) +
- "' must declare a body since it is not marked " +
- "abstract or extern");
- return;
- }
-
- SourceMethod source = SourceMethod.Create (
- container, MethodBuilder, method.Block);
+ SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
//
// Handle destructors specially
if (member is Destructor)
EmitDestructor (ec, block);
else
- ec.EmitTopBlock (block, ParameterInfo, loc);
+ ec.EmitTopBlock (method, block);
if (source != null)
source.CloseMethod ();
ig.BeginExceptionBlock ();
ec.ReturnLabel = finish;
ec.HasReturnLabel = true;
- ec.EmitTopBlock (block, null, method.Location);
+ ec.EmitTopBlock (method, block);
// ig.MarkLabel (finish);
ig.BeginFinallyBlock ();
if (ec.ContainerType.BaseType != null) {
Expression member_lookup = Expression.MemberLookup (
- ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
+ ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
"Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
if (member_lookup != null){
}
}
- // Should derive from MethodCore
+ // TODO: Should derive from MethodCore
public class Destructor : Method {
- public Destructor (TypeContainer ds, Expression return_type, int mod,
+ static string[] attribute_targets = new string [] { "method" };
+
+ public Destructor (DeclSpace parent, Expression return_type, int mod,
string name, Parameters parameters, Attributes attrs,
Location l)
- : base (ds, return_type, mod, false, new MemberName (name),
- parameters, attrs, l)
+ : base (parent, null, return_type, mod, false, new MemberName (name, l),
+ parameters, attrs)
{ }
public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
{
if (a.Type == TypeManager.conditional_attribute_type) {
- Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
+ Error_ConditionalAttributeIsNotValid ();
return;
}
base.ApplyAttributeBuilder (a, cb);
}
- }
-
- abstract public class MemberBase : MemberCore {
- public Expression Type;
- public MethodAttributes flags;
-
- protected readonly int explicit_mod_flags;
+ public override string GetSignatureForError ()
+ {
+ return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
+ }
- //
- // The "short" name of this property / indexer / event. This is the
- // name without the explicit interface.
- //
- public string ShortName {
- get { return MemberName.Name; }
- set {
- SetMemberName (new MemberName (MemberName.Left, value));
+ public override string[] ValidAttributeTargets {
+ get {
+ return attribute_targets;
}
}
+ }
+
+ abstract public class MemberBase : MemberCore {
+ public Expression Type;
+ public readonly DeclSpace ds;
+ public readonly GenericMethod GenericMethod;
//
// The type of this property / indexer / event
//
- Type member_type;
+ protected Type member_type;
public Type MemberType {
get {
if (member_type == null && Type != null) {
- EmitContext ec = Parent.EmitContext;
- bool old_unsafe = ec.InUnsafe;
- ec.InUnsafe = InUnsafe;
- Type = Type.ResolveAsTypeTerminal (ec, false);
- ec.InUnsafe = old_unsafe;
-
- member_type = Type == null ? null : Type.Type;
+ IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
+ Type = Type.ResolveAsTypeTerminal (rc, false);
+ if (Type != null) {
+ member_type = Type.Type;
+ }
}
return member_type;
}
}
- //
- // Whether this is an interface member.
- //
- public bool IsInterface;
-
- //
- // If true, this is an explicit interface implementation
- //
- public bool IsExplicitImpl;
-
- //
- // The interface type we are explicitly implementing
- //
- public Type InterfaceType = null;
-
//
// The constructor is only exposed to our children
//
- protected MemberBase (TypeContainer parent, Expression type, int mod,
- int allowed_mod, int def_mod, MemberName name,
- Attributes attrs, Location loc)
- : base (parent, name, attrs, loc)
+ protected MemberBase (DeclSpace parent, GenericMethod generic,
+ Expression type, int mod, int allowed_mod, int def_mod,
+ MemberName name, Attributes attrs)
+ : base (parent, name, attrs)
{
- explicit_mod_flags = mod;
+ this.ds = generic != null ? generic : (DeclSpace) parent;
Type = type;
- ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
- IsExplicitImpl = (MemberName.Left != null);
+ ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
+ GenericMethod = generic;
+ if (GenericMethod != null)
+ GenericMethod.ModFlags = ModFlags;
}
protected virtual bool CheckBase ()
{
- if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
- Report.Error (666, Location, "Protected member in struct declaration");
+ if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.PartialContainer.Kind == Kind.Struct) {
+ Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
return false;
}
((Parent.ModFlags & Modifiers.SEALED) != 0) &&
((ModFlags & Modifiers.PROTECTED) != 0) &&
((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
- Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
+ Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
}
- return true;
- }
-
- protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
- {
- bool error = false;
-
- foreach (Type partype in parameters){
- if (partype == TypeManager.void_type) {
- Report.Error (
- 1547, Location, "Keyword 'void' cannot " +
- "be used in this context");
- return false;
- }
-
- if (partype.IsPointer){
- if (!UnsafeOK (ds))
- error = true;
- if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
- error = true;
- }
-
- if (ds.AsAccessible (partype, ModFlags))
- continue;
-
- if (this is Indexer)
- Report.Error (55, Location,
- "Inconsistent accessibility: parameter type `" +
- TypeManager.CSharpName (partype) + "' is less " +
- "accessible than indexer `" + Name + "'");
- else if ((this is Method) && ((Method) this).IsOperator)
- Report.Error (57, Location,
- "Inconsistent accessibility: parameter type `" +
- TypeManager.CSharpName (partype) + "' is less " +
- "accessible than operator `" + Name + "'");
- else
- Report.Error (51, Location,
- "Inconsistent accessibility: parameter type `" +
- TypeManager.CSharpName (partype) + "' is less " +
- "accessible than method `" + Name + "'");
- error = true;
- }
-
- return !error;
+ return true;
}
protected virtual bool DoDefine ()
{
- EmitContext ec = Parent.EmitContext;
- if (ec == null)
- throw new InternalErrorException ("MemberBase.DoDefine called too early");
-
- if (Name == null)
- throw new InternalErrorException ();
-
- if (IsInterface) {
- ModFlags = Modifiers.PUBLIC |
- Modifiers.ABSTRACT |
- Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
-
- flags = MethodAttributes.Public |
- MethodAttributes.Abstract |
- MethodAttributes.HideBySig |
- MethodAttributes.NewSlot |
- MethodAttributes.Virtual;
- } else {
- if (!Parent.MethodModifiersValid (this))
- return false;
-
- flags = Modifiers.MethodAttr (ModFlags);
- }
-
if (MemberType == null)
return false;
- if ((Parent.ModFlags & Modifiers.SEALED) != 0){
- if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
- Report.Error (549, Location, "Virtual method can not be contained in sealed class");
+ if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
+ (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
+ Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
+ GetSignatureForError (), Parent.GetSignatureForError ());
return false;
- }
}
// verify accessibility
Report.Error (54, Location,
"Inconsistent accessibility: indexer return type `" +
TypeManager.CSharpName (MemberType) + "' is less " +
- "accessible than indexer `" + Name + "'");
+ "accessible than indexer `" + GetSignatureForError () + "'");
else if (this is MethodCore) {
if (this is Operator)
Report.Error (56, Location,
"Inconsistent accessibility: return type `" +
TypeManager.CSharpName (MemberType) + "' is less " +
- "accessible than operator `" + Name + "'");
+ "accessible than operator `" + GetSignatureForError () + "'");
else
Report.Error (50, Location,
"Inconsistent accessibility: return type `" +
TypeManager.CSharpName (MemberType) + "' is less " +
- "accessible than method `" + Name + "'");
+ "accessible than method `" + GetSignatureForError () + "'");
} else {
Report.Error (52, Location,
"Inconsistent accessibility: field type `" +
TypeManager.CSharpName (MemberType) + "' is less " +
- "accessible than field `" + Name + "'");
+ "accessible than field `" + GetSignatureForError () + "'");
}
return false;
}
- if (MemberType.IsPointer && !UnsafeOK (Parent))
- return false;
-
- if (IsExplicitImpl) {
- Expression expr = MemberName.Left.GetTypeExpression (Location);
- TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
- if (texpr == null)
- return false;
-
- InterfaceType = texpr.ResolveType (ec);
-
- if (!InterfaceType.IsInterface) {
- Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
- return false;
- }
-
- if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
- return false;
-
- Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
-
- }
return true;
}
- public override string GetSignatureForError (TypeContainer tc)
- {
- return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
- }
-
protected bool IsTypePermitted ()
{
if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
- Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
+ Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
return false;
}
return true;
}
-
- protected override bool VerifyClsCompliance(DeclSpace ds)
- {
- if (base.VerifyClsCompliance (ds)) {
- return true;
- }
-
- if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
- Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
- }
- return false;
- }
-
- protected override void VerifyObsoleteAttribute()
- {
- CheckUsageOfObsoleteAttribute (MemberType);
- }
}
//
- // Fields and Events both generate FieldBuilders, we use this to share
- // their common bits. This is also used to flag usage of the field
+ // Abstract class for all fields
//
abstract public class FieldBase : MemberBase {
- public FieldBuilder FieldBuilder;
+ public FieldBuilder FieldBuilder;
public Status status;
+ protected Expression initializer;
[Flags]
public enum Status : byte {
- ASSIGNED = 1,
HAS_OFFSET = 4 // Used by FieldMember.
}
- static string[] attribute_targets = new string [] { "field" };
-
- /// <summary>
- /// Symbol with same name in base class/struct
- /// </summary>
- public MemberInfo conflict_symbol;
-
- //
- // The constructor is only exposed to our children
- //
- protected FieldBase (TypeContainer parent, Expression type, int mod,
- int allowed_mod, MemberName name, object init,
- Attributes attrs, Location loc)
- : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
- name, attrs, loc)
+ static readonly string[] attribute_targets = new string [] { "field" };
+
+ protected FieldBase (DeclSpace parent, Expression type, int mod,
+ int allowed_mod, MemberName name, Attributes attrs)
+ : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
+ name, attrs)
{
- this.init = init;
+ if ((mod & Modifiers.ABSTRACT) != 0)
+ Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
}
public override AttributeTargets AttributeTargets {
public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
{
+ if (a.Type == TypeManager.field_offset_attribute_type) {
+ status |= Status.HAS_OFFSET;
+
+ if (!Parent.PartialContainer.HasExplicitLayout) {
+ Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
+ return;
+ }
+
+ if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
+ Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
+ return;
+ }
+ }
+
+#if NET_2_0
+ if (a.Type == TypeManager.fixed_buffer_attr_type) {
+ Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
+ return;
+ }
+#endif
+
if (a.Type == TypeManager.marshal_as_attr_type) {
UnmanagedMarshal marshal = a.GetMarshal (this);
if (marshal != null) {
FieldBuilder.SetCustomAttribute (cb);
}
- //
- // Whether this field has an initializer.
- //
- public bool HasInitializer {
- get {
- return init != null;
- }
- }
-
- protected readonly Object init;
-
- // Private.
- Expression init_expr;
- bool init_expr_initialized = false;
-
- //
- // Resolves and returns the field initializer.
- //
- public Expression GetInitializerExpression (EmitContext ec)
- {
- if (init_expr_initialized)
- return init_expr;
-
- Expression e;
- if (init is Expression)
- e = (Expression) init;
- else
- e = new ArrayCreation (Type, "", (ArrayList)init, Location);
-
- EmitContext parent_ec = Parent.EmitContext;
-
- bool old_is_static = parent_ec.IsStatic;
- parent_ec.IsStatic = ec.IsStatic;
- parent_ec.IsFieldInitializer = true;
- e = e.DoResolve (parent_ec);
- parent_ec.IsFieldInitializer = false;
- parent_ec.IsStatic = old_is_static;
-
- init_expr = e;
- init_expr_initialized = true;
-
- return init_expr;
- }
-
protected override bool CheckBase ()
{
if (!base.CheckBase ())
return false;
- // TODO: Implement
- if (IsInterface)
- return true;
-
- conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
+ MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
if (conflict_symbol == null) {
- if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
- Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
+ if ((ModFlags & Modifiers.NEW) != 0) {
+ Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
}
return true;
}
if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
Report.SymbolRelatedToPreviousError (conflict_symbol);
- Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
+ Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
+ GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
}
return true;
}
- public override string GetSignatureForError ()
- {
- if (FieldBuilder == null) {
- return base.GetSignatureForError (Parent);
- }
- return TypeManager.GetFullNameSignature (FieldBuilder);
- }
-
- protected virtual bool IsFieldClsCompliant {
- get {
- if (FieldBuilder == null)
- return true;
-
- return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
- }
- }
-
- public override string[] ValidAttributeTargets {
- get {
- return attribute_targets;
- }
- }
-
- protected override bool VerifyClsCompliance (DeclSpace ds)
- {
- if (!base.VerifyClsCompliance (ds))
- return false;
-
- if (!IsFieldClsCompliant) {
- Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
- }
- return true;
- }
-
-
- public void SetAssigned ()
- {
- status |= Status.ASSIGNED;
- }
- }
-
- public abstract class FieldMember: FieldBase
- {
- protected FieldMember (TypeContainer parent, Expression type, int mod,
- int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
- : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
- {
- if ((mod & Modifiers.ABSTRACT) != 0)
- Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
- }
-
- public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
- {
- if (a.Type == TypeManager.field_offset_attribute_type)
- {
- status |= Status.HAS_OFFSET;
-
- if (!Parent.HasExplicitLayout) {
- Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
- return;
- }
-
- if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
- Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
- return;
- }
- }
-
-#if NET_2_0
- if (a.Type == TypeManager.fixed_buffer_attr_type) {
- Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
- return;
- }
-#endif
-
- base.ApplyAttributeBuilder (a, cb);
- }
-
-
public override bool Define()
{
- EmitContext ec = Parent.EmitContext;
- if (ec == null)
- throw new InternalErrorException ("FieldMember.Define called too early");
-
- if (MemberType == null)
+ if (MemberType == null || Type == null)
return false;
if (MemberType == TypeManager.void_type) {
- Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
+ // TODO: wrong location
+ Expression.Error_VoidInvalidInTheContext (Location);
+ return false;
+ }
+
+ if (MemberType.IsSealed && MemberType.IsAbstract) {
+ Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
return false;
}
Report.Error (52, Location,
"Inconsistent accessibility: field type `" +
TypeManager.CSharpName (MemberType) + "' is less " +
- "accessible than field `" + Name + "'");
+ "accessible than field `" + GetSignatureForError () + "'");
return false;
}
if (!IsTypePermitted ())
return false;
- if (MemberType.IsPointer && !UnsafeOK (Parent))
- return false;
-
return true;
}
+ //
+ // Represents header string for documentation comment.
+ //
+ public override string DocCommentHeader {
+ get { return "F:"; }
+ }
+
public override void Emit ()
{
if (OptAttributes != null) {
- EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
- OptAttributes.Emit (ec, this);
+ OptAttributes.Emit ();
}
- if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
- Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
+ if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
+ Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
}
base.Emit ();
}
- //
- // Represents header string for documentation comment.
- //
- public override string DocCommentHeader {
- get { return "F:"; }
+ public static void Error_VariableOfStaticClass (Location loc, string variableName, Type staticClass)
+ {
+ Report.SymbolRelatedToPreviousError (staticClass);
+ Report.Error (723, loc, "`{0}': cannot declare variables of static types",
+ variableName);
+ }
+
+ public Expression Initializer {
+ set {
+ if (value != null) {
+ this.initializer = value;
+ }
+ }
+ }
+
+ protected virtual bool IsFieldClsCompliant {
+ get {
+ if (FieldBuilder == null)
+ return true;
+
+ return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
+ }
+ }
+
+ public override string[] ValidAttributeTargets
+ {
+ get {
+ return attribute_targets;
+ }
+ }
+
+ protected override bool VerifyClsCompliance ()
+ {
+ if (!base.VerifyClsCompliance ())
+ return false;
+
+ if (!IsFieldClsCompliant) {
+ Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
+ }
+ return true;
+ }
+
+ public void SetAssigned ()
+ {
+ caching_flags |= Flags.IsAssigned;
}
}
/// <summary>
/// Fixed buffer implementation
/// </summary>
- public class FixedField: FieldMember, IFixedBuffer
+ public class FixedField : FieldBase, IFixedBuffer
{
public const string FixedElementName = "FixedElementField";
static int GlobalCounter = 0;
Modifiers.INTERNAL |
Modifiers.PRIVATE;
- public FixedField (TypeContainer parent, Expression type, int mod, string name,
+ public FixedField (DeclSpace parent, Expression type, int mod, string name,
Expression size_expr, Attributes attrs, Location loc):
- base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
+ base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
{
if (RootContext.Version == LanguageVersion.ISO_1)
- Report.FeatureIsNotStandardized (loc, "fixed sized buffers");
+ Report.FeatureIsNotISO1 (loc, "fixed size buffers");
this.size_expr = size_expr;
}
{
#if !NET_2_0
if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
- Report.Warning (-23, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
+ Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
#endif
- if (Parent.Kind != Kind.Struct) {
- Report.Error (1642, Location, "Fixed buffer fields may only be members of structs");
+ if (Parent.PartialContainer.Kind != Kind.Struct) {
+ Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
+ GetSignatureForError ());
return false;
}
return false;
if (!TypeManager.IsPrimitiveType (MemberType)) {
- Report.Error (1663, Location, "Fixed sized buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double");
+ Report.Error (1663, Location, "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
+ GetSignatureForError ());
return false;
}
- Expression e = size_expr.Resolve (Parent.EmitContext);
- if (e == null)
- return false;
-
- Constant c = e as Constant;
- if (c == null) {
- Report.Error (133, Location, "The expression being assigned to '{0}' must be constant", GetSignatureForError ());
+ EmitContext ec = new EmitContext (this, Parent, Location, null, null, ModFlags);
+ Constant c = size_expr.ResolveAsConstant (ec, this);
+ if (c == null)
return false;
- }
- IntConstant buffer_size_const = c.ToInt (Location);
+ IntConstant buffer_size_const = c.ImplicitConversionRequired (TypeManager.int32_type, Location) as IntConstant;
if (buffer_size_const == null)
return false;
buffer_size = buffer_size_const.Value;
if (buffer_size <= 0) {
- Report.Error (1665, Location, "Fixed sized buffer '{0}' must have a length greater than zero", GetSignatureForError ());
+ Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
return false;
}
int type_size = Expression.GetTypeSize (MemberType);
if (buffer_size > int.MaxValue / type_size) {
- Report.Error (1664, Location, "Fixed sized buffer of length '{0}' and type '{1}' exceeded 2^31 limit",
- buffer_size.ToString (), TypeManager.CSharpName (MemberType));
+ Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
+ GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
return false;
}
//
// The Field class is used to represents class/struct fields during parsing.
//
- public class Field : FieldMember {
+ public class Field : FieldBase {
// <summary>
// Modifiers allowed in a class declaration
// </summary>
Modifiers.UNSAFE |
Modifiers.READONLY;
- public Field (TypeContainer parent, Expression type, int mod, string name,
- Object expr_or_array_init, Attributes attrs, Location loc)
- : base (parent, type, mod, AllowedModifiers, new MemberName (name),
- expr_or_array_init, attrs, loc)
+ public Field (DeclSpace parent, Expression type, int mod, string name,
+ Attributes attrs, Location loc)
+ : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
+ attrs)
{
}
(vt == TypeManager.char_type) ||
(vt == TypeManager.float_type) ||
(!vt.IsValueType))){
- Report.Error (
- 677, Location, Parent.MakeName (Name) +
- " A volatile field can not be of type `" +
- TypeManager.CSharpName (vt) + "'");
+ Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
+ GetSignatureForError (), TypeManager.CSharpName (vt));
return false;
}
}
if ((ModFlags & Modifiers.READONLY) != 0){
- Report.Error (
- 678, Location,
- "A field can not be both volatile and readonly");
+ Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
+ GetSignatureForError ());
return false;
}
}
FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
- if (Parent.Kind == Kind.Struct &&
+ if (Parent.PartialContainer.Kind == Kind.Struct &&
((fa & FieldAttributes.Static) == 0) &&
MemberType == Parent.TypeBuilder &&
!TypeManager.IsBuiltinType (MemberType)){
TypeManager.RegisterFieldBase (FieldBuilder, this);
}
catch (ArgumentException) {
- Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
+ Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
+ return false;
+ }
+
+ if (initializer != null)
+ Parent.PartialContainer.RegisterFieldForInitialization (this,
+ new FieldInitializer (FieldBuilder, initializer));
+
+ return true;
+ }
+
+ protected override bool VerifyClsCompliance ()
+ {
+ if (!base.VerifyClsCompliance ())
return false;
+
+ if ((ModFlags & Modifiers.VOLATILE) != 0) {
+ Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
}
return true;
//
// `set' and `get' accessors are represented with an Accessor.
//
- public class Accessor {
+ public class Accessor : IAnonymousHost {
//
// Null if the accessor is empty, or a Block if not
//
public Attributes Attributes;
public Location Location;
public int ModFlags;
+ public bool Yields;
+ public ArrayList AnonymousMethods;
public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
{
Location = loc;
ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
}
- }
+ public void SetYields ()
+ {
+ Yields = true;
+ }
+
+ public void AddAnonymousMethod (AnonymousMethodExpression ame)
+ {
+ if (AnonymousMethods == null)
+ AnonymousMethods = new ArrayList ();
+ AnonymousMethods.Add (ame);
+ }
+ }
// Ooouh Martin, templates are missing here.
// When it will be possible move here a lot of child code and template method type.
- public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
+ public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
protected MethodData method_data;
protected ToplevelBlock block;
protected ListDictionary declarative_security;
ReturnParameter return_attributes;
- public AbstractPropertyEventMethod (MemberBase member, string prefix)
- : base (null, SetupName (prefix, member), null, member.Location)
+ public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
+ : base (member.Parent, SetupName (prefix, member, member.Location), null)
{
this.prefix = prefix;
IsDummy = true;
}
- public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
+ public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
string prefix)
- : base (null, SetupName (prefix, member),
- accessor.Attributes, accessor.Location)
+ : base (member.Parent, SetupName (prefix, member, accessor.Location),
+ accessor.Attributes)
{
this.prefix = prefix;
this.block = accessor.Block;
}
- static MemberName SetupName (string prefix, MemberBase member)
+ static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
{
- return new MemberName (member.MemberName.Left, prefix + member.ShortName);
+ return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
}
- public void UpdateName (MemberBase member)
+ public void UpdateName (InterfaceMemberBase member)
{
- SetMemberName (SetupName (prefix, member));
+ SetMemberName (SetupName (prefix, member, Location));
}
#region IMethodData Members
+ public abstract Iterator Iterator {
+ get;
+ }
+
public ToplevelBlock Block {
get {
return block;
}
}
- public bool IsExcluded (EmitContext ec)
+ public bool IsExcluded ()
{
return false;
}
+ GenericMethod IMethodData.GenericMethod {
+ get {
+ return null;
+ }
+ }
+
public MemberName MethodName {
get {
return MemberName;
}
}
- public abstract ObsoleteAttribute GetObsoleteAttribute ();
- public abstract Type[] ParameterTypes { get; }
+ public Type[] ParameterTypes {
+ get {
+ return ParameterInfo.Types;
+ }
+ }
+
+ public abstract Parameters ParameterInfo { get ; }
public abstract Type ReturnType { get; }
- public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
+ public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
#endregion
{
if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
a.Type == TypeManager.conditional_attribute_type) {
- Report.Error (1667, a.Location, "'{0}' is not valid on property or event accessors. It is valid on {1} declarations only", TypeManager.CSharpName (a.Type), a.GetValidTargets ());
+ Report.Error (1667, a.Location,
+ "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
+ TypeManager.CSharpName (a.Type), a.GetValidTargets ());
return;
}
System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
}
- public override bool Define()
+ // It is not supported for the accessors
+ public sealed override bool Define()
{
throw new NotSupportedException ();
}
- public virtual void Emit (TypeContainer container)
+ public void Emit (DeclSpace parent)
{
- EmitMethod (container);
+ EmitMethod (parent);
+
+ if (OptAttributes != null)
+ OptAttributes.Emit ();
if (declarative_security != null) {
foreach (DictionaryEntry de in declarative_security) {
block = null;
}
- protected virtual void EmitMethod (TypeContainer container)
+ protected virtual void EmitMethod (DeclSpace parent)
{
- method_data.Emit (container, this);
+ method_data.Emit (parent);
}
- public override bool IsClsCompliaceRequired(DeclSpace ds)
+ public override bool IsClsComplianceRequired()
{
return false;
}
public bool IsDuplicateImplementation (MethodCore method)
{
- if (Name != method.Name)
+ if (!MemberName.Equals (method.MemberName))
return false;
Type[] param_types = method.ParameterTypes;
return false;
Report.SymbolRelatedToPreviousError (method);
- Report.Error (111, Location, TypeContainer.Error111, method.Parent.GetSignatureForError (), Name);
+ Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
return true;
}
get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
}
- protected override void VerifyObsoleteAttribute()
- {
- }
-
}
//
// Properties and Indexers both generate PropertyBuilders, we use this to share
// their common bits.
//
- abstract public class PropertyBase : MethodCore {
+ abstract public class PropertyBase : PropertyBasedMember {
- public class GetMethod: PropertyMethod
+ public class GetMethod : PropertyMethod
{
static string[] attribute_targets = new string [] { "method", "return" };
- public GetMethod (MethodCore method):
+ public GetMethod (PropertyBase method):
base (method, "get_")
{
}
- public GetMethod (MethodCore method, Accessor accessor):
+ public GetMethod (PropertyBase method, Accessor accessor):
base (method, accessor, "get_")
{
}
- public override MethodBuilder Define(TypeContainer container)
+ public override MethodBuilder Define (DeclSpace parent)
{
- base.Define (container);
+ base.Define (parent);
- method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
+ method_data = new MethodData (method, ModFlags, flags, this);
- if (!method_data.Define (container))
+ if (!method_data.Define (parent))
return null;
return method_data.MethodBuilder;
}
- public override string GetSignatureForError (TypeContainer tc)
- {
- return String.Concat (base.GetSignatureForError (tc), ".get");
- }
-
public override Type ReturnType {
get {
return method.MemberType;
}
}
+ public override Parameters ParameterInfo {
+ get {
+ return Parameters.EmptyReadOnlyParameters;
+ }
+ }
+
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
- public class SetMethod: PropertyMethod {
+ public class SetMethod : PropertyMethod {
static string[] attribute_targets = new string [] { "method", "param", "return" };
ImplicitParameter param_attr;
+ protected Parameters parameters;
- public SetMethod (MethodCore method):
+ public SetMethod (PropertyBase method):
base (method, "set_")
{
}
- public SetMethod (MethodCore method, Accessor accessor):
+ public SetMethod (PropertyBase method, Accessor accessor):
base (method, accessor, "set_")
{
}
base.ApplyAttributeBuilder (a, cb);
}
- protected virtual InternalParameters GetParameterInfo (EmitContext ec)
- {
- Parameter [] parms = new Parameter [1];
- parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
- Parameters parameters = new Parameters (parms, null, method.Location);
-
- bool old_unsafe = ec.InUnsafe;
- ec.InUnsafe = InUnsafe;
- Type [] types = parameters.GetParameterInfo (ec);
- ec.InUnsafe = old_unsafe;
-
- return new InternalParameters (types, parameters);
+ public override Parameters ParameterInfo {
+ get {
+ if (parameters == null)
+ DefineParameters ();
+ return parameters;
+ }
}
- public override MethodBuilder Define (TypeContainer container)
+ protected virtual void DefineParameters ()
{
- if (container.EmitContext == null)
- throw new InternalErrorException ("SetMethod.Define called too early");
-
- base.Define (container);
-
- method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
+ parameters = new Parameters (
+ new Parameter[] { new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location) },
+ new Type[] { method.MemberType });
+ }
- if (!method_data.Define (container))
+ public override MethodBuilder Define (DeclSpace parent)
+ {
+ if (IsDummy)
return null;
- return method_data.MethodBuilder;
- }
+ base.Define (parent);
- public override string GetSignatureForError (TypeContainer tc)
- {
- return String.Concat (base.GetSignatureForError (tc), ".set");
- }
+ method_data = new MethodData (method, ModFlags, flags, this);
- public override Type[] ParameterTypes {
- get {
- return new Type[] { method.MemberType };
- }
+ if (!method_data.Define (parent))
+ return null;
+
+ return method_data.MethodBuilder;
}
public override Type ReturnType {
static string[] attribute_targets = new string [] { "property" };
- public abstract class PropertyMethod: AbstractPropertyEventMethod
+ public abstract class PropertyMethod : AbstractPropertyEventMethod
{
- protected readonly MethodCore method;
+ protected readonly PropertyBase method;
protected MethodAttributes flags;
+ Iterator iterator;
+ ArrayList anonymous_methods;
+ bool yields;
- public PropertyMethod (MethodCore method, string prefix)
+ public PropertyMethod (PropertyBase method, string prefix)
: base (method, prefix)
{
this.method = method;
- Parent = method.Parent;
}
- public PropertyMethod (MethodCore method, Accessor accessor,
+ public PropertyMethod (PropertyBase method, Accessor accessor,
string prefix)
: base (method, accessor, prefix)
{
this.method = method;
- Parent = method.Parent;
this.ModFlags = accessor.ModFlags;
+ yields = accessor.Yields;
+ anonymous_methods = accessor.AnonymousMethods;
if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
- Report.FeatureIsNotStandardized (Location, "accessor modifiers");
+ Report.FeatureIsNotISO1 (Location, "access modifiers on properties");
}
}
+ public override Iterator Iterator {
+ get { return iterator; }
+ }
+
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Method;
}
}
- public override bool IsClsCompliaceRequired(DeclSpace ds)
+ public override bool IsClsComplianceRequired ()
{
- return method.IsClsCompliaceRequired (ds);
+ return method.IsClsComplianceRequired ();
}
- public InternalParameters ParameterInfo
+ public bool ResolveMembers ()
{
- get {
- return method_data.ParameterInfo;
+ if (yields) {
+ iterator = Iterator.CreateIterator (this, Parent, null, ModFlags);
+ if (iterator == null)
+ return false;
}
+
+ if (anonymous_methods != null) {
+ foreach (AnonymousMethodExpression ame in anonymous_methods) {
+ if (!ame.CreateAnonymousHelpers ())
+ return false;
+ }
+ }
+
+ return true;
}
- public virtual MethodBuilder Define (TypeContainer container)
+ public virtual MethodBuilder Define (DeclSpace parent)
{
+ if (!method.CheckAbstractAndExtern (block != null))
+ return null;
+
+ TypeContainer container = parent.PartialContainer;
+
//
// Check for custom access modifier
//
ModFlags = method.ModFlags;
flags = method.flags;
} else {
+ if (container.Kind == Kind.Interface)
+ Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
+ GetSignatureForError ());
+
if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
- Report.Error (442, Location, "{0}': abstract properties cannot have private accessors", GetSignatureForError (container));
+ Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
}
- CheckModifiers (container, ModFlags);
+ CheckModifiers (ModFlags);
ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
ModFlags |= Modifiers.PROPERTY_CUSTOM;
flags = Modifiers.MethodAttr (ModFlags);
}
return null;
-
}
public bool HasCustomAccessModifier
}
}
- public override Type[] ParameterTypes {
- get {
- return TypeManager.NoTypes;
- }
- }
-
- public override EmitContext CreateEmitContext (TypeContainer tc,
- ILGenerator ig)
+ public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
{
- return new EmitContext (
- tc, method.Parent, method.Location, ig, ReturnType,
+ return new EmitContext (method,
+ ds, method.ds, method.Location, ig, ReturnType,
method.ModFlags, false);
}
public override ObsoleteAttribute GetObsoleteAttribute ()
{
- return method.GetObsoleteAttribute (method.Parent);
+ return method.GetObsoleteAttribute ();
}
- public override string GetSignatureForError (TypeContainer tc)
+ public override string GetSignatureForError()
{
- return String.Concat (tc.Name, '.', method.Name);
+ return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
}
- void CheckModifiers (TypeContainer container, int modflags)
+ void CheckModifiers (int modflags)
{
int flags = 0;
int mflags = method.ModFlags & Modifiers.Accessibility;
else if ((mflags & Modifiers.INTERNAL) != 0)
flags |= Modifiers.PRIVATE;
- if ((mflags == modflags) || (modflags & (~flags)) != 0)
- Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
- GetSignatureForError (container));
+ if ((mflags == modflags) || (modflags & (~flags)) != 0) {
+ Report.Error (273, Location,
+ "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
+ GetSignatureForError (), method.GetSignatureForError ());
+ }
}
public override bool MarkForDuplicationCheck ()
}
}
-
public PropertyMethod Get, Set;
public PropertyBuilder PropertyBuilder;
public MethodBuilder GetBuilder, SetBuilder;
- protected EmitContext ec;
+ protected bool define_set_first = false;
- public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
+ public PropertyBase (DeclSpace parent, Expression type, int mod_flags,
int allowed_mod, bool is_iface, MemberName name,
- Parameters parameters, Attributes attrs,
- Location loc)
- : base (ds, type, mod_flags, allowed_mod, is_iface, name,
- attrs, parameters, loc)
+ Attributes attrs, bool define_set_first)
+ : base (parent, null, type, mod_flags, allowed_mod, is_iface, name, attrs)
{
+ this.define_set_first = define_set_first;
}
public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
// Accessors modifiers check
//
if (Get.ModFlags != 0 && Set.ModFlags != 0) {
- Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
+ Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
GetSignatureForError ());
return false;
}
if ((Get.IsDummy || Set.IsDummy)
&& (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
Report.Error (276, Location,
- "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
+ "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
GetSignatureForError ());
return false;
}
return false;
}
- ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
return true;
}
- public override string GetSignatureForError()
+ bool DefineGet ()
+ {
+ if (Get.IsDummy)
+ return true;
+
+ GetBuilder = Get.Define (Parent);
+ return GetBuilder != null;
+ }
+
+ bool DefineSet (bool define)
{
- if (PropertyBuilder == null)
- return GetSignatureForError (Parent);
+ if (!define || Set.IsDummy)
+ return true;
- return TypeManager.CSharpSignature (PropertyBuilder, false);
+ SetBuilder = Set.Define (Parent);
+ return SetBuilder != null;
}
- protected override bool CheckForDuplications ()
+ protected bool DefineAccessors ()
{
- ArrayList ar = Parent.Indexers;
- if (ar != null) {
- int arLen = ar.Count;
-
- for (int i = 0; i < arLen; i++) {
- Indexer m = (Indexer) ar [i];
- if (IsDuplicateImplementation (m))
- return false;
- }
- }
-
- ar = Parent.Properties;
- if (ar != null) {
- int arLen = ar.Count;
-
- for (int i = 0; i < arLen; i++) {
- Property m = (Property) ar [i];
- if (IsDuplicateImplementation (m))
- return false;
- }
- }
-
- return true;
+ return DefineSet (define_set_first) &&
+ DefineGet () &&
+ DefineSet (!define_set_first);
}
+ protected abstract PropertyInfo ResolveBaseProperty ();
+
// TODO: rename to Resolve......
- protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
+ protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
{
- PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
- container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
-
+ PropertyInfo base_property = ResolveBaseProperty ();
if (base_property == null)
return null;
if ((ModFlags & Modifiers.OVERRIDE) != 0) {
if (Get != null && !Get.IsDummy && get_accessor == null) {
Report.SymbolRelatedToPreviousError (base_property);
- Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
+ Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
}
if (Set != null && !Set.IsDummy && set_accessor == null) {
Report.SymbolRelatedToPreviousError (base_property);
- Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
+ Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
}
}
//
// Check base class accessors access
//
+
+ // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
get_accessor_access = set_accessor_access = 0;
if ((ModFlags & Modifiers.NEW) == 0) {
if (get_accessor != null) {
get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
- Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
- GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
+ Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
}
if (set_accessor != null) {
set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
- Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
- GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
+ Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
}
}
// Get the less restrictive access
//
return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
- }
+ }
public override void Emit ()
{
// put the attribute
//
if (PropertyBuilder != null && OptAttributes != null)
- OptAttributes.Emit (ec, this);
+ OptAttributes.Emit ();
if (!Get.IsDummy)
Get.Emit (Parent);
Set.UpdateName (this);
}
- protected override bool VerifyClsCompliance (DeclSpace ds)
- {
- if (!base.VerifyClsCompliance (ds))
- return false;
-
- if ((Get.ModFlags != ModFlags && !Get.IsDummy) || (Set.ModFlags != ModFlags && !Set.IsDummy)) {
- Report.Error (3025, Get.ModFlags != ModFlags ? Get.Location : Set.Location,
- "CLS-compliant accessors must have the same accessibility as their property");
- }
- return true;
- }
-
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
- public class Property : PropertyBase, IIteratorContainer {
+ public class Property : PropertyBase {
const int AllowedModifiers =
Modifiers.NEW |
Modifiers.PUBLIC |
const int AllowedInterfaceModifiers =
Modifiers.NEW;
- public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
+ public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
MemberName name, Attributes attrs, Accessor get_block,
- Accessor set_block, Location loc)
- : base (ds, type, mod,
+ Accessor set_block, bool define_set_first)
+ : base (parent, type, mod,
is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
- is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
- loc)
+ is_iface, name, attrs, define_set_first)
{
if (get_block == null)
Get = new GetMethod (this);
public override bool Define ()
{
+ if (!DoDefineBase ())
+ return false;
+
if (!base.Define ())
return false;
flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
- if (!Get.IsDummy) {
-
- GetBuilder = Get.Define (Parent);
- if (GetBuilder == null)
- return false;
-
- //
- // Setup iterator if we are one
- //
- if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
- Iterator iterator = new Iterator (
- Parent, "get", MemberType,
- Get.ParameterInfo,
- ModFlags, Get.Block, Location);
-
- if (!iterator.DefineIterator ())
- return false;
- Get.Block = iterator.Block;
- }
- }
-
- if (!Set.IsDummy) {
- SetBuilder = Set.Define (Parent);
- if (SetBuilder == null)
- return false;
-
- SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
- }
+ if (!DefineAccessors ())
+ return false;
// FIXME - PropertyAttributes.HasDefault ?
-
- PropertyAttributes prop_attr = PropertyAttributes.None;
- if (!IsInterface)
- prop_attr |= PropertyAttributes.RTSpecialName |
- PropertyAttributes.SpecialName;
PropertyBuilder = Parent.TypeBuilder.DefineProperty (
- Name, prop_attr, MemberType, null);
-
+ MemberName.ToString (), PropertyAttributes.None, MemberType, null);
+
if (!Get.IsDummy)
PropertyBuilder.SetGetMethod (GetBuilder);
if (!Set.IsDummy)
PropertyBuilder.SetSetMethod (SetBuilder);
- TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
+ TypeManager.RegisterProperty (PropertyBuilder, this);
return true;
}
- public void SetYields ()
+ protected override PropertyInfo ResolveBaseProperty ()
{
- ModFlags |= Modifiers.METHOD_YIELDS;
+ return Parent.PartialContainer.BaseCache.FindMemberToOverride (
+ Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters.Types, null, true) as PropertyInfo;
}
}
public void SetUsed ()
{
if (my_event != null) {
- my_event.status = FieldBase.Status.ASSIGNED;
+// my_event.SetAssigned ();
my_event.SetMemberIsUsed ();
}
}
/// For case when event is declared like property (with add and remove accessors).
/// </summary>
public class EventProperty: Event {
+ abstract class AEventPropertyAccessor : AEventAccessor
+ {
+ public AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
+ base (method, accessor, prefix)
+ {
+ }
- static string[] attribute_targets = new string [] { "event", "property" };
+ public override MethodBuilder Define (DeclSpace ds)
+ {
+ method.CheckAbstractAndExtern (block != null);
+ return base.Define (ds);
+ }
+ }
- public EventProperty (TypeContainer parent, Expression type, int mod_flags,
- bool is_iface, MemberName name, Object init,
- Attributes attrs, Accessor add, Accessor remove,
- Location loc)
- : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
+ sealed class AddDelegateMethod: AEventPropertyAccessor
{
- Add = new AddDelegateMethod (this, add);
- Remove = new RemoveDelegateMethod (this, remove);
+ public AddDelegateMethod (Event method, Accessor accessor):
+ base (method, accessor, "add_")
+ {
+ }
- // For this event syntax we don't report error CS0067
- // because it is hard to do it.
- SetAssigned ();
+ protected override MethodInfo DelegateMethodInfo {
+ get {
+ return TypeManager.delegate_combine_delegate_delegate;
+ }
+ }
}
- public override string[] ValidAttributeTargets {
- get {
- return attribute_targets;
+ sealed class RemoveDelegateMethod: AEventPropertyAccessor
+ {
+ public RemoveDelegateMethod (Event method, Accessor accessor):
+ base (method, accessor, "remove_")
+ {
+ }
+
+ protected override MethodInfo DelegateMethodInfo {
+ get {
+ return TypeManager.delegate_remove_delegate_delegate;
+ }
}
}
- }
- /// <summary>
- /// Event is declared like field.
- /// </summary>
- public class EventField: Event {
- static string[] attribute_targets = new string [] { "event", "field", "method" };
- static string[] attribute_targets_interface = new string[] { "event", "method" };
+ static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
- public EventField (TypeContainer parent, Expression type, int mod_flags,
- bool is_iface, MemberName name, Object init,
- Attributes attrs, Location loc)
- : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
+ public EventProperty (DeclSpace parent, Expression type, int mod_flags,
+ bool is_iface, MemberName name,
+ Attributes attrs, Accessor add, Accessor remove)
+ : base (parent, type, mod_flags, is_iface, name, attrs)
{
- Add = new AddDelegateMethod (this);
- Remove = new RemoveDelegateMethod (this);
+ Add = new AddDelegateMethod (this, add);
+ Remove = new RemoveDelegateMethod (this, remove);
}
- public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+ public override bool Define()
{
- if (a.Target == AttributeTargets.Field) {
- FieldBuilder.SetCustomAttribute (cb);
- return;
- }
+ if (!base.Define ())
+ return false;
- if (a.Target == AttributeTargets.Method) {
- Add.ApplyAttributeBuilder (a, cb);
- Remove.ApplyAttributeBuilder (a, cb);
- return;
- }
+ if (IsExplicitImpl)
+ SetMemberIsUsed ();
- base.ApplyAttributeBuilder (a, cb);
+ return true;
}
public override string[] ValidAttributeTargets {
get {
- return IsInterface ? attribute_targets_interface : attribute_targets;
+ return attribute_targets;
}
}
}
- public abstract class Event : FieldBase {
-
- protected sealed class AddDelegateMethod: DelegateMethod
+ /// <summary>
+ /// Event is declared like field.
+ /// </summary>
+ public class EventField : Event {
+ abstract class EventFieldAccessor : AEventAccessor
{
+ protected EventFieldAccessor (Event method, string prefix)
+ : base (method, prefix)
+ {
+ }
- public AddDelegateMethod (Event method):
- base (method, "add_")
+ protected override void EmitMethod(DeclSpace parent)
{
+ if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
+ return;
+
+ ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
+
+ // TODO: because we cannot use generics yet
+ FieldInfo field_info = ((EventField)method).FieldBuilder;
+
+ method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
+ if ((method.ModFlags & Modifiers.STATIC) != 0) {
+ ig.Emit (OpCodes.Ldsfld, field_info);
+ ig.Emit (OpCodes.Ldarg_0);
+ ig.Emit (OpCodes.Call, DelegateMethodInfo);
+ ig.Emit (OpCodes.Castclass, method.MemberType);
+ ig.Emit (OpCodes.Stsfld, field_info);
+ } else {
+ ig.Emit (OpCodes.Ldarg_0);
+ ig.Emit (OpCodes.Ldarg_0);
+ ig.Emit (OpCodes.Ldfld, field_info);
+ ig.Emit (OpCodes.Ldarg_1);
+ ig.Emit (OpCodes.Call, DelegateMethodInfo);
+ ig.Emit (OpCodes.Castclass, method.MemberType);
+ ig.Emit (OpCodes.Stfld, field_info);
+ }
+ ig.Emit (OpCodes.Ret);
}
+ }
- public AddDelegateMethod (Event method, Accessor accessor):
- base (method, accessor, "add_")
+ sealed class AddDelegateMethod: EventFieldAccessor
+ {
+ public AddDelegateMethod (Event method):
+ base (method, "add_")
{
}
return TypeManager.delegate_combine_delegate_delegate;
}
}
-
}
- protected sealed class RemoveDelegateMethod: DelegateMethod
+ sealed class RemoveDelegateMethod: EventFieldAccessor
{
public RemoveDelegateMethod (Event method):
base (method, "remove_")
{
}
- public RemoveDelegateMethod (Event method, Accessor accessor):
- base (method, accessor, "remove_")
- {
- }
-
protected override MethodInfo DelegateMethodInfo {
get {
return TypeManager.delegate_remove_delegate_delegate;
}
}
-
}
- public abstract class DelegateMethod: AbstractPropertyEventMethod
- {
- protected readonly Event method;
- ImplicitParameter param_attr;
- static string[] attribute_targets = new string [] { "method", "param", "return" };
+ static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
+ static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
- public DelegateMethod (Event method, string prefix)
- : base (method, prefix)
- {
- this.method = method;
+ public FieldBuilder FieldBuilder;
+ public Expression Initializer;
+
+ public EventField (DeclSpace parent, Expression type, int mod_flags,
+ bool is_iface, MemberName name,
+ Attributes attrs)
+ : base (parent, type, mod_flags, is_iface, name, attrs)
+ {
+ Add = new AddDelegateMethod (this);
+ Remove = new RemoveDelegateMethod (this);
+ }
+
+ public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+ {
+ if (a.Target == AttributeTargets.Field) {
+ FieldBuilder.SetCustomAttribute (cb);
+ return;
}
- public DelegateMethod (Event method, Accessor accessor, string prefix)
- : base (method, accessor, prefix)
- {
- this.method = method;
+ if (a.Target == AttributeTargets.Method) {
+ int errors = Report.Errors;
+ Add.ApplyAttributeBuilder (a, cb);
+ if (errors == Report.Errors)
+ Remove.ApplyAttributeBuilder (a, cb);
+ return;
}
- protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
- {
- if (a.Target == AttributeTargets.Parameter) {
- if (param_attr == null)
- param_attr = new ImplicitParameter (method_data.MethodBuilder);
+ base.ApplyAttributeBuilder (a, cb);
+ }
- param_attr.ApplyAttributeBuilder (a, cb);
- return;
- }
+ public override bool Define()
+ {
+ if (!base.Define ())
+ return false;
- base.ApplyAttributeBuilder (a, cb);
- }
+ if (IsInterface)
+ return true;
- public override AttributeTargets AttributeTargets {
- get {
- return AttributeTargets.Method;
+ // FIXME: We are unable to detect whether generic event is used because
+ // we are using FieldExpr instead of EventExpr for event access in that
+ // case. When this issue will be fixed this hack can be removed.
+ if (TypeManager.IsGenericType (MemberType))
+ SetMemberIsUsed();
+
+ FieldBuilder = Parent.TypeBuilder.DefineField (
+ Name, MemberType,
+ FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
+ TypeManager.RegisterEventField (EventBuilder, this);
+
+ if (Initializer != null) {
+ if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
+ Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
+ GetSignatureForError ());
+ return false;
}
- }
- public override bool IsClsCompliaceRequired(DeclSpace ds)
- {
- return method.IsClsCompliaceRequired (ds);
+ Parent.PartialContainer.RegisterFieldForInitialization (this,
+ new FieldInitializer (FieldBuilder, Initializer));
}
- public MethodBuilder Define (TypeContainer container, InternalParameters ip)
- {
- method_data = new MethodData (method, ip, method.ModFlags,
- method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
-
- if (!method_data.Define (container))
- return null;
+ return true;
+ }
- MethodBuilder mb = method_data.MethodBuilder;
- mb.DefineParameter (1, ParameterAttributes.None, "value");
- return mb;
+ public override string[] ValidAttributeTargets
+ {
+ get {
+ return IsInterface ? attribute_targets_interface : attribute_targets;
}
+ }
+ }
+
+ public abstract class Event : PropertyBasedMember {
+ public abstract class AEventAccessor : AbstractPropertyEventMethod
+ {
+ protected readonly Event method;
+ ImplicitParameter param_attr;
+ static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
- protected override void EmitMethod (TypeContainer tc)
+ protected AEventAccessor (Event method, string prefix)
+ : base (method, prefix)
{
- if (block != null) {
- base.EmitMethod (tc);
- return;
- }
+ this.method = method;
+ }
- if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
- return;
+ protected AEventAccessor (Event method, Accessor accessor, string prefix)
+ : base (method, accessor, prefix)
+ {
+ this.method = method;
+ }
- ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
- FieldInfo field_info = (FieldInfo)method.FieldBuilder;
+ public override Iterator Iterator {
+ get { return null; }
+ }
- method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
- if ((method.ModFlags & Modifiers.STATIC) != 0) {
- ig.Emit (OpCodes.Ldsfld, field_info);
- ig.Emit (OpCodes.Ldarg_0);
- ig.Emit (OpCodes.Call, DelegateMethodInfo);
- ig.Emit (OpCodes.Castclass, method.MemberType);
- ig.Emit (OpCodes.Stsfld, field_info);
- } else {
- ig.Emit (OpCodes.Ldarg_0);
- ig.Emit (OpCodes.Ldarg_0);
- ig.Emit (OpCodes.Ldfld, field_info);
- ig.Emit (OpCodes.Ldarg_1);
- ig.Emit (OpCodes.Call, DelegateMethodInfo);
- ig.Emit (OpCodes.Castclass, method.MemberType);
- ig.Emit (OpCodes.Stfld, field_info);
+ protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
+ {
+ if (a.Target == AttributeTargets.Parameter) {
+ if (param_attr == null)
+ param_attr = new ImplicitParameter (method_data.MethodBuilder);
+
+ param_attr.ApplyAttributeBuilder (a, cb);
+ return;
}
- ig.Emit (OpCodes.Ret);
- }
- protected abstract MethodInfo DelegateMethodInfo { get; }
+ base.ApplyAttributeBuilder (a, cb);
+ }
- public override Type[] ParameterTypes {
+ public override AttributeTargets AttributeTargets {
get {
- return new Type[] { method.MemberType };
+ return AttributeTargets.Method;
}
}
+ public override bool IsClsComplianceRequired ()
+ {
+ return method.IsClsComplianceRequired ();
+ }
+
+ public virtual MethodBuilder Define (DeclSpace parent)
+ {
+ method_data = new MethodData (method, method.ModFlags,
+ method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
+
+ if (!method_data.Define (parent))
+ return null;
+
+ MethodBuilder mb = method_data.MethodBuilder;
+ ParameterInfo.ApplyAttributes (mb);
+ return mb;
+ }
+
+ protected abstract MethodInfo DelegateMethodInfo { get; }
+
public override Type ReturnType {
get {
return TypeManager.void_type;
}
}
- public override EmitContext CreateEmitContext (TypeContainer tc,
- ILGenerator ig)
+ public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
{
return new EmitContext (
- tc, method.Parent, Location, ig, ReturnType,
+ ds, method.Parent, Location, ig, ReturnType,
method.ModFlags, false);
}
- public override string GetSignatureForError (TypeContainer tc)
- {
- return String.Concat (tc.Name, '.', method.Name);
- }
-
public override ObsoleteAttribute GetObsoleteAttribute ()
{
- return method.GetObsoleteAttribute (method.Parent);
+ return method.GetObsoleteAttribute ();
}
public override string[] ValidAttributeTargets {
return attribute_targets;
}
}
+
+ public override Parameters ParameterInfo {
+ get {
+ return method.parameters;
+ }
+ }
}
Modifiers.SEALED |
Modifiers.OVERRIDE |
Modifiers.UNSAFE |
- Modifiers.ABSTRACT;
+ Modifiers.ABSTRACT |
+ Modifiers.EXTERN;
const int AllowedInterfaceModifiers =
Modifiers.NEW;
- public DelegateMethod Add, Remove;
+ public AEventAccessor Add, Remove;
public MyEventBuilder EventBuilder;
public MethodBuilder AddBuilder, RemoveBuilder;
- public Event (TypeContainer parent, Expression type, int mod_flags,
- bool is_iface, MemberName name, Object init, Attributes attrs,
- Location loc)
- : base (parent, type, mod_flags,
- is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
- name, init, attrs, loc)
+ Parameters parameters;
+
+ protected Event (DeclSpace parent, Expression type, int mod_flags,
+ bool is_iface, MemberName name, Attributes attrs)
+ : base (parent, null, type, mod_flags,
+ is_iface ? AllowedInterfaceModifiers : AllowedModifiers, is_iface,
+ name, attrs)
{
- IsInterface = is_iface;
}
public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
public override bool Define ()
{
- EventAttributes e_attr;
- e_attr = EventAttributes.None;
+ if (!DoDefineBase ())
+ return false;
if (!DoDefine ())
return false;
- if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
- Report.Error (74, Location, "'" + Parent.Name + "." + Name +
- "': abstract event can not have an initializer");
- return false;
- }
-
- if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
- Report.Error (66, Location, "'" + Parent.Name + "." + Name +
- "' : event must be of a delegate type");
+ if (!TypeManager.IsDelegateType (MemberType)) {
+ Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
return false;
}
- EmitContext ec = Parent.EmitContext;
- if (ec == null)
- throw new InternalErrorException ("Event.Define called too early?");
- bool old_unsafe = ec.InUnsafe;
- ec.InUnsafe = InUnsafe;
-
- Parameter [] parms = new Parameter [1];
- parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
- Parameters parameters = new Parameters (parms, null, Location);
- Type [] types = parameters.GetParameterInfo (ec);
- InternalParameters ip = new InternalParameters (types, parameters);
-
- ec.InUnsafe = old_unsafe;
+ parameters = new Parameters (
+ new Parameter[] { new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location) },
+ new Type[] { MemberType } );
if (!CheckBase ())
return false;
// Now define the accessors
//
- AddBuilder = Add.Define (Parent, ip);
+ AddBuilder = Add.Define (Parent);
if (AddBuilder == null)
return false;
- RemoveBuilder = Remove.Define (Parent, ip);
+ RemoveBuilder = Remove.Define (Parent);
if (RemoveBuilder == null)
return false;
- EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
-
- if (Add.Block == null && Remove.Block == null && !IsInterface) {
- FieldBuilder = Parent.TypeBuilder.DefineField (
- Name, MemberType,
- FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
- TypeManager.RegisterPrivateFieldOfEvent (
- (EventInfo) EventBuilder, FieldBuilder);
- TypeManager.RegisterFieldBase (FieldBuilder, this);
- }
-
+ EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
EventBuilder.SetAddOnMethod (AddBuilder);
EventBuilder.SetRemoveOnMethod (RemoveBuilder);
-
- TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
return true;
}
- protected override bool CheckBase ()
- {
- if (!base.CheckBase ())
- return false;
-
- if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
- if (!(conflict_symbol is EventInfo)) {
- Report.SymbolRelatedToPreviousError (conflict_symbol);
- Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
- return false;
- }
- }
-
- return true;
- }
-
public override void Emit ()
{
if (OptAttributes != null) {
- EmitContext ec = new EmitContext (
- Parent, Location, null, MemberType, ModFlags);
- OptAttributes.Emit (ec, this);
+ OptAttributes.Emit ();
}
Add.Emit (Parent);
base.Emit ();
}
- public override string GetSignatureForError ()
+ protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
{
- if (EventBuilder == null)
- return base.GetSignatureForError (Parent);
+ MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
+ Parent.TypeBuilder, Name);
- return TypeManager.GetFullNameSignature (EventBuilder);
+ if (mi == null)
+ return null;
+
+ ParameterData pd = TypeManager.GetParameterData (mi);
+ base_ret_type = pd.ParameterType (0);
+ return mi;
}
//
}
}
-
+
public class Indexer : PropertyBase {
- class GetIndexerMethod: GetMethod
+ class GetIndexerMethod : GetMethod
{
- public GetIndexerMethod (MethodCore method):
+ public GetIndexerMethod (PropertyBase method):
base (method)
{
}
- public GetIndexerMethod (MethodCore method, Accessor accessor):
+ public GetIndexerMethod (PropertyBase method, Accessor accessor):
base (method, accessor)
{
}
- // TODO: one GetSignatureForError is enough (reuse Parent member)
- public override string GetSignatureForError (TypeContainer tc)
- {
- string core = base.GetSignatureForError (tc);
- return core.Replace (TypeContainer.DefaultIndexerName,
- String.Format ("this[{0}]", TypeManager.CSharpName (ParameterTypes)));
- }
-
- public override Type[] ParameterTypes {
+ public override Parameters ParameterInfo {
get {
- return method.ParameterTypes;
+ return ((Indexer)method).parameters;
}
}
}
class SetIndexerMethod: SetMethod
{
- readonly Parameters parameters;
-
- public SetIndexerMethod (MethodCore method):
+ public SetIndexerMethod (PropertyBase method):
base (method)
{
}
- public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
+ public SetIndexerMethod (PropertyBase method, Accessor accessor):
base (method, accessor)
{
- this.parameters = parameters;
- }
-
- public override Type[] ParameterTypes {
- get {
- int top = method.ParameterTypes.Length;
- Type [] set_pars = new Type [top + 1];
- method.ParameterTypes.CopyTo (set_pars, 0);
- set_pars [top] = method.MemberType;
- return set_pars;
- }
}
- protected override InternalParameters GetParameterInfo (EmitContext ec)
+ protected override void DefineParameters ()
{
- Parameter [] fixed_parms = parameters.FixedParameters;
-
- if (fixed_parms == null){
- throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
- // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
- // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
- //
- // Here is the problem: the `value' parameter has
- // to come *after* the array parameter in the declaration
- // like this:
- // X (object [] x, Type value)
- // .param [0]
- //
- // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
- // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
-
- }
-
- Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
-
- fixed_parms.CopyTo (tmp, 0);
- tmp [fixed_parms.Length] = new Parameter (
- method.Type, "value", Parameter.Modifier.NONE, null);
-
- Parameters set_formal_params = new Parameters (tmp, null, method.Location);
- Type [] types = set_formal_params.GetParameterInfo (ec);
-
- return new InternalParameters (types, set_formal_params);
+ parameters = Parameters.MergeGenerated (((Indexer)method).parameters,
+ new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
}
}
-
const int AllowedModifiers =
Modifiers.NEW |
Modifiers.PUBLIC |
const int AllowedInterfaceModifiers =
Modifiers.NEW;
+ public readonly Parameters parameters;
- public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
+ public Indexer (DeclSpace parent, Expression type, MemberName name, int mod,
bool is_iface, Parameters parameters, Attributes attrs,
- Accessor get_block, Accessor set_block, Location loc)
- : base (ds, type, mod,
+ Accessor get_block, Accessor set_block, bool define_set_first)
+ : base (parent, type, mod,
is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
- is_iface, name, parameters, attrs, loc)
+ is_iface, name, attrs, define_set_first)
{
+ this.parameters = parameters;
+
if (get_block == null)
Get = new GetIndexerMethod (this);
else
if (set_block == null)
Set = new SetIndexerMethod (this);
else
- Set = new SetIndexerMethod (this, parameters, set_block);
+ Set = new SetIndexerMethod (this, set_block);
+ }
+
+ protected override bool CheckForDuplications ()
+ {
+ ArrayList ar = Parent.PartialContainer.Indexers;
+ if (ar != null) {
+ int arLen = ar.Count;
+
+ for (int i = 0; i < arLen; i++) {
+ Indexer m = (Indexer) ar [i];
+ if (IsDuplicateImplementation (m))
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ bool IsDuplicateImplementation (Indexer indexer)
+ {
+ if (this == indexer)
+ return false;
+
+ if (!MemberName.Equals (indexer.MemberName))
+ return false;
+
+ Type[] param_types = indexer.parameters.Types;
+
+ // When it is not yet defined
+ if (param_types == null)
+ return false;
+
+ if (param_types.Length != parameters.Count)
+ return false;
+
+ for (int i = 0; i < param_types.Length; i++)
+ if (param_types [i] != parameters.Types [i])
+ return false;
+
+ Report.SymbolRelatedToPreviousError (indexer);
+ Report.Error (111, Location, TypeContainer.Error111, indexer.GetSignatureForError ());
+ return true;
}
-
+
+
public override bool Define ()
{
- PropertyAttributes prop_attr =
- PropertyAttributes.RTSpecialName |
- PropertyAttributes.SpecialName;
-
+ if (!DoDefineBase ())
+ return false;
+
if (!base.Define ())
return false;
+ if (!parameters.Resolve (ds))
+ return false;
+
+ if (!CheckParameters (parameters))
+ return false;
+
if (MemberType == TypeManager.void_type) {
Report.Error (620, Location, "Indexers cannot have void type");
return false;
}
if (OptAttributes != null) {
- Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
+ Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
if (indexer_attr != null) {
// Remove the attribute from the list because it is not emitted
OptAttributes.Attrs.Remove (indexer_attr);
- ShortName = indexer_attr.GetIndexerAttributeValue (ec);
+ string name = indexer_attr.GetIndexerAttributeValue ();
+ if (name == null)
+ return false;
+
+ ShortName = name;
if (IsExplicitImpl) {
Report.Error (415, indexer_attr.Location,
- "The 'IndexerName' attribute is valid only on an " +
+ "The `IndexerName' attribute is valid only on an " +
"indexer that is not an explicit interface member declaration");
return false;
}
if ((ModFlags & Modifiers.OVERRIDE) != 0) {
Report.Error (609, indexer_attr.Location,
- "Cannot set the 'IndexerName' attribute on an indexer marked override");
- return false;
- }
-
- if (!Tokenizer.IsValidIdentifier (ShortName)) {
- Report.Error (633, indexer_attr.Location,
- "The argument to the 'IndexerName' attribute must be a valid identifier");
+ "Cannot set the `IndexerName' attribute on an indexer marked override");
return false;
}
}
ShortName = base_IndexerName;
}
- if (!Parent.AddToMemberContainer (this) ||
- !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
+ if (!Parent.PartialContainer.AddMember (this) ||
+ !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
return false;
if (!CheckBase ())
return false;
flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
- if (!Get.IsDummy){
- GetBuilder = Get.Define (Parent);
- if (GetBuilder == null)
- return false;
- }
- if (!Set.IsDummy){
- SetBuilder = Set.Define (Parent);
- if (SetBuilder == null)
- return false;
+ if (!DefineAccessors ())
+ return false;
+
+ if (!Get.IsDummy) {
+ // Setup iterator if we are one
+ if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
+ Iterator iterator = Iterator.CreateIterator (Get, Parent, null, ModFlags);
+ if (iterator == null)
+ return false;
+ }
}
//
// Now name the parameters
//
- Parameter [] p = Parameters.FixedParameters;
+ Parameter [] p = parameters.FixedParameters;
if (p != null) {
+ // TODO: should be done in parser and it needs to do cycle
if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
- Report.Error (631, Location, "ref and out are not valid in this context");
+ CSharpParser.Error_ParameterModifierNotValid (Location);
return false;
}
-
- int i;
-
- for (i = 0; i < p.Length; ++i) {
- if (!Get.IsDummy)
- GetBuilder.DefineParameter (
- i + 1, p [i].Attributes, p [i].Name);
-
- if (!Set.IsDummy)
- SetBuilder.DefineParameter (
- i + 1, p [i].Attributes, p [i].Name);
- }
-
- if (!Set.IsDummy)
- SetBuilder.DefineParameter (
- i + 1, ParameterAttributes.None, "value");
-
- if (i != ParameterTypes.Length) {
- Parameter array_param = Parameters.ArrayParameter;
-
- SetBuilder.DefineParameter (
- i + 1, array_param.Attributes, array_param.Name);
- }
}
PropertyBuilder = Parent.TypeBuilder.DefineProperty (
- Name, prop_attr, MemberType, ParameterTypes);
+ Name, PropertyAttributes.None, MemberType, parameters.Types);
if (!Get.IsDummy)
PropertyBuilder.SetGetMethod (GetBuilder);
if (!Set.IsDummy)
PropertyBuilder.SetSetMethod (SetBuilder);
- TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
+ TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, parameters.Types);
return true;
}
- public override string GetSignatureForError ()
+ public override string GetDocCommentName (DeclSpace ds)
{
- if (PropertyBuilder == null)
- return GetSignatureForError (Parent);
-
- return TypeManager.CSharpSignature (PropertyBuilder, true);
+ return DocUtil.GetMethodDocCommentName (this, parameters, ds);
}
- public override string GetSignatureForError(TypeContainer tc)
+ public override string GetSignatureForError ()
{
- return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
+ StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
+ if (MemberName.Left != null) {
+ sb.Append ('.');
+ sb.Append (MemberName.Left);
+ }
+
+ sb.Append (".this");
+ sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
+ return sb.ToString ();
}
public override bool MarkForDuplicationCheck ()
return true;
}
+ protected override PropertyInfo ResolveBaseProperty ()
+ {
+ return Parent.PartialContainer.BaseCache.FindMemberToOverride (
+ Parent.TypeBuilder, Name, parameters.Types, null, true) as PropertyInfo;
+ }
+
+ protected override bool VerifyClsCompliance ()
+ {
+ if (!base.VerifyClsCompliance ())
+ return false;
+
+ parameters.VerifyClsCompliance ();
+ return true;
+ }
}
- public class Operator : MethodCore, IIteratorContainer {
+ public class Operator : MethodOrOperator, IAnonymousHost {
const int AllowedModifiers =
Modifiers.PUBLIC |
// Implicit and Explicit
Implicit,
- Explicit
+ Explicit,
+
+ // Just because of enum
+ TOP
};
public readonly OpType OperatorType;
- public MethodBuilder OperatorMethodBuilder;
- public Method OperatorMethod;
-
- static string[] attribute_targets = new string [] { "method", "return" };
-
- public Operator (TypeContainer parent, OpType type, Expression ret_type,
+ public Operator (DeclSpace parent, OpType type, Expression ret_type,
int mod_flags, Parameters parameters,
ToplevelBlock block, Attributes attrs, Location loc)
- : base (parent, ret_type, mod_flags, AllowedModifiers, false,
- new MemberName ("op_" + type), attrs, parameters, loc)
+ : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
+ new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
{
OperatorType = type;
Block = block;
public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
{
- OperatorMethod.ApplyAttributeBuilder (a, cb);
- }
-
- public override AttributeTargets AttributeTargets {
- get {
- return AttributeTargets.Method;
+ if (a.Type == TypeManager.conditional_attribute_type) {
+ Error_ConditionalAttributeIsNotValid ();
+ return;
}
+
+ base.ApplyAttributeBuilder (a, cb);
}
- protected override bool CheckForDuplications()
+ protected override bool CheckForDuplications ()
{
- ArrayList ar = Parent.Operators;
+ ArrayList ar = Parent.PartialContainer.Operators;
if (ar != null) {
int arLen = ar.Count;
}
}
- ar = Parent.Methods;
+ ar = Parent.PartialContainer.Methods;
if (ar != null) {
int arLen = ar.Count;
public override bool Define ()
{
-
const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
if ((ModFlags & RequiredModifiers) != RequiredModifiers){
- Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
+ Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
return false;
}
- if (!DoDefine ())
+ // imlicit and explicit operator of same types are not allowed
+ if (OperatorType == OpType.Explicit || OperatorType == OpType.Implicit)
+ MarkForDuplicationCheck ();
+
+ if (!base.Define ())
return false;
if (MemberType == TypeManager.void_type) {
return false;
}
- OperatorMethod = new Method (
- Parent, Type, ModFlags, false, MemberName,
- Parameters, OptAttributes, Location);
-
- OperatorMethod.Block = Block;
- OperatorMethod.IsOperator = true;
- OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
- OperatorMethod.Define ();
-
- if (OperatorMethod.MethodBuilder == null)
- return false;
-
- OperatorMethodBuilder = OperatorMethod.MethodBuilder;
-
- parameter_types = OperatorMethod.ParameterTypes;
- Type declaring_type = OperatorMethodBuilder.DeclaringType;
- Type return_type = OperatorMethod.ReturnType;
- Type first_arg_type = parameter_types [0];
-
- if (!CheckBase ())
- return false;
+ Type declaring_type = MethodData.DeclaringType;
+ Type return_type = MemberType;
+ Type first_arg_type = ParameterTypes [0];
// Rules for conversion operators
if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
if (first_arg_type == return_type && first_arg_type == declaring_type){
- Report.Error (
- 555, Location,
- "User-defined conversion cannot take an object of the " +
- "enclosing type and convert to an object of the enclosing" +
- " type");
+ Report.Error (555, Location,
+ "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
return false;
}
- if (first_arg_type != declaring_type && return_type != declaring_type){
+ if ((first_arg_type != declaring_type) && (return_type != declaring_type) &&
+ !TypeManager.IsNullableTypeOf (first_arg_type, declaring_type) &&
+ !TypeManager.IsNullableTypeOf (return_type, declaring_type)) {
Report.Error (
556, Location,
"User-defined conversion must convert to or from the " +
"enclosing type");
return false;
}
-
- if (first_arg_type == TypeManager.object_type ||
- return_type == TypeManager.object_type){
- Report.Error (
- -8, Location,
- "User-defined conversion cannot convert to or from " +
- "object type");
- return false;
- }
if (first_arg_type.IsInterface || return_type.IsInterface){
- Report.Error (
- 552, Location,
- "User-defined conversion cannot convert to or from an " +
- "interface type");
+ Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
+ GetSignatureForError ());
return false;
}
- if (first_arg_type.IsSubclassOf (return_type)
- || return_type.IsSubclassOf (first_arg_type)){
- if (declaring_type.IsSubclassOf (return_type)) {
- Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
+ if (first_arg_type.IsSubclassOf (return_type) || return_type.IsSubclassOf (first_arg_type)) {
+ if (declaring_type.IsSubclassOf (return_type) || declaring_type.IsSubclassOf (first_arg_type)) {
+ Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
+ GetSignatureForError ());
return false;
}
- Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
+ Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
+ GetSignatureForError ());
return false;
}
} else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
- if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
+ if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
Report.Error (564, Location, "Overloaded shift operator must have the type of the first operand be the containing type, and the type of the second operand must be int");
return false;
}
- } else if (Parameters.FixedParameters.Length == 1) {
+ } else if (Parameters.Count == 1) {
// Checks for Unary operators
if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
- if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
+ if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
Report.Error (448, Location,
"The return type for ++ or -- operator must be the containing type or derived from the containing type");
return false;
// Checks for Binary operators
if (first_arg_type != declaring_type &&
- parameter_types [1] != declaring_type){
+ ParameterTypes [1] != declaring_type){
Report.Error (
563, Location,
"One of the parameters of a binary operator must " +
return true;
}
+
+ protected override bool DoDefine ()
+ {
+ if (!base.DoDefine ())
+ return false;
+
+ flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
+ return true;
+ }
public override void Emit ()
{
+ base.Emit ();
+
+ Parameters.ApplyAttributes (MethodBuilder);
+
//
// abstract or extern methods have no bodies
//
if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
return;
- OperatorMethod.Emit ();
+ EmitContext ec;
+ if ((flags & MethodAttributes.PinvokeImpl) == 0)
+ ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
+ else
+ ec = CreateEmitContext (Parent, null);
+
+ SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
+ ec.EmitTopBlock (this, Block);
+
+ if (source != null)
+ source.CloseMethod ();
+
Block = null;
}
// Operator cannot be override
- protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
+ protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
{
return null;
}
}
}
- public override string GetSignatureForError (TypeContainer tc)
+ public static OpType GetOperatorType (string name)
{
- StringBuilder sb = new StringBuilder ();
- sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
- Parameters.FixedParameters [0].GetSignatureForError ());
-
- if (Parameters.FixedParameters.Length > 1) {
- sb.Append (",");
- sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
+ if (name.StartsWith ("op_")){
+ for (int i = 0; i < Unary.oper_names.Length; ++i) {
+ if (Unary.oper_names [i] == name)
+ return (OpType)i;
+ }
+
+ for (int i = 0; i < Binary.oper_names.Length; ++i) {
+ if (Binary.oper_names [i] == name)
+ return (OpType)i;
+ }
}
- sb.Append (")");
- return sb.ToString ();
+ return OpType.TOP;
}
public override string GetSignatureForError ()
{
- return ToString ();
- }
-
- public override bool MarkForDuplicationCheck ()
- {
- caching_flags |= Flags.TestMethodDuplication;
- return true;
- }
-
- public override string ToString ()
- {
- if (OperatorMethod == null)
- return Name;
-
- Type return_type = OperatorMethod.ReturnType;
- Type [] param_types = OperatorMethod.ParameterTypes;
-
- if (Parameters.FixedParameters.Length == 1)
- return String.Format (
- "{0} operator {1}({2})",
- TypeManager.CSharpName (return_type),
- GetName (OperatorType),
- param_types [0]);
- else
- return String.Format (
- "{0} operator {1}({2}, {3})",
- TypeManager.CSharpName (return_type),
- GetName (OperatorType),
- param_types [0], param_types [1]);
- }
-
- public override string[] ValidAttributeTargets {
- get {
- return attribute_targets;
+ StringBuilder sb = new StringBuilder ();
+ if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
+ sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
+ }
+ else {
+ sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
}
- }
- public void SetYields ()
- {
- ModFlags |= Modifiers.METHOD_YIELDS;
+ sb.Append (Parameters.GetSignatureForError ());
+ return sb.ToString ();
}
}
RetType = ret_type;
if (parameters == null)
- Parameters = TypeManager.NoTypes;
+ Parameters = Type.EmptyTypes;
else
Parameters = parameters;
}
Type [] args;
if (mi != null)
- args = TypeManager.GetArgumentTypes (mi);
+ args = TypeManager.GetParameterData (mi).Types;
else
args = TypeManager.GetArgumentTypes (pi);
Type [] sigp = sig.Parameters;