2
// method.cs: Method based declarations
4
// Authors: Miguel de Icaza (miguel@gnu.org)
5
// Martin Baulig (martin@ximian.com)
6
// Marek Safar (marek.safar@gmail.com)
8
// Dual licensed under the terms of the MIT X11 or GNU GPL
10
// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11
// Copyright 2004-2008 Novell, Inc
12
// Copyright 2011 Xamarin Inc.
16
using System.Collections.Generic;
17
using System.Security;
18
using System.Security.Permissions;
21
using Mono.CompilerServices.SymbolWriter;
22
using System.Runtime.CompilerServices;
25
using XmlElement = System.Object;
31
using MetaType = IKVM.Reflection.Type;
32
using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
33
using IKVM.Reflection;
34
using IKVM.Reflection.Emit;
36
using MetaType = System.Type;
37
using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
38
using System.Reflection;
39
using System.Reflection.Emit;
42
namespace Mono.CSharp {
44
public abstract class MethodCore : InterfaceMemberBase, IParametersMember
46
protected ParametersCompiled parameters;
47
protected ToplevelBlock block;
48
protected MethodSpec spec;
50
public MethodCore (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
51
MemberName name, Attributes attrs, ParametersCompiled parameters)
52
: base (parent, type, mod, allowed_mod, name, attrs)
54
this.parameters = parameters;
57
public override Variance ExpectedMemberTypeVariance {
59
return Variance.Covariant;
64
// Returns the System.Type array for the parameters of this method
66
public TypeSpec [] ParameterTypes {
68
return parameters.Types;
72
public ParametersCompiled ParameterInfo {
78
AParametersCollection IParametersMember.Parameters {
79
get { return parameters; }
82
public ToplevelBlock Block {
92
public CallingConventions CallingConventions {
94
CallingConventions cc = parameters.CallingConvention;
96
if ((ModFlags & Modifiers.STATIC) == 0)
97
cc |= CallingConventions.HasThis;
99
// FIXME: How is `ExplicitThis' used in C#?
105
protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
107
bool res = base.CheckOverrideAgainstBase (base_member);
110
// Check that the permissions are not being changed
112
if (!CheckAccessModifiers (this, base_member)) {
113
Error_CannotChangeAccessModifiers (this, base_member);
120
protected override bool CheckBase ()
122
// Check whether arguments were correct.
123
if (!DefineParameters (parameters))
126
return base.CheckBase ();
130
// Represents header string for documentation comment.
132
public override string DocCommentHeader
137
public override void Emit ()
139
if ((ModFlags & Modifiers.COMPILER_GENERATED) == 0) {
140
parameters.CheckConstraints (this);
146
public override bool EnableOverloadChecks (MemberCore overload)
148
if (overload is MethodCore) {
149
caching_flags |= Flags.MethodOverloadsExist;
153
if (overload is AbstractPropertyEventMethod)
156
return base.EnableOverloadChecks (overload);
159
public override string GetSignatureForDocumentation ()
161
string s = base.GetSignatureForDocumentation ();
162
if (MemberName.Arity > 0)
163
s += "``" + MemberName.Arity.ToString ();
165
return s + parameters.GetSignatureForDocumentation ();
168
public MethodSpec Spec {
172
protected override bool VerifyClsCompliance ()
174
if (!base.VerifyClsCompliance ())
177
if (parameters.HasArglist) {
178
Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
181
if (member_type != null && !member_type.IsCLSCompliant ()) {
182
Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
183
GetSignatureForError ());
186
parameters.VerifyClsCompliance (this);
191
public interface IGenericMethodDefinition : IMemberDefinition
193
TypeParameterSpec[] TypeParameters { get; }
194
int TypeParametersCount { get; }
196
// MethodInfo MakeGenericMethod (TypeSpec[] targs);
199
public sealed class MethodSpec : MemberSpec, IParametersMember
201
MethodBase metaInfo, inflatedMetaInfo;
202
AParametersCollection parameters;
206
TypeParameterSpec[] constraints;
208
public MethodSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition details, TypeSpec returnType,
209
MethodBase info, AParametersCollection parameters, Modifiers modifiers)
210
: base (kind, declaringType, details, modifiers)
212
this.metaInfo = info;
213
this.parameters = parameters;
214
this.returnType = returnType;
219
public override int Arity {
221
return IsGeneric ? GenericDefinition.TypeParametersCount : 0;
225
public TypeParameterSpec[] Constraints {
227
if (constraints == null && IsGeneric)
228
constraints = GenericDefinition.TypeParameters;
234
public bool IsConstructor {
236
return Kind == MemberKind.Constructor;
240
public IGenericMethodDefinition GenericDefinition {
242
return (IGenericMethodDefinition) definition;
246
public bool IsAsync {
248
return (Modifiers & Modifiers.ASYNC) != 0;
252
public bool IsExtensionMethod {
254
return IsStatic && parameters.HasExtensionMethodType;
258
public bool IsSealed {
260
return (Modifiers & Modifiers.SEALED) != 0;
264
// When is virtual or abstract
265
public bool IsVirtual {
267
return (Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) != 0;
271
public bool IsReservedMethod {
273
return Kind == MemberKind.Operator || IsAccessor;
277
TypeSpec IInterfaceMemberSpec.MemberType {
283
public AParametersCollection Parameters {
289
public TypeSpec ReturnType {
295
public TypeSpec[] TypeArguments {
303
public MethodSpec GetGenericMethodDefinition ()
305
if (!IsGeneric && !DeclaringType.IsGeneric)
308
return MemberCache.GetMember (declaringType, this);
311
public MethodBase GetMetaInfo ()
314
// inflatedMetaInfo is extra field needed for cases where we
315
// inflate method but another nested type can later inflate
316
// again (the cache would be build with inflated metaInfo) and
317
// TypeBuilder can work with method definitions only
319
if (inflatedMetaInfo == null) {
320
if ((state & StateFlags.PendingMetaInflate) != 0) {
321
var dt_meta = DeclaringType.GetMetaInfo ();
323
if (DeclaringType.IsTypeBuilder) {
325
inflatedMetaInfo = TypeBuilder.GetConstructor (dt_meta, (ConstructorInfo) metaInfo);
327
inflatedMetaInfo = TypeBuilder.GetMethod (dt_meta, (MethodInfo) metaInfo);
330
// it should not be reached
331
throw new NotImplementedException ();
333
inflatedMetaInfo = MethodInfo.GetMethodFromHandle (metaInfo.MethodHandle, dt_meta.TypeHandle);
337
state &= ~StateFlags.PendingMetaInflate;
339
inflatedMetaInfo = metaInfo;
343
if ((state & StateFlags.PendingMakeMethod) != 0) {
344
var sre_targs = new MetaType[targs.Length];
345
for (int i = 0; i < sre_targs.Length; ++i)
346
sre_targs[i] = targs[i].GetMetaInfo ();
348
inflatedMetaInfo = ((MethodInfo) inflatedMetaInfo).MakeGenericMethod (sre_targs);
349
state &= ~StateFlags.PendingMakeMethod;
352
return inflatedMetaInfo;
355
public override string GetSignatureForDocumentation ()
359
case MemberKind.Constructor:
362
case MemberKind.Method:
364
name = Name + "``" + Arity.ToString ();
374
name = DeclaringType.GetSignatureForDocumentation () + "." + name + parameters.GetSignatureForDocumentation ();
375
if (Kind == MemberKind.Operator) {
376
var op = Operator.GetType (Name).Value;
377
if (op == Operator.OpType.Explicit || op == Operator.OpType.Implicit) {
378
name += "~" + ReturnType.GetSignatureForDocumentation ();
385
public override string GetSignatureForError ()
389
name = DeclaringType.GetSignatureForError () + "." + DeclaringType.Name;
390
} else if (Kind == MemberKind.Operator) {
391
var op = Operator.GetType (Name).Value;
392
if (op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) {
393
name = DeclaringType.GetSignatureForError () + "." + Operator.GetName (op) + " operator " + returnType.GetSignatureForError ();
395
name = DeclaringType.GetSignatureForError () + ".operator " + Operator.GetName (op);
397
} else if (IsAccessor) {
398
int split = Name.IndexOf ('_');
399
name = Name.Substring (split + 1);
400
var postfix = Name.Substring (0, split);
402
var pc = parameters.Count;
403
if (pc > 0 && postfix == "get") {
404
name = "this" + parameters.GetSignatureForError ("[", "]", pc);
405
} else if (pc > 1 && postfix == "set") {
406
name = "this" + parameters.GetSignatureForError ("[", "]", pc - 1);
410
return DeclaringType.GetSignatureForError () + "." + name + "." + postfix;
412
name = base.GetSignatureForError ();
414
name += "<" + TypeManager.CSharpName (targs) + ">";
416
name += "<" + TypeManager.CSharpName (GenericDefinition.TypeParameters) + ">";
419
return name + parameters.GetSignatureForError ();
422
public override MemberSpec InflateMember (TypeParameterInflator inflator)
424
var ms = (MethodSpec) base.InflateMember (inflator);
425
ms.inflatedMetaInfo = null;
426
ms.returnType = inflator.Inflate (returnType);
427
ms.parameters = parameters.Inflate (inflator);
429
ms.constraints = TypeParameterSpec.InflateConstraints (inflator, Constraints);
434
public MethodSpec MakeGenericMethod (IMemberContext context, params TypeSpec[] targs)
437
throw new ArgumentNullException ();
439
// if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
442
//if (generic_intances == null)
443
// generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
445
var inflator = new TypeParameterInflator (context, DeclaringType, GenericDefinition.TypeParameters, targs);
447
var inflated = (MethodSpec) MemberwiseClone ();
448
inflated.declaringType = inflator.TypeInstance;
449
inflated.returnType = inflator.Inflate (returnType);
450
inflated.parameters = parameters.Inflate (inflator);
451
inflated.targs = targs;
452
inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
453
inflated.state |= StateFlags.PendingMakeMethod;
455
// if (inflated.parent == null)
456
// inflated.parent = parent;
458
//generic_intances.Add (targs, inflated);
462
public MethodSpec Mutate (TypeParameterMutator mutator)
464
var targs = TypeArguments;
466
targs = mutator.Mutate (targs);
468
var decl = DeclaringType;
469
if (DeclaringType.IsGenericOrParentIsGeneric) {
470
decl = mutator.Mutate (decl);
473
if (targs == TypeArguments && decl == DeclaringType)
476
var ms = (MethodSpec) MemberwiseClone ();
477
if (decl != DeclaringType) {
478
ms.inflatedMetaInfo = null;
479
ms.declaringType = decl;
480
ms.state |= StateFlags.PendingMetaInflate;
485
ms.state |= StateFlags.PendingMakeMethod;
491
public override List<TypeSpec> ResolveMissingDependencies ()
493
var missing = returnType.ResolveMissingDependencies ();
494
foreach (var pt in parameters.Types) {
495
var m = pt.GetMissingDependencies ();
500
missing = new List<TypeSpec> ();
502
missing.AddRange (m);
506
foreach (var tp in GenericDefinition.TypeParameters) {
507
var m = tp.GetMissingDependencies ();
513
missing = new List<TypeSpec> ();
515
missing.AddRange (m);
522
public void SetMetaInfo (MethodInfo info)
524
if (this.metaInfo != null)
525
throw new InternalErrorException ("MetaInfo reset");
527
this.metaInfo = info;
531
public abstract class MethodOrOperator : MethodCore, IMethodData
533
public MethodBuilder MethodBuilder;
534
ReturnParameter return_attributes;
535
SecurityType declarative_security;
536
protected MethodData MethodData;
538
static readonly string[] attribute_targets = new string [] { "method", "return" };
540
protected MethodOrOperator (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name,
541
Attributes attrs, ParametersCompiled parameters)
542
: base (parent, type, mod, allowed_mod, name, attrs, parameters)
546
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
548
if (a.Target == AttributeTargets.ReturnValue) {
549
if (return_attributes == null)
550
return_attributes = new ReturnParameter (this, MethodBuilder, Location);
552
return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
556
if (a.Type == pa.MethodImpl) {
557
if ((ModFlags & Modifiers.ASYNC) != 0 && (a.GetMethodImplOptions () & MethodImplOptions.Synchronized) != 0) {
558
Report.Error (4015, a.Location, "`{0}': Async methods cannot use `MethodImplOptions.Synchronized'",
559
GetSignatureForError ());
562
is_external_implementation = a.IsInternalCall ();
563
} else if (a.Type == pa.DllImport) {
564
const Modifiers extern_static = Modifiers.EXTERN | Modifiers.STATIC;
565
if ((ModFlags & extern_static) != extern_static) {
566
Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
568
is_external_implementation = true;
571
if (a.IsValidSecurityAttribute ()) {
572
a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
576
if (MethodBuilder != null)
577
MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
580
public override AttributeTargets AttributeTargets {
582
return AttributeTargets.Method;
586
protected override bool CheckForDuplications ()
588
return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
591
public virtual EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
593
return new EmitContext (this, ig, MemberType, sourceMethod);
596
public override bool Define ()
605
if (this is Operator)
606
kind = MemberKind.Operator;
607
else if (this is Destructor)
608
kind = MemberKind.Destructor;
610
kind = MemberKind.Method;
612
if (IsPartialDefinition) {
613
caching_flags &= ~Flags.Excluded_Undetected;
614
caching_flags |= Flags.Excluded;
616
// Add to member cache only when a partial method implementation has not been found yet
617
if ((caching_flags & Flags.PartialDefinitionExists) == 0) {
618
// MethodBase mb = new PartialMethodDefinitionInfo (this);
620
spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, null, parameters, ModFlags);
621
if (MemberName.Arity > 0) {
622
spec.IsGeneric = true;
624
// TODO: Have to move DefineMethod after Define (ideally to Emit)
625
throw new NotImplementedException ("Generic partial methods");
628
Parent.MemberCache.AddMember (spec);
634
MethodData = new MethodData (
635
this, ModFlags, flags, this, MethodBuilder, base_method);
637
if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
640
MethodBuilder = MethodData.MethodBuilder;
642
spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, MethodBuilder, parameters, ModFlags);
643
if (MemberName.Arity > 0)
644
spec.IsGeneric = true;
646
Parent.MemberCache.AddMember (this, MethodBuilder.Name, spec);
651
protected override void DoMemberTypeIndependentChecks ()
653
base.DoMemberTypeIndependentChecks ();
655
CheckAbstractAndExtern (block != null);
657
if ((ModFlags & Modifiers.PARTIAL) != 0) {
658
for (int i = 0; i < parameters.Count; ++i) {
659
IParameterData p = parameters.FixedParameters [i];
660
if ((p.ModFlags & Parameter.Modifier.OUT) != 0) {
661
Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
662
GetSignatureForError ());
665
if (p.HasDefaultValue && IsPartialImplementation)
666
((Parameter) p).Warning_UselessOptionalParameter (Report);
671
protected override void DoMemberTypeDependentChecks ()
673
base.DoMemberTypeDependentChecks ();
675
if (MemberType.IsStatic) {
676
Error_StaticReturnType ();
680
public override void Emit ()
682
if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
683
Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (MethodBuilder);
684
if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
685
Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (MethodBuilder);
687
if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
688
return_attributes = new ReturnParameter (this, MethodBuilder, Location);
689
Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
690
} else if (ReturnType.HasDynamicElement) {
691
return_attributes = new ReturnParameter (this, MethodBuilder, Location);
692
Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
695
if (OptAttributes != null)
696
OptAttributes.Emit ();
698
if (declarative_security != null) {
699
foreach (var de in declarative_security) {
701
MethodBuilder.__AddDeclarativeSecurity (de);
703
MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
708
if (type_expr != null)
709
ConstraintChecker.Check (this, member_type, type_expr.Location);
713
if (MethodData != null)
714
MethodData.Emit (Parent);
719
protected void Error_ConditionalAttributeIsNotValid ()
721
Report.Error (577, Location,
722
"Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
723
GetSignatureForError ());
726
public bool IsPartialDefinition {
728
return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
732
public bool IsPartialImplementation {
734
return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
738
public override string[] ValidAttributeTargets {
740
return attribute_targets;
744
#region IMethodData Members
746
bool IMethodData.IsAccessor {
752
public TypeSpec ReturnType {
758
public MemberName MethodName {
765
/// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
767
public override string[] ConditionalConditions ()
769
if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
772
if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
773
return new string [0];
775
caching_flags &= ~Flags.Excluded_Undetected;
778
if (base_method == null) {
779
if (OptAttributes == null)
782
Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
786
conditions = new string[attrs.Length];
787
for (int i = 0; i < conditions.Length; ++i)
788
conditions[i] = attrs[i].GetConditionalAttributeValue ();
790
conditions = base_method.MemberDefinition.ConditionalConditions();
793
if (conditions != null)
794
caching_flags |= Flags.Excluded;
801
public override void WriteDebugSymbol (MonoSymbolFile file)
803
if (MethodData != null)
804
MethodData.WriteDebugSymbol (file);
808
public class Method : MethodOrOperator, IGenericMethodDefinition
810
Method partialMethodImplementation;
812
public Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, MemberName name, ParametersCompiled parameters, Attributes attrs)
813
: base (parent, return_type, mod,
814
parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
815
parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct | Modifiers.ASYNC :
816
AllowedModifiersClass | Modifiers.ASYNC,
817
name, attrs, parameters)
821
protected Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
822
MemberName name, ParametersCompiled parameters, Attributes attrs)
823
: base (parent, return_type, mod, amod, name, attrs, parameters)
829
public override TypeParameters CurrentTypeParameters {
831
return MemberName.TypeParameters;
835
public TypeParameterSpec[] TypeParameters {
837
return CurrentTypeParameters.Types;
841
public int TypeParametersCount {
843
return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Count;
849
public override void Accept (StructuralVisitor visitor)
851
visitor.Visit (this);
854
public static Method Create (TypeDefinition parent, FullNamedExpression returnType, Modifiers mod,
855
MemberName name, ParametersCompiled parameters, Attributes attrs)
857
var m = new Method (parent, returnType, mod, name, parameters, attrs);
859
if ((mod & Modifiers.PARTIAL) != 0) {
860
const Modifiers invalid_partial_mod = Modifiers.AccessibilityMask | Modifiers.ABSTRACT | Modifiers.EXTERN |
861
Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.SEALED | Modifiers.VIRTUAL;
863
if ((mod & invalid_partial_mod) != 0) {
864
m.Report.Error (750, m.Location,
865
"A partial method cannot define access modifier or any of abstract, extern, new, override, sealed, or virtual modifiers");
866
mod &= ~invalid_partial_mod;
869
if ((parent.ModFlags & Modifiers.PARTIAL) == 0) {
870
m.Report.Error (751, m.Location,
871
"A partial method must be declared within a partial class or partial struct");
875
if ((mod & Modifiers.STATIC) == 0 && parameters.HasExtensionMethodType) {
876
m.Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static",
877
m.GetSignatureForError ());
884
public override string GetSignatureForError()
886
return base.GetSignatureForError () + parameters.GetSignatureForError ();
889
void Error_DuplicateEntryPoint (Method b)
891
Report.Error (17, b.Location,
892
"Program `{0}' has more than one entry point defined: `{1}'",
893
b.Module.Builder.ScopeName, b.GetSignatureForError ());
898
if (ReturnType.Kind != MemberKind.Void && ReturnType.BuiltinType != BuiltinTypeSpec.Type.Int)
901
if (parameters.IsEmpty)
904
if (parameters.Count > 1)
907
var ac = parameters.Types [0] as ArrayContainer;
908
return ac != null && ac.Rank == 1 && ac.Element.BuiltinType == BuiltinTypeSpec.Type.String &&
909
(parameters[0].ModFlags & Parameter.Modifier.RefOutMask) == 0;
912
public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
915
var tp = CurrentTypeParameters;
917
TypeParameter t = tp.Find (name);
919
return new TypeParameterExpr (t, loc);
923
return base.LookupNamespaceOrType (name, arity, mode, loc);
926
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
928
if (a.Type == pa.Conditional) {
929
if (IsExplicitImpl) {
930
Error_ConditionalAttributeIsNotValid ();
934
if ((ModFlags & Modifiers.OVERRIDE) != 0) {
935
Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
939
if (ReturnType.Kind != MemberKind.Void) {
940
Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
945
Report.Error (582, Location, "Conditional not valid on interface members");
949
if (MethodData.implementing != null) {
950
Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
951
Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
952
GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
956
for (int i = 0; i < parameters.Count; ++i) {
957
if ((parameters.FixedParameters [i].ModFlags & Parameter.Modifier.OUT) != 0) {
958
Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
964
if (a.Type == pa.Extension) {
965
a.Error_MisusedExtensionAttribute ();
969
base.ApplyAttributeBuilder (a, ctor, cdata, pa);
972
void CreateTypeParameters ()
974
var tparams = MemberName.TypeParameters;
975
string[] snames = new string[MemberName.Arity];
976
var parent_tparams = Parent.TypeParametersAll;
978
for (int i = 0; i < snames.Length; i++) {
979
string type_argument_name = tparams[i].MemberName.Name;
982
int idx = parameters.GetParameterIndexByName (type_argument_name);
986
b = new ToplevelBlock (Compiler, Location);
988
b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
991
INamedBlockVariable variable = null;
992
block.GetLocalName (type_argument_name, block, ref variable);
993
if (variable != null)
994
variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
997
if (parent_tparams != null) {
998
var tp = parent_tparams.Find (type_argument_name);
1000
tparams[i].WarningParentNameConflict (tp);
1004
snames[i] = type_argument_name;
1007
GenericTypeParameterBuilder[] gen_params = MethodBuilder.DefineGenericParameters (snames);
1008
tparams.Define (gen_params, null, 0, Parent);
1011
protected virtual void DefineTypeParameters ()
1013
var tparams = CurrentTypeParameters;
1015
TypeParameterSpec[] base_tparams = null;
1016
TypeParameterSpec[] base_decl_tparams = TypeParameterSpec.EmptyTypes;
1017
TypeSpec[] base_targs = TypeSpec.EmptyTypes;
1018
if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
1019
MethodSpec base_override = base_method ?? MethodData.implementing;
1021
if (base_override != null) {
1022
base_tparams = base_override.GenericDefinition.TypeParameters;
1024
if (base_override.DeclaringType.IsGeneric) {
1025
base_decl_tparams = base_override.DeclaringType.MemberDefinition.TypeParameters;
1027
if (base_method != null) {
1028
var base_type_parent = CurrentType;
1029
while (base_type_parent.BaseType != base_override.DeclaringType) {
1030
base_type_parent = base_type_parent.BaseType;
1033
base_targs = base_type_parent.BaseType.TypeArguments;
1035
foreach (var iface in Parent.CurrentType.Interfaces) {
1036
if (iface == base_override.DeclaringType) {
1037
base_targs = iface.TypeArguments;
1044
if (base_override.IsGeneric) {
1045
ObsoleteAttribute oa;
1046
foreach (var base_tp in base_tparams) {
1047
oa = base_tp.BaseType.GetAttributeObsolete ();
1049
AttributeTester.Report_ObsoleteMessage (oa, base_tp.BaseType.GetSignatureForError (), Location, Report);
1052
if (base_tp.InterfacesDefined != null) {
1053
foreach (var iface in base_tp.InterfacesDefined) {
1054
oa = iface.GetAttributeObsolete ();
1056
AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1062
if (base_decl_tparams.Length != 0) {
1063
base_decl_tparams = base_decl_tparams.Concat (base_tparams).ToArray ();
1064
base_targs = base_targs.Concat (tparams.Types).ToArray ();
1066
base_decl_tparams = base_tparams;
1067
base_targs = tparams.Types;
1073
for (int i = 0; i < tparams.Count; ++i) {
1074
var tp = tparams[i];
1076
if (!tp.ResolveConstraints (this))
1080
// Copy base constraints for override/explicit methods
1082
if (base_tparams != null) {
1083
var base_tparam = base_tparams[i];
1084
var local_tparam = tp.Type;
1085
local_tparam.SpecialConstraint = base_tparam.SpecialConstraint;
1087
var inflator = new TypeParameterInflator (this, CurrentType, base_decl_tparams, base_targs);
1088
base_tparam.InflateConstraints (inflator, local_tparam);
1091
// Check all type argument constraints for possible collision or unification
1092
// introduced by inflating inherited constraints in this context
1094
// Conflict example:
1096
// class A<T> { virtual void Foo<U> () where U : class, T {} }
1097
// class B : A<int> { override void Foo<U> {} }
1099
var local_tparam_targs = local_tparam.TypeArguments;
1100
if (local_tparam_targs != null) {
1101
for (int ii = 0; ii < local_tparam_targs.Length; ++ii) {
1102
var ta = local_tparam_targs [ii];
1103
if (!ta.IsClass && !ta.IsStruct)
1106
TypeSpec[] unique_tparams = null;
1107
for (int iii = ii + 1; iii < local_tparam_targs.Length; ++iii) {
1109
// Remove any identical or unified constraint types
1111
var tparam_checked = local_tparam_targs[iii];
1112
if (TypeSpecComparer.IsEqual (ta, tparam_checked) || TypeSpec.IsBaseClass (ta, tparam_checked, false)) {
1113
unique_tparams = new TypeSpec[local_tparam_targs.Length - 1];
1114
Array.Copy (local_tparam_targs, 0, unique_tparams, 0, iii);
1115
Array.Copy (local_tparam_targs, iii + 1, unique_tparams, iii, local_tparam_targs.Length - iii - 1);
1116
} else if (!TypeSpec.IsBaseClass (tparam_checked, ta, false)) {
1117
Constraints.Error_ConflictingConstraints (this, local_tparam, ta, tparam_checked, Location);
1121
if (unique_tparams != null) {
1122
local_tparam_targs = unique_tparams;
1123
local_tparam.TypeArguments = local_tparam_targs;
1127
Constraints.CheckConflictingInheritedConstraint (local_tparam, ta, this, Location);
1133
if (base_tparams == null && MethodData != null && MethodData.implementing != null) {
1134
CheckImplementingMethodConstraints (Parent, spec, MethodData.implementing);
1138
public static bool CheckImplementingMethodConstraints (TypeContainer container, MethodSpec method, MethodSpec baseMethod)
1140
var tparams = method.Constraints;
1141
var base_tparams = baseMethod.Constraints;
1142
for (int i = 0; i < tparams.Length; ++i) {
1143
if (!tparams[i].HasSameConstraintsImplementation (base_tparams[i])) {
1144
container.Compiler.Report.SymbolRelatedToPreviousError (method);
1145
container.Compiler.Report.SymbolRelatedToPreviousError (baseMethod);
1147
// Using container location because the interface can be implemented
1149
container.Compiler.Report.Error (425, container.Location,
1150
"The constraints for type parameter `{0}' of method `{1}' must match the constraints for type parameter `{2}' of interface method `{3}'. Consider using an explicit interface implementation instead",
1151
tparams[i].GetSignatureForError (), method.GetSignatureForError (),
1152
base_tparams[i].GetSignatureForError (), baseMethod.GetSignatureForError ());
1164
public override bool Define ()
1166
if (!base.Define ())
1169
if (member_type.Kind == MemberKind.Void && parameters.IsEmpty && MemberName.Arity == 0 && MemberName.Name == Destructor.MetadataName) {
1170
Report.Warning (465, 1, Location,
1171
"Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
1174
if (partialMethodImplementation != null && IsPartialDefinition)
1175
MethodBuilder = partialMethodImplementation.MethodBuilder;
1177
if (Compiler.Settings.StdLib && ReturnType.IsSpecialRuntimeType) {
1178
Error1599 (Location, ReturnType, Report);
1182
if (CurrentTypeParameters == null) {
1183
if (base_method != null && !IsExplicitImpl) {
1184
if (parameters.Count == 1 && ParameterTypes[0].BuiltinType == BuiltinTypeSpec.Type.Object && MemberName.Name == "Equals")
1185
Parent.PartialContainer.Mark_HasEquals ();
1186
else if (parameters.IsEmpty && MemberName.Name == "GetHashCode")
1187
Parent.PartialContainer.Mark_HasGetHashCode ();
1191
DefineTypeParameters ();
1194
if (block != null) {
1195
if (block.IsIterator) {
1197
// Current method is turned into automatically generated
1198
// wrapper which creates an instance of iterator
1200
Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1201
ModFlags |= Modifiers.DEBUGGER_HIDDEN;
1204
if ((ModFlags & Modifiers.ASYNC) != 0) {
1205
if (ReturnType.Kind != MemberKind.Void &&
1206
ReturnType != Module.PredefinedTypes.Task.TypeSpec &&
1207
!ReturnType.IsGenericTask) {
1208
Report.Error (1983, Location, "The return type of an async method must be void, Task, or Task<T>");
1211
block = (ToplevelBlock) block.ConvertToAsyncTask (this, Parent.PartialContainer, parameters, ReturnType, Location);
1212
ModFlags |= Modifiers.DEBUGGER_HIDDEN;
1215
if (Compiler.Settings.WriteMetadataOnly)
1219
if ((ModFlags & Modifiers.STATIC) == 0)
1222
if (parameters.HasExtensionMethodType) {
1223
if (Parent.PartialContainer.IsStatic && !Parent.IsGenericOrParentIsGeneric) {
1224
if (!Parent.IsTopLevel)
1225
Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
1226
GetSignatureForError ());
1228
PredefinedAttribute pa = Module.PredefinedAttributes.Extension;
1229
if (!pa.IsDefined) {
1230
Report.Error (1110, Location,
1231
"`{0}': Extension methods require `System.Runtime.CompilerServices.ExtensionAttribute' type to be available. Are you missing an assembly reference?",
1232
GetSignatureForError ());
1235
ModFlags |= Modifiers.METHOD_EXTENSION;
1236
Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
1237
Spec.DeclaringType.SetExtensionMethodContainer ();
1238
Parent.Module.HasExtensionMethod = true;
1240
Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
1241
GetSignatureForError ());
1246
// This is used to track the Entry Point,
1248
var settings = Compiler.Settings;
1249
if (settings.NeedsEntryPoint && MemberName.Name == "Main" && (settings.MainClass == null || settings.MainClass == Parent.TypeBuilder.FullName)) {
1250
if (IsEntryPoint ()) {
1251
if (Parent.DeclaringAssembly.EntryPoint == null) {
1252
if (Parent.IsGenericOrParentIsGeneric || MemberName.IsGeneric) {
1253
Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
1254
GetSignatureForError ());
1255
} else if ((ModFlags & Modifiers.ASYNC) != 0) {
1256
Report.Error (4009, Location, "`{0}': an entry point cannot be async method",
1257
GetSignatureForError ());
1260
Parent.DeclaringAssembly.EntryPoint = this;
1263
Error_DuplicateEntryPoint (Parent.DeclaringAssembly.EntryPoint);
1264
Error_DuplicateEntryPoint (this);
1267
Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
1268
GetSignatureForError ());
1278
public override void Emit ()
1281
if (IsPartialDefinition) {
1283
// Use partial method implementation builder for partial method declaration attributes
1285
if (partialMethodImplementation != null) {
1286
MethodBuilder = partialMethodImplementation.MethodBuilder;
1292
if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
1293
Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
1294
GetSignatureForError ());
1297
if (CurrentTypeParameters != null) {
1298
for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1299
var tp = CurrentTypeParameters [i];
1300
tp.CheckGenericConstraints (false);
1305
if (block != null && block.StateMachine is AsyncTaskStorey) {
1306
var psm = Module.PredefinedAttributes.AsyncStateMachine;
1308
psm.EmitAttribute (MethodBuilder, block.StateMachine);
1311
if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
1312
Module.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
1316
Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
1317
Location, MethodBuilder);
1322
public override bool EnableOverloadChecks (MemberCore overload)
1324
if (overload is Indexer)
1327
return base.EnableOverloadChecks (overload);
1330
public static void Error1599 (Location loc, TypeSpec t, Report Report)
1332
Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
1335
protected override bool ResolveMemberType ()
1337
if (CurrentTypeParameters != null) {
1338
MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
1339
CreateTypeParameters ();
1342
return base.ResolveMemberType ();
1345
public void SetPartialDefinition (Method methodDefinition)
1347
caching_flags |= Flags.PartialDefinitionExists;
1348
methodDefinition.partialMethodImplementation = this;
1350
// Ensure we are always using method declaration parameters
1351
for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
1352
parameters [i].Name = methodDefinition.parameters [i].Name;
1353
parameters [i].DefaultValue = methodDefinition.parameters [i].DefaultValue;
1356
if (methodDefinition.attributes == null)
1359
if (attributes == null) {
1360
attributes = methodDefinition.attributes;
1362
attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
1367
public abstract class ConstructorInitializer : ExpressionStatement
1369
Arguments argument_list;
1370
MethodSpec base_ctor;
1372
public ConstructorInitializer (Arguments argument_list, Location loc)
1374
this.argument_list = argument_list;
1378
public Arguments Arguments {
1380
return argument_list;
1384
public override bool ContainsEmitWithAwait ()
1386
throw new NotSupportedException ();
1389
public override Expression CreateExpressionTree (ResolveContext ec)
1391
throw new NotSupportedException ("ET");
1394
protected override Expression DoResolve (ResolveContext ec)
1396
eclass = ExprClass.Value;
1399
var caller_builder = (Constructor) ec.MemberContext;
1402
// Spec mandates that constructor initializer will not have `this' access
1404
using (ec.Set (ResolveContext.Options.BaseInitializer)) {
1405
if (argument_list != null) {
1407
argument_list.Resolve (ec, out dynamic);
1410
ec.Report.Error (1975, loc,
1411
"The constructor call cannot be dynamically dispatched within constructor initializer");
1417
type = ec.CurrentType;
1418
if (this is ConstructorBaseInitializer) {
1419
if (ec.CurrentType.BaseType == null)
1422
type = ec.CurrentType.BaseType;
1423
if (ec.CurrentType.IsStruct) {
1424
ec.Report.Error (522, loc,
1425
"`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
1430
// It is legal to have "this" initializers that take no arguments
1431
// in structs, they are just no-ops.
1433
// struct D { public D (int a) : this () {}
1435
if (ec.CurrentType.IsStruct && argument_list == null)
1439
base_ctor = ConstructorLookup (ec, type, ref argument_list, loc);
1442
if (base_ctor != null && base_ctor.MemberDefinition == caller_builder.Spec.MemberDefinition) {
1443
ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
1444
caller_builder.GetSignatureForError ());
1450
public override void Emit (EmitContext ec)
1452
// It can be null for static initializers
1453
if (base_ctor == null)
1456
var call = new CallEmitter ();
1457
call.InstanceExpression = new CompilerGeneratedThis (type, loc);
1458
call.EmitPredefined (ec, base_ctor, argument_list);
1461
public override void EmitStatement (EmitContext ec)
1467
public class ConstructorBaseInitializer : ConstructorInitializer {
1468
public ConstructorBaseInitializer (Arguments argument_list, Location l) :
1469
base (argument_list, l)
1474
class GeneratedBaseInitializer: ConstructorBaseInitializer {
1475
public GeneratedBaseInitializer (Location loc):
1481
public class ConstructorThisInitializer : ConstructorInitializer {
1482
public ConstructorThisInitializer (Arguments argument_list, Location l) :
1483
base (argument_list, l)
1488
public class Constructor : MethodCore, IMethodData
1490
public ConstructorBuilder ConstructorBuilder;
1491
public ConstructorInitializer Initializer;
1492
SecurityType declarative_security;
1493
bool has_compliant_args;
1494
SourceMethodBuilder debug_builder;
1497
// Modifiers allowed for a constructor.
1499
public const Modifiers AllowedModifiers =
1501
Modifiers.PROTECTED |
1502
Modifiers.INTERNAL |
1508
static readonly string[] attribute_targets = new string [] { "method" };
1510
public static readonly string ConstructorName = ".ctor";
1511
public static readonly string TypeConstructorName = ".cctor";
1513
public Constructor (TypeDefinition parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args, Location loc)
1514
: base (parent, null, mod, AllowedModifiers, new MemberName (name, loc), attrs, args)
1518
public bool HasCompliantArgs {
1520
return has_compliant_args;
1524
public override AttributeTargets AttributeTargets {
1526
return AttributeTargets.Constructor;
1530
bool IMethodData.IsAccessor {
1537
// Returns true if this is a default constructor
1539
public bool IsDefault ()
1541
if ((ModFlags & Modifiers.STATIC) != 0)
1542
return parameters.IsEmpty;
1544
return parameters.IsEmpty &&
1545
(Initializer is ConstructorBaseInitializer) &&
1546
(Initializer.Arguments == null);
1549
public override void Accept (StructuralVisitor visitor)
1551
visitor.Visit (this);
1554
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1556
if (a.IsValidSecurityAttribute ()) {
1557
a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
1561
if (a.Type == pa.MethodImpl) {
1562
is_external_implementation = a.IsInternalCall ();
1565
ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1568
protected override bool CheckBase ()
1570
if ((ModFlags & Modifiers.STATIC) != 0) {
1571
if (!parameters.IsEmpty) {
1572
Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
1573
GetSignatureForError ());
1577
if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1578
Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1580
// the rest can be ignored
1584
// Check whether arguments were correct.
1585
if (!DefineParameters (parameters))
1588
if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1589
Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1591
if (Parent.PartialContainer.Kind == MemberKind.Struct && parameters.IsEmpty) {
1592
Report.Error (568, Location,
1593
"Structs cannot contain explicit parameterless constructors");
1597
CheckProtectedModifier ();
1603
// Creates the ConstructorBuilder
1605
public override bool Define ()
1607
if (ConstructorBuilder != null)
1610
if (!CheckAbstractAndExtern (block != null))
1613
// Check if arguments were correct.
1617
var ca = ModifiersExtensions.MethodAttr (ModFlags) | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
1619
ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
1620
ca, CallingConventions,
1621
parameters.GetMetaInfo ());
1623
spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, Compiler.BuiltinTypes.Void, ConstructorBuilder, parameters, ModFlags);
1625
Parent.MemberCache.AddMember (spec);
1627
if (block != null) {
1628
// It's here only to report an error
1629
if (block.IsIterator) {
1630
member_type = Compiler.BuiltinTypes.Void;
1631
Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1634
if (Compiler.Settings.WriteMetadataOnly)
1644
public override void Emit ()
1646
if (Parent.PartialContainer.IsComImport) {
1647
if (!IsDefault ()) {
1648
Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
1649
Parent.GetSignatureForError ());
1652
// Set as internal implementation and reset block data
1653
// to ensure no IL is generated
1654
ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
1658
if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
1659
Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (ConstructorBuilder);
1661
if (OptAttributes != null)
1662
OptAttributes.Emit ();
1665
parameters.ApplyAttributes (this, ConstructorBuilder);
1668
BlockContext bc = new BlockContext (this, block, Compiler.BuiltinTypes.Void);
1669
bc.Set (ResolveContext.Options.ConstructorScope);
1671
if (block != null) {
1673
// If we use a "this (...)" constructor initializer, then
1674
// do not emit field initializers, they are initialized in the other constructor
1676
if (!(Initializer is ConstructorThisInitializer))
1677
Parent.PartialContainer.ResolveFieldInitializers (bc);
1680
if (Initializer == null) {
1681
if (Parent.PartialContainer.Kind == MemberKind.Struct) {
1683
// If this is a non-static `struct' constructor and doesn't have any
1684
// initializer, it must initialize all of the struct's fields.
1686
block.AddThisVariable (bc);
1687
} else if (Parent.PartialContainer.Kind == MemberKind.Class) {
1688
Initializer = new GeneratedBaseInitializer (Location);
1692
if (Initializer != null) {
1694
// mdb format does not support reqions. Try to workaround this by emitting the
1695
// sequence point at initializer. Any breakpoint at constructor header should
1696
// be adjusted to this sequence point as it's the next one which follows.
1698
block.AddScopeStatement (new StatementExpression (Initializer));
1702
if (block.Resolve (null, bc, this)) {
1703
debug_builder = Parent.CreateMethodSymbolEntry ();
1704
EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType, debug_builder);
1705
ec.With (EmitContext.Options.ConstructorScope, true);
1711
if (declarative_security != null) {
1712
foreach (var de in declarative_security) {
1714
ConstructorBuilder.__AddDeclarativeSecurity (de);
1716
ConstructorBuilder.AddDeclarativeSecurity (de.Key, de.Value);
1724
protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
1726
// Is never override
1727
bestCandidate = null;
1731
public override string GetCallerMemberName ()
1733
return IsStatic ? TypeConstructorName : ConstructorName;
1736
public override string GetSignatureForDocumentation ()
1738
return Parent.GetSignatureForDocumentation () + ".#ctor" + parameters.GetSignatureForDocumentation ();
1741
public override string GetSignatureForError()
1743
return base.GetSignatureForError () + parameters.GetSignatureForError ();
1746
public override string[] ValidAttributeTargets {
1748
return attribute_targets;
1752
protected override bool VerifyClsCompliance ()
1754
if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
1758
if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
1759
foreach (TypeSpec param in parameters.Types) {
1760
if (param.IsArray) {
1766
has_compliant_args = true;
1770
public override void WriteDebugSymbol (MonoSymbolFile file)
1772
if (debug_builder == null)
1775
var token = ConstructorBuilder.GetToken ();
1776
int t = token.Token;
1778
if (ModuleBuilder.IsPseudoToken (t))
1779
t = Module.Builder.ResolvePseudoToken (t);
1782
debug_builder.DefineMethod (file, t);
1785
#region IMethodData Members
1787
public MemberName MethodName {
1793
public TypeSpec ReturnType {
1799
EmitContext IMethodData.CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
1801
throw new NotImplementedException ();
1808
/// Interface for MethodData class. Holds links to parent members to avoid member duplication.
1810
public interface IMethodData : IMemberContext
1812
CallingConventions CallingConventions { get; }
1813
Location Location { get; }
1814
MemberName MethodName { get; }
1815
TypeSpec ReturnType { get; }
1816
ParametersCompiled ParameterInfo { get; }
1817
MethodSpec Spec { get; }
1818
bool IsAccessor { get; }
1820
Attributes OptAttributes { get; }
1821
ToplevelBlock Block { get; set; }
1823
EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod);
1827
// Encapsulates most of the Method's state
1829
public class MethodData
1832
static FieldInfo methodbuilder_attrs_field;
1835
public readonly IMethodData method;
1838
// Are we implementing an interface ?
1840
public MethodSpec implementing;
1845
protected InterfaceMemberBase member;
1846
protected Modifiers modifiers;
1847
protected MethodAttributes flags;
1848
protected TypeSpec declaring_type;
1849
protected MethodSpec parent_method;
1850
SourceMethodBuilder debug_builder;
1852
MethodBuilder builder;
1853
public MethodBuilder MethodBuilder {
1859
public TypeSpec DeclaringType {
1861
return declaring_type;
1865
public MethodData (InterfaceMemberBase member,
1866
Modifiers modifiers, MethodAttributes flags, IMethodData method)
1868
this.member = member;
1869
this.modifiers = modifiers;
1872
this.method = method;
1875
public MethodData (InterfaceMemberBase member,
1876
Modifiers modifiers, MethodAttributes flags,
1877
IMethodData method, MethodBuilder builder,
1878
MethodSpec parent_method)
1879
: this (member, modifiers, flags, method)
1881
this.builder = builder;
1882
this.parent_method = parent_method;
1885
public bool Define (TypeDefinition container, string method_full_name)
1887
PendingImplementation pending = container.PendingImplementations;
1888
MethodSpec ambig_iface_method;
1889
bool optional = false;
1891
if (pending != null) {
1892
implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this, out ambig_iface_method, ref optional);
1894
if (member.InterfaceType != null) {
1895
if (implementing == null) {
1896
if (member is PropertyBase) {
1897
container.Compiler.Report.Error (550, method.Location,
1898
"`{0}' is an accessor not found in interface member `{1}{2}'",
1899
method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
1900
member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
1903
container.Compiler.Report.Error (539, method.Location,
1904
"`{0}.{1}' in explicit interface declaration is not a member of interface",
1905
TypeManager.CSharpName (member.InterfaceType), member.ShortName);
1909
if (implementing.IsAccessor && !method.IsAccessor) {
1910
container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
1911
container.Compiler.Report.Error (683, method.Location,
1912
"`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
1913
member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1917
if (implementing != null) {
1918
if (!method.IsAccessor) {
1919
if (implementing.IsAccessor) {
1920
container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
1921
container.Compiler.Report.Error (470, method.Location,
1922
"Method `{0}' cannot implement interface accessor `{1}'",
1923
method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1925
} else if (implementing.DeclaringType.IsInterface) {
1926
if (!implementing.IsAccessor) {
1927
container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
1928
container.Compiler.Report.Error (686, method.Location,
1929
"Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
1930
method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
1932
PropertyBase.PropertyMethod pm = method as PropertyBase.PropertyMethod;
1933
if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
1934
container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
1935
container.Compiler.Report.Error (277, method.Location,
1936
"Accessor `{0}' must be declared public to implement interface member `{1}'",
1937
method.GetSignatureForError (), implementing.GetSignatureForError ());
1944
ambig_iface_method = null;
1948
// For implicit implementations, make sure we are public, for
1949
// explicit implementations, make sure we are private.
1951
if (implementing != null){
1952
if (member.IsExplicitImpl) {
1953
if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
1954
container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
1955
container.Compiler.Report.Error (466, method.Location,
1956
"`{0}': the explicit interface implementation cannot introduce the params modifier",
1957
method.GetSignatureForError ());
1960
if (ambig_iface_method != null) {
1961
container.Compiler.Report.SymbolRelatedToPreviousError (ambig_iface_method);
1962
container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
1963
container.Compiler.Report.Warning (473, 2, method.Location,
1964
"Explicit interface implementation `{0}' matches more than one interface member. Consider using a non-explicit implementation instead",
1965
method.GetSignatureForError ());
1969
// Setting implementin to null inside this block will trigger a more
1970
// verbose error reporting for missing interface implementations
1972
if (implementing.DeclaringType.IsInterface) {
1974
// If this is an interface method implementation,
1975
// check for public accessibility
1977
if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) {
1978
implementing = null;
1979
} else if (optional && (container.Interfaces == null || !container.Definition.Interfaces.Contains (implementing.DeclaringType))) {
1981
// We are not implementing interface when base class already implemented it
1983
implementing = null;
1985
} else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1986
// We may never be private.
1987
implementing = null;
1989
} else if ((modifiers & Modifiers.OVERRIDE) == 0) {
1991
// We may be protected if we're overriding something.
1993
implementing = null;
1998
// Static is not allowed
2000
if ((modifiers & Modifiers.STATIC) != 0){
2001
implementing = null;
2006
// If implementing is still valid, set flags
2008
if (implementing != null){
2010
// When implementing interface methods, set NewSlot
2011
// unless, we are overwriting a method.
2013
if ((modifiers & Modifiers.OVERRIDE) == 0 && implementing.DeclaringType.IsInterface) {
2014
flags |= MethodAttributes.NewSlot;
2017
flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;
2019
// Set Final unless we're virtual, abstract or already overriding a method.
2020
if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
2021
flags |= MethodAttributes.Final;
2024
// clear the pending implementation flag (requires explicit methods to be defined first)
2026
pending.ImplementMethod (method.MethodName,
2027
member.InterfaceType, this, member.IsExplicitImpl, out ambig_iface_method, ref optional);
2030
// Update indexer accessor name to match implementing abstract accessor
2032
if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
2033
method_full_name = implementing.MemberDefinition.Name;
2036
DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
2038
if (builder == null)
2041
// if (container.CurrentType != null)
2042
// declaring_type = container.CurrentType;
2044
declaring_type = container.Definition;
2046
if (implementing != null && member.IsExplicitImpl) {
2047
container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
2055
/// Create the MethodBuilder for the method
2057
void DefineMethodBuilder (TypeDefinition container, string method_name, ParametersCompiled param)
2059
var return_type = method.ReturnType.GetMetaInfo ();
2060
var p_types = param.GetMetaInfo ();
2062
if (builder == null) {
2063
builder = container.TypeBuilder.DefineMethod (
2064
method_name, flags, method.CallingConventions,
2065
return_type, p_types);
2070
// Generic method has been already defined to resolve method parameters
2071
// correctly when they use type parameters
2073
builder.SetParameters (p_types);
2074
builder.SetReturnType (return_type);
2075
if (builder.Attributes != flags) {
2077
builder.__SetAttributes (flags);
2080
if (methodbuilder_attrs_field == null)
2081
methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
2082
methodbuilder_attrs_field.SetValue (builder, flags);
2084
container.Compiler.Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
2093
public void Emit (TypeDefinition parent)
2095
var mc = (IMemberContext) method;
2097
method.ParameterInfo.ApplyAttributes (mc, MethodBuilder);
2099
ToplevelBlock block = method.Block;
2100
if (block != null) {
2101
BlockContext bc = new BlockContext (mc, block, method.ReturnType);
2102
if (block.Resolve (null, bc, method)) {
2103
debug_builder = member.Parent.CreateMethodSymbolEntry ();
2104
EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator (), debug_builder);
2111
public void WriteDebugSymbol (MonoSymbolFile file)
2113
if (debug_builder == null)
2116
var token = builder.GetToken ();
2117
int t = token.Token;
2119
if (ModuleBuilder.IsPseudoToken (t))
2120
t = member.Module.Builder.ResolvePseudoToken (t);
2123
debug_builder.DefineMethod (file, t);
2127
public class Destructor : MethodOrOperator
2129
const Modifiers AllowedModifiers =
2133
static readonly string[] attribute_targets = new string [] { "method" };
2135
public static readonly string MetadataName = "Finalize";
2137
public string Identifier {
2142
public Destructor (TypeDefinition parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
2143
: base (parent, null, mod, AllowedModifiers, new MemberName (MetadataName, l), attrs, parameters)
2145
ModFlags &= ~Modifiers.PRIVATE;
2146
ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
2149
public override void Accept (StructuralVisitor visitor)
2151
visitor.Visit (this);
2154
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2156
if (a.Type == pa.Conditional) {
2157
Error_ConditionalAttributeIsNotValid ();
2161
base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2164
protected override bool CheckBase ()
2166
// Don't check base, destructors have special syntax
2170
public override bool Define ()
2174
if (Compiler.Settings.WriteMetadataOnly)
2180
public override void Emit()
2182
var base_type = Parent.PartialContainer.BaseType;
2183
if (base_type != null && Block != null) {
2184
var base_dtor = MemberCache.FindMember (base_type,
2185
new MemberFilter (MetadataName, 0, MemberKind.Destructor, null, null), BindingRestriction.InstanceOnly) as MethodSpec;
2187
if (base_dtor == null)
2188
throw new NotImplementedException ();
2190
MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
2191
method_expr.InstanceExpression = new BaseThis (base_type, Location);
2193
var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation) {
2194
IsCompilerGenerated = true
2196
var finaly_block = new ExplicitBlock (block, Location, Location) {
2197
IsCompilerGenerated = true
2201
// 0-size arguments to avoid CS0250 error
2202
// TODO: Should use AddScopeStatement or something else which emits correct
2205
finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0)), Location.Null));
2207
var tf = new TryFinally (try_block, finaly_block, Location);
2208
block.WrapIntoDestructor (tf, try_block);
2214
public override string GetSignatureForError ()
2216
return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
2219
protected override bool ResolveMemberType ()
2221
member_type = Compiler.BuiltinTypes.Void;
2225
public override string[] ValidAttributeTargets {
2227
return attribute_targets;
2232
// Ooouh Martin, templates are missing here.
2233
// When it will be possible move here a lot of child code and template method type.
2234
public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
2235
protected MethodData method_data;
2236
protected ToplevelBlock block;
2237
protected SecurityType declarative_security;
2239
protected readonly string prefix;
2241
ReturnParameter return_attributes;
2243
public AbstractPropertyEventMethod (InterfaceMemberBase member, string prefix, Attributes attrs, Location loc)
2244
: base (member.Parent, SetupName (prefix, member, loc), attrs)
2246
this.prefix = prefix;
2249
static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
2251
return new MemberName (member.MemberName.Left, prefix + member.ShortName, member.MemberName.ExplicitInterface, loc);
2254
public void UpdateName (InterfaceMemberBase member)
2256
SetMemberName (SetupName (prefix, member, Location));
2259
#region IMethodData Members
2261
public ToplevelBlock Block {
2271
public CallingConventions CallingConventions {
2273
return CallingConventions.Standard;
2277
public EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
2279
return new EmitContext (this, ig, ReturnType, sourceMethod);
2282
public bool IsAccessor {
2288
public MemberName MethodName {
2294
public TypeSpec[] ParameterTypes {
2296
return ParameterInfo.Types;
2300
public abstract ParametersCompiled ParameterInfo { get ; }
2301
public abstract TypeSpec ReturnType { get; }
2305
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2307
if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
2308
Report.Error (1667, a.Location,
2309
"Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
2310
TypeManager.CSharpName (a.Type), a.GetValidTargets ());
2314
if (a.IsValidSecurityAttribute ()) {
2315
a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
2319
if (a.Target == AttributeTargets.Method) {
2320
method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
2324
if (a.Target == AttributeTargets.ReturnValue) {
2325
if (return_attributes == null)
2326
return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2328
return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
2332
ApplyToExtraTarget (a, ctor, cdata, pa);
2335
protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2337
throw new NotSupportedException ("You forgot to define special attribute target handling");
2340
// It is not supported for the accessors
2341
public sealed override bool Define()
2343
throw new NotSupportedException ();
2346
public virtual void Emit (TypeDefinition parent)
2348
method_data.Emit (parent);
2350
if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
2351
Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
2352
if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
2353
Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
2355
if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2356
return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2357
Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
2358
} else if (ReturnType.HasDynamicElement) {
2359
return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2360
Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
2363
if (OptAttributes != null)
2364
OptAttributes.Emit ();
2366
if (declarative_security != null) {
2367
foreach (var de in declarative_security) {
2369
method_data.MethodBuilder.__AddDeclarativeSecurity (de);
2371
method_data.MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2379
public override bool EnableOverloadChecks (MemberCore overload)
2381
if (overload is MethodCore) {
2382
caching_flags |= Flags.MethodOverloadsExist;
2386
// This can only happen with indexers and it will
2387
// be catched as indexer difference
2388
if (overload is AbstractPropertyEventMethod)
2394
public override string GetCallerMemberName ()
2396
return base.GetCallerMemberName ().Substring (prefix.Length);
2399
public override string GetSignatureForDocumentation ()
2401
// should not be called
2402
throw new NotSupportedException ();
2405
public override bool IsClsComplianceRequired()
2410
public override void WriteDebugSymbol (MonoSymbolFile file)
2412
if (method_data != null)
2413
method_data.WriteDebugSymbol (file);
2416
public MethodSpec Spec { get; protected set; }
2419
// Represents header string for documentation comment.
2421
public override string DocCommentHeader {
2422
get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
2426
public class Operator : MethodOrOperator {
2428
const Modifiers AllowedModifiers =
2434
public enum OpType : byte {
2444
// Unary and Binary operators
2467
// Implicit and Explicit
2471
// Just because of enum
2475
public readonly OpType OperatorType;
2477
static readonly string [] [] names;
2481
names = new string[(int)OpType.TOP][];
2482
names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
2483
names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
2484
names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
2485
names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
2486
names [(int) OpType.True] = new string [] { "true", "op_True" };
2487
names [(int) OpType.False] = new string [] { "false", "op_False" };
2488
names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
2489
names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
2490
names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
2491
names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
2492
names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
2493
names [(int) OpType.Division] = new string [] { "/", "op_Division" };
2494
names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
2495
names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
2496
names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
2497
names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
2498
names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
2499
names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
2500
names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
2501
names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
2502
names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
2503
names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
2504
names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
2505
names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
2506
names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
2507
names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
2510
public Operator (TypeDefinition parent, OpType type, FullNamedExpression ret_type, Modifiers mod_flags, ParametersCompiled parameters,
2511
ToplevelBlock block, Attributes attrs, Location loc)
2512
: base (parent, ret_type, mod_flags, AllowedModifiers, new MemberName (GetMetadataName (type), loc), attrs, parameters)
2514
OperatorType = type;
2518
public override void Accept (StructuralVisitor visitor)
2520
visitor.Visit (this);
2523
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2525
if (a.Type == pa.Conditional) {
2526
Error_ConditionalAttributeIsNotValid ();
2530
base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2533
public override bool Define ()
2535
const Modifiers RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
2536
if ((ModFlags & RequiredModifiers) != RequiredModifiers){
2537
Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
2540
if (!base.Define ())
2543
if (block != null) {
2544
if (block.IsIterator) {
2546
// Current method is turned into automatically generated
2547
// wrapper which creates an instance of iterator
2549
Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
2550
ModFlags |= Modifiers.DEBUGGER_HIDDEN;
2553
if (Compiler.Settings.WriteMetadataOnly)
2557
// imlicit and explicit operator of same types are not allowed
2558
if (OperatorType == OpType.Explicit)
2559
Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
2560
else if (OperatorType == OpType.Implicit)
2561
Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
2563
TypeSpec declaring_type = Parent.CurrentType;
2564
TypeSpec return_type = MemberType;
2565
TypeSpec first_arg_type = ParameterTypes [0];
2567
TypeSpec first_arg_type_unwrap = first_arg_type;
2568
if (first_arg_type.IsNullableType)
2569
first_arg_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (first_arg_type);
2571
TypeSpec return_type_unwrap = return_type;
2572
if (return_type.IsNullableType)
2573
return_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (return_type);
2576
// Rules for conversion operators
2578
if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2579
if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type) {
2580
Report.Error (555, Location,
2581
"User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
2586
if (declaring_type == return_type || declaring_type == return_type_unwrap) {
2587
conv_type = first_arg_type;
2588
} else if (declaring_type == first_arg_type || declaring_type == first_arg_type_unwrap) {
2589
conv_type = return_type;
2591
Report.Error (556, Location,
2592
"User-defined conversion must convert to or from the enclosing type");
2596
if (conv_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2597
Report.Error (1964, Location,
2598
"User-defined conversion `{0}' cannot convert to or from the dynamic type",
2599
GetSignatureForError ());
2604
if (conv_type.IsInterface) {
2605
Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
2606
GetSignatureForError ());
2610
if (conv_type.IsClass) {
2611
if (TypeSpec.IsBaseClass (declaring_type, conv_type, true)) {
2612
Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
2613
GetSignatureForError ());
2617
if (TypeSpec.IsBaseClass (conv_type, declaring_type, false)) {
2618
Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
2619
GetSignatureForError ());
2623
} else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
2624
if (first_arg_type != declaring_type || parameters.Types[1].BuiltinType != BuiltinTypeSpec.Type.Int) {
2625
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");
2628
} else if (parameters.Count == 1) {
2629
// Checks for Unary operators
2631
if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
2632
if (return_type != declaring_type && !TypeSpec.IsBaseClass (return_type, declaring_type, false)) {
2633
Report.Error (448, Location,
2634
"The return type for ++ or -- operator must be the containing type or derived from the containing type");
2637
if (first_arg_type != declaring_type) {
2639
559, Location, "The parameter type for ++ or -- operator must be the containing type");
2644
if (first_arg_type_unwrap != declaring_type) {
2645
Report.Error (562, Location,
2646
"The parameter type of a unary operator must be the containing type");
2650
if (OperatorType == OpType.True || OperatorType == OpType.False) {
2651
if (return_type.BuiltinType != BuiltinTypeSpec.Type.Bool) {
2654
"The return type of operator True or False " +
2660
} else if (first_arg_type_unwrap != declaring_type) {
2661
// Checks for Binary operators
2663
var second_arg_type = ParameterTypes[1];
2664
if (second_arg_type.IsNullableType)
2665
second_arg_type = Nullable.NullableInfo.GetUnderlyingType (second_arg_type);
2667
if (second_arg_type != declaring_type) {
2668
Report.Error (563, Location,
2669
"One of the parameters of a binary operator must be the containing type");
2677
protected override bool ResolveMemberType ()
2679
if (!base.ResolveMemberType ())
2682
flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2686
protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
2688
// Operator cannot be override
2689
bestCandidate = null;
2693
public static string GetName (OpType ot)
2695
return names [(int) ot] [0];
2698
public static string GetName (string metadata_name)
2700
for (int i = 0; i < names.Length; ++i) {
2701
if (names [i] [1] == metadata_name)
2702
return names [i] [0];
2707
public static string GetMetadataName (OpType ot)
2709
return names [(int) ot] [1];
2712
public static string GetMetadataName (string name)
2714
for (int i = 0; i < names.Length; ++i) {
2715
if (names [i] [0] == name)
2716
return names [i] [1];
2721
public static OpType? GetType (string metadata_name)
2723
for (int i = 0; i < names.Length; ++i) {
2724
if (names[i][1] == metadata_name)
2731
public OpType GetMatchingOperator ()
2733
switch (OperatorType) {
2734
case OpType.Equality:
2735
return OpType.Inequality;
2736
case OpType.Inequality:
2737
return OpType.Equality;
2739
return OpType.False;
2742
case OpType.GreaterThan:
2743
return OpType.LessThan;
2744
case OpType.LessThan:
2745
return OpType.GreaterThan;
2746
case OpType.GreaterThanOrEqual:
2747
return OpType.LessThanOrEqual;
2748
case OpType.LessThanOrEqual:
2749
return OpType.GreaterThanOrEqual;
2755
public override string GetSignatureForDocumentation ()
2757
string s = base.GetSignatureForDocumentation ();
2758
if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2759
s = s + "~" + ReturnType.GetSignatureForDocumentation ();
2765
public override string GetSignatureForError ()
2767
StringBuilder sb = new StringBuilder ();
2768
if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2769
sb.AppendFormat ("{0}.{1} operator {2}",
2770
Parent.GetSignatureForError (), GetName (OperatorType),
2771
member_type == null ? type_expr.GetSignatureForError () : member_type.GetSignatureForError ());
2774
sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
2777
sb.Append (parameters.GetSignatureForError ());
2778
return sb.ToString ();