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;
23 using XmlElement = System.Object;
29 using MetaType = IKVM.Reflection.Type;
30 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
31 using IKVM.Reflection;
32 using IKVM.Reflection.Emit;
34 using MetaType = System.Type;
35 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
36 using System.Reflection;
37 using System.Reflection.Emit;
40 using Mono.CompilerServices.SymbolWriter;
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 (DeclSpace parent, GenericMethod generic,
51 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
52 MemberName name, Attributes attrs, ParametersCompiled parameters)
53 : base (parent, generic, type, mod, allowed_mod, name, attrs)
55 this.parameters = parameters;
58 public override Variance ExpectedMemberTypeVariance {
60 return Variance.Covariant;
65 // Returns the System.Type array for the parameters of this method
67 public TypeSpec [] ParameterTypes {
69 return parameters.Types;
73 public ParametersCompiled ParameterInfo {
79 AParametersCollection IParametersMember.Parameters {
80 get { return parameters; }
83 public ToplevelBlock Block {
93 public CallingConventions CallingConventions {
95 CallingConventions cc = parameters.CallingConvention;
97 if ((ModFlags & Modifiers.STATIC) == 0)
98 cc |= CallingConventions.HasThis;
100 // FIXME: How is `ExplicitThis' used in C#?
106 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
108 bool res = base.CheckOverrideAgainstBase (base_member);
111 // Check that the permissions are not being changed
113 if (!CheckAccessModifiers (this, base_member)) {
114 Error_CannotChangeAccessModifiers (this, base_member);
121 protected override bool CheckBase ()
123 // Check whether arguments were correct.
124 if (!DefineParameters (parameters))
127 return base.CheckBase ();
131 // Represents header string for documentation comment.
133 public override string DocCommentHeader
138 public override void Emit ()
140 if ((ModFlags & Modifiers.COMPILER_GENERATED) == 0) {
141 parameters.CheckConstraints (this);
147 public override bool EnableOverloadChecks (MemberCore overload)
149 if (overload is MethodCore) {
150 caching_flags |= Flags.MethodOverloadsExist;
154 if (overload is AbstractPropertyEventMethod)
157 return base.EnableOverloadChecks (overload);
160 public override string GetSignatureForDocumentation ()
162 string s = base.GetSignatureForDocumentation ();
163 if (MemberName.Arity > 0)
164 s += "``" + MemberName.Arity.ToString ();
166 return s + parameters.GetSignatureForDocumentation ();
169 public MethodSpec Spec {
173 protected override bool VerifyClsCompliance ()
175 if (!base.VerifyClsCompliance ())
178 if (parameters.HasArglist) {
179 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
182 if (member_type != null && !member_type.IsCLSCompliant ()) {
183 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
184 GetSignatureForError ());
187 parameters.VerifyClsCompliance (this);
192 public interface IGenericMethodDefinition : IMemberDefinition
194 TypeParameterSpec[] TypeParameters { get; }
195 int TypeParametersCount { get; }
197 // MethodInfo MakeGenericMethod (TypeSpec[] targs);
200 public sealed class MethodSpec : MemberSpec, IParametersMember
202 MethodBase metaInfo, inflatedMetaInfo;
203 AParametersCollection parameters;
207 TypeParameterSpec[] constraints;
209 public MethodSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition details, TypeSpec returnType,
210 MethodBase info, AParametersCollection parameters, Modifiers modifiers)
211 : base (kind, declaringType, details, modifiers)
213 this.metaInfo = info;
214 this.parameters = parameters;
215 this.returnType = returnType;
220 public override int Arity {
222 return IsGeneric ? GenericDefinition.TypeParametersCount : 0;
226 public TypeParameterSpec[] Constraints {
228 if (constraints == null && IsGeneric)
229 constraints = GenericDefinition.TypeParameters;
235 public bool IsConstructor {
237 return Kind == MemberKind.Constructor;
241 public IGenericMethodDefinition GenericDefinition {
243 return (IGenericMethodDefinition) definition;
247 public bool IsExtensionMethod {
249 return IsStatic && parameters.HasExtensionMethodType;
253 public bool IsSealed {
255 return (Modifiers & Modifiers.SEALED) != 0;
259 // When is virtual or abstract
260 public bool IsVirtual {
262 return (Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) != 0;
266 public bool IsReservedMethod {
268 return Kind == MemberKind.Operator || IsAccessor;
272 TypeSpec IInterfaceMemberSpec.MemberType {
278 public AParametersCollection Parameters {
284 public TypeSpec ReturnType {
290 public TypeSpec[] TypeArguments {
298 public MethodSpec GetGenericMethodDefinition ()
300 if (!IsGeneric && !DeclaringType.IsGeneric)
303 return MemberCache.GetMember (declaringType, this);
306 public MethodBase GetMetaInfo ()
309 // inflatedMetaInfo is extra field needed for cases where we
310 // inflate method but another nested type can later inflate
311 // again (the cache would be build with inflated metaInfo) and
312 // TypeBuilder can work with method definitions only
314 if (inflatedMetaInfo == null) {
315 if ((state & StateFlags.PendingMetaInflate) != 0) {
316 var dt_meta = DeclaringType.GetMetaInfo ();
318 if (DeclaringType.IsTypeBuilder) {
320 inflatedMetaInfo = TypeBuilder.GetConstructor (dt_meta, (ConstructorInfo) metaInfo);
322 inflatedMetaInfo = TypeBuilder.GetMethod (dt_meta, (MethodInfo) metaInfo);
325 // it should not be reached
326 throw new NotImplementedException ();
328 inflatedMetaInfo = MethodInfo.GetMethodFromHandle (metaInfo.MethodHandle, dt_meta.TypeHandle);
332 state &= ~StateFlags.PendingMetaInflate;
334 inflatedMetaInfo = metaInfo;
338 if ((state & StateFlags.PendingMakeMethod) != 0) {
339 var sre_targs = new MetaType[targs.Length];
340 for (int i = 0; i < sre_targs.Length; ++i)
341 sre_targs[i] = targs[i].GetMetaInfo ();
343 inflatedMetaInfo = ((MethodInfo) inflatedMetaInfo).MakeGenericMethod (sre_targs);
344 state &= ~StateFlags.PendingMakeMethod;
347 return inflatedMetaInfo;
350 public override string GetSignatureForDocumentation ()
354 case MemberKind.Constructor:
357 case MemberKind.Method:
359 name = Name + "``" + Arity.ToString ();
369 name = DeclaringType.GetSignatureForDocumentation () + "." + name + parameters.GetSignatureForDocumentation ();
370 if (Kind == MemberKind.Operator) {
371 var op = Operator.GetType (Name).Value;
372 if (op == Operator.OpType.Explicit || op == Operator.OpType.Implicit) {
373 name += "~" + ReturnType.GetSignatureForDocumentation ();
380 public override string GetSignatureForError ()
384 name = DeclaringType.GetSignatureForError () + "." + DeclaringType.Name;
385 } else if (Kind == MemberKind.Operator) {
386 var op = Operator.GetType (Name).Value;
387 if (op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) {
388 name = DeclaringType.GetSignatureForError () + "." + Operator.GetName (op) + " operator " + returnType.GetSignatureForError ();
390 name = DeclaringType.GetSignatureForError () + ".operator " + Operator.GetName (op);
392 } else if (IsAccessor) {
393 int split = Name.IndexOf ('_');
394 name = Name.Substring (split + 1);
395 var postfix = Name.Substring (0, split);
397 var pc = parameters.Count;
398 if (pc > 0 && postfix == "get") {
399 name = "this" + parameters.GetSignatureForError ("[", "]", pc);
400 } else if (pc > 1 && postfix == "set") {
401 name = "this" + parameters.GetSignatureForError ("[", "]", pc - 1);
405 return DeclaringType.GetSignatureForError () + "." + name + "." + postfix;
407 name = base.GetSignatureForError ();
409 name += "<" + TypeManager.CSharpName (targs) + ">";
411 name += "<" + TypeManager.CSharpName (GenericDefinition.TypeParameters) + ">";
414 return name + parameters.GetSignatureForError ();
417 public override MemberSpec InflateMember (TypeParameterInflator inflator)
419 var ms = (MethodSpec) base.InflateMember (inflator);
420 ms.inflatedMetaInfo = null;
421 ms.returnType = inflator.Inflate (returnType);
422 ms.parameters = parameters.Inflate (inflator);
424 ms.constraints = TypeParameterSpec.InflateConstraints (inflator, Constraints);
429 public MethodSpec MakeGenericMethod (IMemberContext context, params TypeSpec[] targs)
432 throw new ArgumentNullException ();
434 // if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
437 //if (generic_intances == null)
438 // generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
440 var inflator = new TypeParameterInflator (context, DeclaringType, GenericDefinition.TypeParameters, targs);
442 var inflated = (MethodSpec) MemberwiseClone ();
443 inflated.declaringType = inflator.TypeInstance;
444 inflated.returnType = inflator.Inflate (returnType);
445 inflated.parameters = parameters.Inflate (inflator);
446 inflated.targs = targs;
447 inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
448 inflated.state |= StateFlags.PendingMakeMethod;
450 // if (inflated.parent == null)
451 // inflated.parent = parent;
453 //generic_intances.Add (targs, inflated);
457 public MethodSpec Mutate (TypeParameterMutator mutator)
459 var targs = TypeArguments;
461 targs = mutator.Mutate (targs);
463 var decl = DeclaringType;
464 if (DeclaringType.IsGenericOrParentIsGeneric) {
465 decl = mutator.Mutate (decl);
468 if (targs == TypeArguments && decl == DeclaringType)
471 var ms = (MethodSpec) MemberwiseClone ();
472 if (decl != DeclaringType) {
473 ms.inflatedMetaInfo = null;
474 ms.declaringType = decl;
475 ms.state |= StateFlags.PendingMetaInflate;
480 ms.state |= StateFlags.PendingMakeMethod;
486 public override List<TypeSpec> ResolveMissingDependencies ()
488 var missing = returnType.ResolveMissingDependencies ();
489 foreach (var pt in parameters.Types) {
490 var m = pt.GetMissingDependencies ();
495 missing = new List<TypeSpec> ();
497 missing.AddRange (m);
503 public void SetMetaInfo (MethodInfo info)
505 if (this.metaInfo != null)
506 throw new InternalErrorException ("MetaInfo reset");
508 this.metaInfo = info;
512 public abstract class MethodOrOperator : MethodCore, IMethodData
514 public MethodBuilder MethodBuilder;
515 ReturnParameter return_attributes;
516 SecurityType declarative_security;
517 protected MethodData MethodData;
519 static readonly string[] attribute_targets = new string [] { "method", "return" };
521 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, Modifiers mod,
522 Modifiers allowed_mod, MemberName name,
523 Attributes attrs, ParametersCompiled parameters)
524 : base (parent, generic, type, mod, allowed_mod, name,
529 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
531 if (a.Target == AttributeTargets.ReturnValue) {
532 if (return_attributes == null)
533 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
535 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
539 if (a.Type == pa.MethodImpl) {
540 is_external_implementation = a.IsInternalCall ();
543 if (a.Type == pa.DllImport) {
544 const Modifiers extern_static = Modifiers.EXTERN | Modifiers.STATIC;
545 if ((ModFlags & extern_static) != extern_static) {
546 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
548 is_external_implementation = true;
551 if (a.IsValidSecurityAttribute ()) {
552 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
556 if (MethodBuilder != null)
557 MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
560 public override AttributeTargets AttributeTargets {
562 return AttributeTargets.Method;
566 protected override bool CheckForDuplications ()
568 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
571 public virtual EmitContext CreateEmitContext (ILGenerator ig)
573 return new EmitContext (this, ig, MemberType);
576 public override bool Define ()
585 if (this is Operator)
586 kind = MemberKind.Operator;
587 else if (this is Destructor)
588 kind = MemberKind.Destructor;
590 kind = MemberKind.Method;
592 if (IsPartialDefinition) {
593 caching_flags &= ~Flags.Excluded_Undetected;
594 caching_flags |= Flags.Excluded;
596 // Add to member cache only when a partial method implementation has not been found yet
597 if ((caching_flags & Flags.PartialDefinitionExists) == 0) {
598 // MethodBase mb = new PartialMethodDefinitionInfo (this);
600 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, null, parameters, ModFlags);
601 if (MemberName.Arity > 0) {
602 spec.IsGeneric = true;
604 // TODO: Have to move DefineMethod after Define (ideally to Emit)
605 throw new NotImplementedException ("Generic partial methods");
608 Parent.MemberCache.AddMember (spec);
614 MethodData = new MethodData (
615 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
617 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
620 MethodBuilder = MethodData.MethodBuilder;
622 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, MethodBuilder, parameters, ModFlags);
623 if (MemberName.Arity > 0)
624 spec.IsGeneric = true;
626 Parent.MemberCache.AddMember (this, MethodBuilder.Name, spec);
631 protected override void DoMemberTypeIndependentChecks ()
633 base.DoMemberTypeIndependentChecks ();
635 CheckAbstractAndExtern (block != null);
637 if ((ModFlags & Modifiers.PARTIAL) != 0) {
638 for (int i = 0; i < parameters.Count; ++i) {
639 IParameterData p = parameters.FixedParameters [i];
640 if (p.ModFlags == Parameter.Modifier.OUT) {
641 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
642 GetSignatureForError ());
645 if (p.HasDefaultValue && IsPartialImplementation)
646 ((Parameter) p).Warning_UselessOptionalParameter (Report);
651 protected override void DoMemberTypeDependentChecks ()
653 base.DoMemberTypeDependentChecks ();
655 if (MemberType.IsStatic) {
656 Error_StaticReturnType ();
660 public override void Emit ()
662 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
663 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (MethodBuilder);
664 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
665 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (MethodBuilder);
667 if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
668 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
669 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
670 } else if (ReturnType.HasDynamicElement) {
671 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
672 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
675 if (OptAttributes != null)
676 OptAttributes.Emit ();
678 if (declarative_security != null) {
679 foreach (var de in declarative_security) {
681 MethodBuilder.__AddDeclarativeSecurity (de);
683 MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
688 if (type_expr != null)
689 ConstraintChecker.Check (this, member_type, type_expr.Location);
693 if (MethodData != null)
694 MethodData.Emit (Parent);
700 protected void Error_ConditionalAttributeIsNotValid ()
702 Report.Error (577, Location,
703 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
704 GetSignatureForError ());
707 public bool IsPartialDefinition {
709 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
713 public bool IsPartialImplementation {
715 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
719 public override string[] ValidAttributeTargets {
721 return attribute_targets;
725 #region IMethodData Members
727 bool IMethodData.IsAccessor {
733 public TypeSpec ReturnType {
739 public MemberName MethodName {
746 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
748 public override string[] ConditionalConditions ()
750 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
753 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
754 return new string [0];
756 caching_flags &= ~Flags.Excluded_Undetected;
759 if (base_method == null) {
760 if (OptAttributes == null)
763 Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
767 conditions = new string[attrs.Length];
768 for (int i = 0; i < conditions.Length; ++i)
769 conditions[i] = attrs[i].GetConditionalAttributeValue ();
771 conditions = base_method.MemberDefinition.ConditionalConditions();
774 if (conditions != null)
775 caching_flags |= Flags.Excluded;
780 GenericMethod IMethodData.GenericMethod {
782 return GenericMethod;
786 public virtual void EmitExtraSymbolInfo (SourceMethod source)
793 public class SourceMethod : IMethodDef
796 SourceMethodBuilder builder;
798 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
800 this.method = method;
802 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
806 get { return method.Name; }
812 var mb = method as MethodBuilder;
814 token = mb.GetToken ();
816 token = ((ConstructorBuilder) method).GetToken ();
818 if (token.IsPseudoToken)
819 return ((ModuleBuilder) method.Module).ResolvePseudoToken (token.Token);
825 public void CloseMethod ()
827 SymbolWriter.CloseMethod ();
830 public void SetRealMethodName (string name)
833 builder.SetRealMethodName (name);
836 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
838 if (!SymbolWriter.HasSymbolWriter)
843 Location start_loc = block.StartLocation;
844 if (start_loc.IsNull)
847 ICompileUnit compile_unit = start_loc.CompilationUnit;
848 if (compile_unit == null)
851 return new SourceMethod (parent, method, compile_unit);
855 public class Method : MethodOrOperator, IGenericMethodDefinition
857 Method partialMethodImplementation;
859 public Method (DeclSpace parent, GenericMethod generic,
860 FullNamedExpression return_type, Modifiers mod,
861 MemberName name, ParametersCompiled parameters, Attributes attrs)
862 : base (parent, generic, return_type, mod,
863 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
864 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct | Modifiers.ASYNC :
865 AllowedModifiersClass | Modifiers.ASYNC,
866 name, attrs, parameters)
870 protected Method (DeclSpace parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
871 MemberName name, ParametersCompiled parameters, Attributes attrs)
872 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
878 public override TypeParameters CurrentTypeParameters {
880 if (GenericMethod != null)
881 return GenericMethod.CurrentTypeParameters;
887 public TypeParameterSpec[] TypeParameters {
889 return CurrentTypeParameters.Types;
893 public int TypeParametersCount {
895 return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Count;
901 public override void Accept (StructuralVisitor visitor)
903 visitor.Visit (this);
906 public static Method Create (DeclSpace parent, GenericMethod generic, FullNamedExpression returnType, Modifiers mod,
907 MemberName name, ParametersCompiled parameters, Attributes attrs, bool hasConstraints)
909 var m = new Method (parent, generic, returnType, mod, name, parameters, attrs);
911 if (hasConstraints && ((mod & Modifiers.OVERRIDE) != 0 || m.IsExplicitImpl)) {
912 m.Report.Error (460, m.Location,
913 "`{0}': Cannot specify constraints for overrides and explicit interface implementation methods",
914 m.GetSignatureForError ());
917 if ((mod & Modifiers.PARTIAL) != 0) {
918 const Modifiers invalid_partial_mod = Modifiers.AccessibilityMask | Modifiers.ABSTRACT | Modifiers.EXTERN |
919 Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.SEALED | Modifiers.VIRTUAL;
921 if ((mod & invalid_partial_mod) != 0) {
922 m.Report.Error (750, m.Location,
923 "A partial method cannot define access modifier or any of abstract, extern, new, override, sealed, or virtual modifiers");
924 mod &= ~invalid_partial_mod;
927 if ((parent.ModFlags & Modifiers.PARTIAL) == 0) {
928 m.Report.Error (751, m.Location,
929 "A partial method must be declared within a partial class or partial struct");
933 if ((mod & Modifiers.STATIC) == 0 && parameters.HasExtensionMethodType) {
934 m.Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static",
935 m.GetSignatureForError ());
942 public override string GetSignatureForError()
944 return base.GetSignatureForError () + parameters.GetSignatureForError ();
947 void Error_DuplicateEntryPoint (Method b)
949 Report.Error (17, b.Location,
950 "Program `{0}' has more than one entry point defined: `{1}'",
951 b.Module.Builder.ScopeName, b.GetSignatureForError ());
956 if (ReturnType.Kind != MemberKind.Void && ReturnType.BuiltinType != BuiltinTypeSpec.Type.Int)
959 if (parameters.IsEmpty)
962 if (parameters.Count > 1)
965 var ac = parameters.Types [0] as ArrayContainer;
966 return ac != null && ac.Rank == 1 && ac.Element.BuiltinType == BuiltinTypeSpec.Type.String &&
967 (parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
970 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
973 var tp = CurrentTypeParameters;
975 TypeParameter t = tp.Find (name);
977 return new TypeParameterExpr (t, loc);
981 return base.LookupNamespaceOrType (name, arity, mode, loc);
984 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
986 if (a.Type == pa.Conditional) {
987 if (IsExplicitImpl) {
988 Error_ConditionalAttributeIsNotValid ();
992 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
993 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
997 if (ReturnType.Kind != MemberKind.Void) {
998 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
1003 Report.Error (582, Location, "Conditional not valid on interface members");
1007 if (MethodData.implementing != null) {
1008 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
1009 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
1010 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
1014 for (int i = 0; i < parameters.Count; ++i) {
1015 if (parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
1016 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
1022 if (a.Type == pa.Extension) {
1023 a.Error_MisusedExtensionAttribute ();
1027 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1030 protected virtual void DefineTypeParameters ()
1032 var tparams = CurrentTypeParameters;
1034 TypeParameterSpec[] base_tparams = null;
1035 TypeParameterSpec[] base_decl_tparams = TypeParameterSpec.EmptyTypes;
1036 TypeSpec[] base_targs = TypeSpec.EmptyTypes;
1037 if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
1038 if (base_method != null) {
1039 base_tparams = base_method.GenericDefinition.TypeParameters;
1041 if (base_method.DeclaringType.IsGeneric) {
1042 base_decl_tparams = base_method.DeclaringType.MemberDefinition.TypeParameters;
1044 var base_type_parent = CurrentType;
1045 while (base_type_parent.BaseType != base_method.DeclaringType) {
1046 base_type_parent = base_type_parent.BaseType;
1049 base_targs = base_type_parent.BaseType.TypeArguments;
1052 if (base_method.IsGeneric) {
1053 ObsoleteAttribute oa;
1054 foreach (var base_tp in base_tparams) {
1055 oa = base_tp.BaseType.GetAttributeObsolete ();
1057 AttributeTester.Report_ObsoleteMessage (oa, base_tp.BaseType.GetSignatureForError (), Location, Report);
1060 if (base_tp.InterfacesDefined != null) {
1061 foreach (var iface in base_tp.InterfacesDefined) {
1062 oa = iface.GetAttributeObsolete ();
1064 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1070 if (base_decl_tparams.Length != 0) {
1071 base_decl_tparams = base_decl_tparams.Concat (base_tparams).ToArray ();
1072 base_targs = base_targs.Concat (tparams.Types).ToArray ();
1074 base_decl_tparams = base_tparams;
1075 base_targs = tparams.Types;
1078 } else if (MethodData.implementing != null) {
1079 base_tparams = MethodData.implementing.GenericDefinition.TypeParameters;
1080 if (MethodData.implementing.DeclaringType.IsGeneric) {
1081 base_decl_tparams = MethodData.implementing.DeclaringType.MemberDefinition.TypeParameters;
1082 foreach (var iface in Parent.CurrentType.Interfaces) {
1083 if (iface == MethodData.implementing.DeclaringType) {
1084 base_targs = iface.TypeArguments;
1092 for (int i = 0; i < tparams.Count; ++i) {
1093 var tp = tparams[i];
1095 if (!tp.ResolveConstraints (this))
1099 // Copy base constraints for override/explicit methods
1101 if (base_tparams != null) {
1102 var base_tparam = base_tparams[i];
1103 var local_tparam = tp.Type;
1104 local_tparam.SpecialConstraint = base_tparam.SpecialConstraint;
1106 var inflator = new TypeParameterInflator (this, CurrentType, base_decl_tparams, base_targs);
1107 base_tparam.InflateConstraints (inflator, local_tparam);
1110 // Check all type argument constraints for possible collision or unification
1111 // introduced by inflating inherited constraints in this context
1113 // Conflict example:
1115 // class A<T> { virtual void Foo<U> () where U : class, T {} }
1116 // class B : A<int> { override void Foo<U> {} }
1118 var local_tparam_targs = local_tparam.TypeArguments;
1119 if (local_tparam_targs != null) {
1120 for (int ii = 0; ii < local_tparam_targs.Length; ++ii) {
1121 var ta = local_tparam_targs [ii];
1122 if (!ta.IsClass && !ta.IsStruct)
1125 TypeSpec[] unique_tparams = null;
1126 for (int iii = ii + 1; iii < local_tparam_targs.Length; ++iii) {
1128 // Remove any identical or unified constraint types
1130 var tparam_checked = local_tparam_targs[iii];
1131 if (TypeSpecComparer.IsEqual (ta, tparam_checked) || TypeSpec.IsBaseClass (ta, tparam_checked, false)) {
1132 unique_tparams = new TypeSpec[local_tparam_targs.Length - 1];
1133 Array.Copy (local_tparam_targs, 0, unique_tparams, 0, iii);
1134 Array.Copy (local_tparam_targs, iii + 1, unique_tparams, iii, local_tparam_targs.Length - iii - 1);
1135 } else if (!TypeSpec.IsBaseClass (tparam_checked, ta, false)) {
1136 Constraints.Error_ConflictingConstraints (this, local_tparam, ta, tparam_checked, Location);
1140 if (unique_tparams != null) {
1141 local_tparam_targs = unique_tparams;
1142 local_tparam.TypeArguments = local_tparam_targs;
1146 Constraints.CheckConflictingInheritedConstraint (local_tparam, ta, this, Location);
1154 if (base_tparams == null && MethodData != null && MethodData.implementing != null) {
1155 CheckImplementingMethodConstraints (Parent, spec, MethodData.implementing);
1159 public static bool CheckImplementingMethodConstraints (TypeContainer container, MethodSpec method, MethodSpec baseMethod)
1161 var tparams = method.Constraints;
1162 var base_tparams = baseMethod.Constraints;
1163 for (int i = 0; i < tparams.Length; ++i) {
1164 if (!tparams[i].HasSameConstraintsImplementation (base_tparams[i])) {
1165 container.Compiler.Report.SymbolRelatedToPreviousError (method);
1166 container.Compiler.Report.SymbolRelatedToPreviousError (baseMethod);
1168 // Using container location because the interface can be implemented
1170 container.Compiler.Report.Error (425, container.Location,
1171 "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",
1172 tparams[i].GetSignatureForError (), method.GetSignatureForError (),
1173 base_tparams[i].GetSignatureForError (), baseMethod.GetSignatureForError ());
1185 public override bool Define ()
1187 if (!base.Define ())
1190 if (member_type.Kind == MemberKind.Void && parameters.IsEmpty && MemberName.Arity == 0 && MemberName.Name == Destructor.MetadataName) {
1191 Report.Warning (465, 1, Location,
1192 "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
1195 if (partialMethodImplementation != null && IsPartialDefinition)
1196 MethodBuilder = partialMethodImplementation.MethodBuilder;
1198 if (Compiler.Settings.StdLib && ReturnType.IsSpecialRuntimeType) {
1199 Error1599 (Location, ReturnType, Report);
1203 if (CurrentTypeParameters == null) {
1204 if (base_method != null) {
1205 if (parameters.Count == 1 && ParameterTypes[0].BuiltinType == BuiltinTypeSpec.Type.Object && Name == "Equals")
1206 Parent.PartialContainer.Mark_HasEquals ();
1207 else if (parameters.IsEmpty && Name == "GetHashCode")
1208 Parent.PartialContainer.Mark_HasGetHashCode ();
1212 DefineTypeParameters ();
1215 if (block != null) {
1216 if (block.IsIterator) {
1218 // Current method is turned into automatically generated
1219 // wrapper which creates an instance of iterator
1221 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1222 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
1225 if ((ModFlags & Modifiers.ASYNC) != 0) {
1226 if (ReturnType.Kind != MemberKind.Void &&
1227 ReturnType != Module.PredefinedTypes.Task.TypeSpec &&
1228 !ReturnType.IsGenericTask) {
1229 Report.Error (1983, Location, "The return type of an async method must be void, Task, or Task<T>");
1232 AsyncInitializer.Create (this, block, parameters, Parent.PartialContainer, ReturnType, Location);
1236 if ((ModFlags & Modifiers.STATIC) == 0)
1239 if (parameters.HasExtensionMethodType) {
1240 if (Parent.PartialContainer.IsStatic && !Parent.IsGeneric) {
1241 if (!Parent.IsTopLevel)
1242 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
1243 GetSignatureForError ());
1245 PredefinedAttribute pa = Module.PredefinedAttributes.Extension;
1246 if (!pa.IsDefined) {
1247 Report.Error (1110, Location,
1248 "`{0}': Extension methods require `System.Runtime.CompilerServices.ExtensionAttribute' type to be available. Are you missing an assembly reference?",
1249 GetSignatureForError ());
1252 ModFlags |= Modifiers.METHOD_EXTENSION;
1253 Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
1254 Spec.DeclaringType.SetExtensionMethodContainer ();
1255 Parent.Module.HasExtensionMethod = true;
1257 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
1258 GetSignatureForError ());
1263 // This is used to track the Entry Point,
1265 var settings = Compiler.Settings;
1266 if (settings.NeedsEntryPoint && Name == "Main" && (settings.MainClass == null || settings.MainClass == Parent.TypeBuilder.FullName)) {
1267 if (IsEntryPoint ()) {
1268 if (Parent.DeclaringAssembly.EntryPoint == null) {
1269 if (Parent.IsGeneric || MemberName.IsGeneric) {
1270 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
1271 GetSignatureForError ());
1272 } else if ((ModFlags & Modifiers.ASYNC) != 0) {
1273 Report.Error (4009, Location, "`{0}': an entry point cannot be async method",
1274 GetSignatureForError ());
1277 Parent.DeclaringAssembly.EntryPoint = this;
1280 Error_DuplicateEntryPoint (Parent.DeclaringAssembly.EntryPoint);
1281 Error_DuplicateEntryPoint (this);
1284 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
1285 GetSignatureForError ());
1295 public override void Emit ()
1298 if (IsPartialDefinition) {
1300 // Use partial method implementation builder for partial method declaration attributes
1302 if (partialMethodImplementation != null) {
1303 MethodBuilder = partialMethodImplementation.MethodBuilder;
1309 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
1310 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
1311 GetSignatureForError ());
1314 if (CurrentTypeParameters != null) {
1315 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1316 var tp = CurrentTypeParameters [i];
1317 tp.CheckGenericConstraints (false);
1324 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
1325 Module.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
1327 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
1328 Location, MethodBuilder);
1333 public override bool EnableOverloadChecks (MemberCore overload)
1335 // TODO: It can be deleted when members will be defined in correct order
1336 if (overload is Operator)
1337 return overload.EnableOverloadChecks (this);
1339 if (overload is Indexer)
1342 return base.EnableOverloadChecks (overload);
1345 public static void Error1599 (Location loc, TypeSpec t, Report Report)
1347 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
1350 protected override bool ResolveMemberType ()
1352 if (GenericMethod != null) {
1353 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
1354 if (!GenericMethod.Define (this))
1358 return base.ResolveMemberType ();
1361 public void SetPartialDefinition (Method methodDefinition)
1363 caching_flags |= Flags.PartialDefinitionExists;
1364 methodDefinition.partialMethodImplementation = this;
1366 // Ensure we are always using method declaration parameters
1367 for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
1368 parameters [i].Name = methodDefinition.parameters [i].Name;
1369 parameters [i].DefaultValue = methodDefinition.parameters [i].DefaultValue;
1372 if (methodDefinition.attributes == null)
1375 if (attributes == null) {
1376 attributes = methodDefinition.attributes;
1378 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
1383 public abstract class ConstructorInitializer : ExpressionStatement
1385 Arguments argument_list;
1386 MethodSpec base_ctor;
1388 public ConstructorInitializer (Arguments argument_list, Location loc)
1390 this.argument_list = argument_list;
1394 public Arguments Arguments {
1396 return argument_list;
1400 public override bool ContainsEmitWithAwait ()
1402 throw new NotSupportedException ();
1405 public override Expression CreateExpressionTree (ResolveContext ec)
1407 throw new NotSupportedException ("ET");
1410 protected override Expression DoResolve (ResolveContext ec)
1412 eclass = ExprClass.Value;
1415 var caller_builder = (Constructor) ec.MemberContext;
1418 // Spec mandates that constructor initializer will not have `this' access
1420 using (ec.Set (ResolveContext.Options.BaseInitializer)) {
1421 if (argument_list != null) {
1423 argument_list.Resolve (ec, out dynamic);
1426 ec.Report.Error (1975, loc,
1427 "The constructor call cannot be dynamically dispatched within constructor initializer");
1433 type = ec.CurrentType;
1434 if (this is ConstructorBaseInitializer) {
1435 if (ec.CurrentType.BaseType == null)
1438 type = ec.CurrentType.BaseType;
1439 if (ec.CurrentType.IsStruct) {
1440 ec.Report.Error (522, loc,
1441 "`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
1446 // It is legal to have "this" initializers that take no arguments
1447 // in structs, they are just no-ops.
1449 // struct D { public D (int a) : this () {}
1451 if (ec.CurrentType.IsStruct && argument_list == null)
1455 base_ctor = ConstructorLookup (ec, type, ref argument_list, loc);
1458 // TODO MemberCache: Does it work for inflated types ?
1459 if (base_ctor == caller_builder.Spec){
1460 ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
1461 caller_builder.GetSignatureForError ());
1467 public override void Emit (EmitContext ec)
1469 // It can be null for static initializers
1470 if (base_ctor == null)
1475 var call = new CallEmitter ();
1476 call.InstanceExpression = new CompilerGeneratedThis (type, loc);
1477 call.EmitPredefined (ec, base_ctor, argument_list);
1480 public override void EmitStatement (EmitContext ec)
1486 public class ConstructorBaseInitializer : ConstructorInitializer {
1487 public ConstructorBaseInitializer (Arguments argument_list, Location l) :
1488 base (argument_list, l)
1493 class GeneratedBaseInitializer: ConstructorBaseInitializer {
1494 public GeneratedBaseInitializer (Location loc):
1500 public class ConstructorThisInitializer : ConstructorInitializer {
1501 public ConstructorThisInitializer (Arguments argument_list, Location l) :
1502 base (argument_list, l)
1507 public class Constructor : MethodCore, IMethodData {
1508 public ConstructorBuilder ConstructorBuilder;
1509 public ConstructorInitializer Initializer;
1510 SecurityType declarative_security;
1511 bool has_compliant_args;
1514 // Modifiers allowed for a constructor.
1516 public const Modifiers AllowedModifiers =
1518 Modifiers.PROTECTED |
1519 Modifiers.INTERNAL |
1525 static readonly string[] attribute_targets = new string [] { "method" };
1527 public static readonly string ConstructorName = ".ctor";
1528 public static readonly string TypeConstructorName = ".cctor";
1530 public Constructor (DeclSpace parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args, Location loc)
1531 : base (parent, null, null, mod, AllowedModifiers,
1532 new MemberName (name, loc), attrs, args)
1536 public bool HasCompliantArgs {
1538 return has_compliant_args;
1542 public override AttributeTargets AttributeTargets {
1544 return AttributeTargets.Constructor;
1548 bool IMethodData.IsAccessor {
1555 // Returns true if this is a default constructor
1557 public bool IsDefault ()
1559 if ((ModFlags & Modifiers.STATIC) != 0)
1560 return parameters.IsEmpty;
1562 return parameters.IsEmpty &&
1563 (Initializer is ConstructorBaseInitializer) &&
1564 (Initializer.Arguments == null);
1567 public override void Accept (StructuralVisitor visitor)
1569 visitor.Visit (this);
1572 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1574 if (a.IsValidSecurityAttribute ()) {
1575 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
1579 if (a.Type == pa.MethodImpl) {
1580 is_external_implementation = a.IsInternalCall ();
1583 ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1586 protected override bool CheckBase ()
1588 if ((ModFlags & Modifiers.STATIC) != 0) {
1589 if (!parameters.IsEmpty) {
1590 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
1591 GetSignatureForError ());
1595 // the rest can be ignored
1599 // Check whether arguments were correct.
1600 if (!DefineParameters (parameters))
1603 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1604 Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1606 if (Parent.PartialContainer.Kind == MemberKind.Struct && parameters.IsEmpty) {
1607 Report.Error (568, Location,
1608 "Structs cannot contain explicit parameterless constructors");
1612 CheckProtectedModifier ();
1618 // Creates the ConstructorBuilder
1620 public override bool Define ()
1622 if (ConstructorBuilder != null)
1625 var ca = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
1627 if ((ModFlags & Modifiers.STATIC) != 0) {
1628 ca |= MethodAttributes.Static | MethodAttributes.Private;
1630 ca |= ModifiersExtensions.MethodAttr (ModFlags);
1633 if (!CheckAbstractAndExtern (block != null))
1636 // Check if arguments were correct.
1640 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
1641 ca, CallingConventions,
1642 parameters.GetMetaInfo ());
1644 spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, Compiler.BuiltinTypes.Void, ConstructorBuilder, parameters, ModFlags);
1646 Parent.MemberCache.AddMember (spec);
1648 // It's here only to report an error
1649 if (block != null && block.IsIterator) {
1650 member_type = Compiler.BuiltinTypes.Void;
1651 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1660 public override void Emit ()
1662 if (Parent.PartialContainer.IsComImport) {
1663 if (!IsDefault ()) {
1664 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
1665 Parent.GetSignatureForError ());
1668 // Set as internal implementation and reset block data
1669 // to ensure no IL is generated
1670 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
1674 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
1675 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (ConstructorBuilder);
1677 if (OptAttributes != null)
1678 OptAttributes.Emit ();
1681 parameters.ApplyAttributes (this, ConstructorBuilder);
1684 // If we use a "this (...)" constructor initializer, then
1685 // do not emit field initializers, they are initialized in the other constructor
1687 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
1688 !(Initializer is ConstructorThisInitializer);
1690 BlockContext bc = new BlockContext (this, block, Compiler.BuiltinTypes.Void);
1691 bc.Set (ResolveContext.Options.ConstructorScope);
1693 if (emit_field_initializers)
1694 Parent.PartialContainer.ResolveFieldInitializers (bc);
1696 if (block != null) {
1697 // If this is a non-static `struct' constructor and doesn't have any
1698 // initializer, it must initialize all of the struct's fields.
1699 if ((Parent.PartialContainer.Kind == MemberKind.Struct) &&
1700 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
1701 block.AddThisVariable (bc);
1703 if ((ModFlags & Modifiers.STATIC) == 0){
1704 if (Parent.PartialContainer.Kind == MemberKind.Class && Initializer == null)
1705 Initializer = new GeneratedBaseInitializer (Location);
1707 if (Initializer != null) {
1708 block.AddScopeStatement (new StatementExpression (Initializer));
1713 SourceMethod source = SourceMethod.Create (Parent, ConstructorBuilder, block);
1715 if (block != null) {
1716 if (block.Resolve (null, bc, this)) {
1717 EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType);
1718 ec.With (EmitContext.Options.ConstructorScope, true);
1725 source.CloseMethod ();
1727 if (declarative_security != null) {
1728 foreach (var de in declarative_security) {
1730 ConstructorBuilder.__AddDeclarativeSecurity (de);
1732 ConstructorBuilder.AddDeclarativeSecurity (de.Key, de.Value);
1740 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
1742 // Is never override
1743 bestCandidate = null;
1747 public override string GetSignatureForDocumentation ()
1749 return Parent.GetSignatureForDocumentation () + ".#ctor" + parameters.GetSignatureForDocumentation ();
1752 public override string GetSignatureForError()
1754 return base.GetSignatureForError () + parameters.GetSignatureForError ();
1757 public override string[] ValidAttributeTargets {
1759 return attribute_targets;
1763 protected override bool VerifyClsCompliance ()
1765 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
1769 if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
1770 foreach (TypeSpec param in parameters.Types) {
1771 if (param.IsArray) {
1777 has_compliant_args = true;
1781 #region IMethodData Members
1783 public MemberName MethodName {
1789 public TypeSpec ReturnType {
1795 public EmitContext CreateEmitContext (ILGenerator ig)
1797 throw new NotImplementedException ();
1800 public bool IsExcluded()
1805 GenericMethod IMethodData.GenericMethod {
1811 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
1818 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
1820 public interface IMethodData : IMemberContext
1822 CallingConventions CallingConventions { get; }
1823 Location Location { get; }
1824 MemberName MethodName { get; }
1825 TypeSpec ReturnType { get; }
1826 GenericMethod GenericMethod { get; }
1827 ParametersCompiled ParameterInfo { get; }
1828 MethodSpec Spec { get; }
1829 bool IsAccessor { get; }
1831 Attributes OptAttributes { get; }
1832 ToplevelBlock Block { get; set; }
1834 EmitContext CreateEmitContext (ILGenerator ig);
1835 void EmitExtraSymbolInfo (SourceMethod source);
1839 // Encapsulates most of the Method's state
1841 public class MethodData
1844 static FieldInfo methodbuilder_attrs_field;
1847 public readonly IMethodData method;
1849 public readonly GenericMethod GenericMethod;
1852 // Are we implementing an interface ?
1854 public MethodSpec implementing;
1859 protected InterfaceMemberBase member;
1860 protected Modifiers modifiers;
1861 protected MethodAttributes flags;
1862 protected TypeSpec declaring_type;
1863 protected MethodSpec parent_method;
1865 MethodBuilder builder;
1866 public MethodBuilder MethodBuilder {
1872 public TypeSpec DeclaringType {
1874 return declaring_type;
1878 public MethodData (InterfaceMemberBase member,
1879 Modifiers modifiers, MethodAttributes flags, IMethodData method)
1881 this.member = member;
1882 this.modifiers = modifiers;
1885 this.method = method;
1888 public MethodData (InterfaceMemberBase member,
1889 Modifiers modifiers, MethodAttributes flags,
1890 IMethodData method, MethodBuilder builder,
1891 GenericMethod generic, MethodSpec parent_method)
1892 : this (member, modifiers, flags, method)
1894 this.builder = builder;
1895 this.GenericMethod = generic;
1896 this.parent_method = parent_method;
1899 public bool Define (TypeContainer container, string method_full_name)
1901 PendingImplementation pending = container.PendingImplementations;
1902 MethodSpec ambig_iface_method;
1903 bool optional = false;
1905 if (pending != null) {
1906 implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this, out ambig_iface_method, ref optional);
1908 if (member.InterfaceType != null) {
1909 if (implementing == null) {
1910 if (member is PropertyBase) {
1911 container.Compiler.Report.Error (550, method.Location,
1912 "`{0}' is an accessor not found in interface member `{1}{2}'",
1913 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
1914 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
1917 container.Compiler.Report.Error (539, method.Location,
1918 "`{0}.{1}' in explicit interface declaration is not a member of interface",
1919 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
1923 if (implementing.IsAccessor && !method.IsAccessor) {
1924 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
1925 container.Compiler.Report.Error (683, method.Location,
1926 "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
1927 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1931 if (implementing != null) {
1932 if (!method.IsAccessor) {
1933 if (implementing.IsAccessor) {
1934 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
1935 container.Compiler.Report.Error (470, method.Location,
1936 "Method `{0}' cannot implement interface accessor `{1}'",
1937 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1939 } else if (implementing.DeclaringType.IsInterface) {
1940 if (!implementing.IsAccessor) {
1941 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
1942 container.Compiler.Report.Error (686, method.Location,
1943 "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
1944 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
1946 PropertyBase.PropertyMethod pm = method as PropertyBase.PropertyMethod;
1947 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
1948 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
1949 container.Compiler.Report.Error (277, method.Location,
1950 "Accessor `{0}' must be declared public to implement interface member `{1}'",
1951 method.GetSignatureForError (), implementing.GetSignatureForError ());
1958 ambig_iface_method = null;
1962 // For implicit implementations, make sure we are public, for
1963 // explicit implementations, make sure we are private.
1965 if (implementing != null){
1966 if (member.IsExplicitImpl) {
1967 if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
1968 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
1969 container.Compiler.Report.Error (466, method.Location,
1970 "`{0}': the explicit interface implementation cannot introduce the params modifier",
1971 method.GetSignatureForError ());
1974 if (ambig_iface_method != null) {
1975 container.Compiler.Report.SymbolRelatedToPreviousError (ambig_iface_method);
1976 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
1977 container.Compiler.Report.Warning (473, 2, method.Location,
1978 "Explicit interface implementation `{0}' matches more than one interface member. Consider using a non-explicit implementation instead",
1979 method.GetSignatureForError ());
1983 // Setting implementin to null inside this block will trigger a more
1984 // verbose error reporting for missing interface implementations
1986 if (implementing.DeclaringType.IsInterface) {
1988 // If this is an interface method implementation,
1989 // check for public accessibility
1991 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) {
1992 implementing = null;
1993 } else if (optional && (container.Interfaces == null || Array.IndexOf (container.Interfaces, implementing.DeclaringType) < 0)) {
1995 // We are not implementing interface when base class already implemented it
1997 implementing = null;
1999 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2000 // We may never be private.
2001 implementing = null;
2003 } else if ((modifiers & Modifiers.OVERRIDE) == 0) {
2005 // We may be protected if we're overriding something.
2007 implementing = null;
2012 // Static is not allowed
2014 if ((modifiers & Modifiers.STATIC) != 0){
2015 implementing = null;
2020 // If implementing is still valid, set flags
2022 if (implementing != null){
2024 // When implementing interface methods, set NewSlot
2025 // unless, we are overwriting a method.
2027 if ((modifiers & Modifiers.OVERRIDE) == 0 && implementing.DeclaringType.IsInterface) {
2028 flags |= MethodAttributes.NewSlot;
2031 flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;
2033 // Set Final unless we're virtual, abstract or already overriding a method.
2034 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
2035 flags |= MethodAttributes.Final;
2038 // clear the pending implementation flag (requires explicit methods to be defined first)
2040 pending.ImplementMethod (method.MethodName,
2041 member.InterfaceType, this, member.IsExplicitImpl, out ambig_iface_method, ref optional);
2044 // Update indexer accessor name to match implementing abstract accessor
2046 if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
2047 method_full_name = implementing.MemberDefinition.Name;
2050 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
2052 if (builder == null)
2055 // if (container.CurrentType != null)
2056 // declaring_type = container.CurrentType;
2058 declaring_type = container.Definition;
2060 if (implementing != null && member.IsExplicitImpl) {
2061 container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
2069 /// Create the MethodBuilder for the method
2071 void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
2073 var return_type = method.ReturnType.GetMetaInfo ();
2074 var p_types = param.GetMetaInfo ();
2076 if (builder == null) {
2077 builder = container.TypeBuilder.DefineMethod (
2078 method_name, flags, method.CallingConventions,
2079 return_type, p_types);
2084 // Generic method has been already defined to resolve method parameters
2085 // correctly when they use type parameters
2087 builder.SetParameters (p_types);
2088 builder.SetReturnType (return_type);
2089 if (builder.Attributes != flags) {
2091 builder.__SetAttributes (flags);
2094 if (methodbuilder_attrs_field == null)
2095 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
2096 methodbuilder_attrs_field.SetValue (builder, flags);
2098 container.Compiler.Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
2107 public void Emit (DeclSpace parent)
2109 if (GenericMethod != null)
2110 GenericMethod.EmitAttributes ();
2112 var mc = (IMemberContext) method;
2114 method.ParameterInfo.ApplyAttributes (mc, MethodBuilder);
2116 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
2118 ToplevelBlock block = method.Block;
2119 if (block != null) {
2120 BlockContext bc = new BlockContext (mc, block, method.ReturnType);
2121 if (block.Resolve (null, bc, method)) {
2122 EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator ());
2128 if (source != null) {
2129 method.EmitExtraSymbolInfo (source);
2130 source.CloseMethod ();
2135 public class Destructor : MethodOrOperator
2137 const Modifiers AllowedModifiers =
2141 static readonly string[] attribute_targets = new string [] { "method" };
2143 public static readonly string MetadataName = "Finalize";
2145 public Destructor (DeclSpace parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
2146 : base (parent, null, null, mod, AllowedModifiers,
2147 new MemberName (MetadataName, l), attrs, parameters)
2149 ModFlags &= ~Modifiers.PRIVATE;
2150 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
2153 public override void Accept (StructuralVisitor visitor)
2155 visitor.Visit (this);
2158 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2160 if (a.Type == pa.Conditional) {
2161 Error_ConditionalAttributeIsNotValid ();
2165 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2168 protected override bool CheckBase ()
2170 // Don't check base, destructors have special syntax
2174 public override void Emit()
2176 var base_type = Parent.PartialContainer.BaseType;
2177 if (base_type != null && Block != null) {
2178 var base_dtor = MemberCache.FindMember (base_type,
2179 new MemberFilter (MetadataName, 0, MemberKind.Destructor, null, null), BindingRestriction.InstanceOnly) as MethodSpec;
2181 if (base_dtor == null)
2182 throw new NotImplementedException ();
2184 MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
2185 method_expr.InstanceExpression = new BaseThis (base_type, Location);
2187 var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation);
2188 var finaly_block = new ExplicitBlock (block, Location, Location);
2191 // 0-size arguments to avoid CS0250 error
2192 // TODO: Should use AddScopeStatement or something else which emits correct
2195 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0))));
2197 var tf = new TryFinally (try_block, finaly_block, Location);
2198 block.WrapIntoDestructor (tf, try_block);
2204 public override string GetSignatureForError ()
2206 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
2209 protected override bool ResolveMemberType ()
2211 member_type = Compiler.BuiltinTypes.Void;
2215 public override string[] ValidAttributeTargets {
2217 return attribute_targets;
2222 // Ooouh Martin, templates are missing here.
2223 // When it will be possible move here a lot of child code and template method type.
2224 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
2225 protected MethodData method_data;
2226 protected ToplevelBlock block;
2227 protected SecurityType declarative_security;
2229 protected readonly string prefix;
2231 ReturnParameter return_attributes;
2233 public AbstractPropertyEventMethod (InterfaceMemberBase member, string prefix, Attributes attrs, Location loc)
2234 : base (member.Parent, SetupName (prefix, member, loc), attrs)
2236 this.prefix = prefix;
2239 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
2241 return new MemberName (member.MemberName.Left, prefix + member.ShortName, member.MemberName.ExplicitInterface, loc);
2244 public void UpdateName (InterfaceMemberBase member)
2246 SetMemberName (SetupName (prefix, member, Location));
2249 #region IMethodData Members
2251 public ToplevelBlock Block {
2261 public CallingConventions CallingConventions {
2263 return CallingConventions.Standard;
2267 public EmitContext CreateEmitContext (ILGenerator ig)
2269 return new EmitContext (this, ig, ReturnType);
2272 public bool IsAccessor {
2278 public bool IsExcluded ()
2283 GenericMethod IMethodData.GenericMethod {
2289 public MemberName MethodName {
2295 public TypeSpec[] ParameterTypes {
2297 return ParameterInfo.Types;
2301 public abstract ParametersCompiled ParameterInfo { get ; }
2302 public abstract TypeSpec ReturnType { get; }
2306 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2308 if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
2309 Report.Error (1667, a.Location,
2310 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
2311 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
2315 if (a.IsValidSecurityAttribute ()) {
2316 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
2320 if (a.Target == AttributeTargets.Method) {
2321 method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
2325 if (a.Target == AttributeTargets.ReturnValue) {
2326 if (return_attributes == null)
2327 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2329 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
2333 ApplyToExtraTarget (a, ctor, cdata, pa);
2336 protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2338 throw new NotSupportedException ("You forgot to define special attribute target handling");
2341 // It is not supported for the accessors
2342 public sealed override bool Define()
2344 throw new NotSupportedException ();
2347 public virtual void Emit (DeclSpace parent)
2349 method_data.Emit (parent);
2351 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
2352 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
2353 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
2354 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
2356 if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2357 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2358 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
2359 } else if (ReturnType.HasDynamicElement) {
2360 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2361 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
2364 if (OptAttributes != null)
2365 OptAttributes.Emit ();
2367 if (declarative_security != null) {
2368 foreach (var de in declarative_security) {
2370 method_data.MethodBuilder.__AddDeclarativeSecurity (de);
2372 method_data.MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2380 public override bool EnableOverloadChecks (MemberCore overload)
2382 if (overload is MethodCore) {
2383 caching_flags |= Flags.MethodOverloadsExist;
2387 // This can only happen with indexers and it will
2388 // be catched as indexer difference
2389 if (overload is AbstractPropertyEventMethod)
2395 public override string GetSignatureForDocumentation ()
2397 // should not be called
2398 throw new NotSupportedException ();
2401 public override bool IsClsComplianceRequired()
2406 public MethodSpec Spec { get; protected set; }
2409 // Represents header string for documentation comment.
2411 public override string DocCommentHeader {
2412 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
2415 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
2419 public class Operator : MethodOrOperator {
2421 const Modifiers AllowedModifiers =
2427 public enum OpType : byte {
2437 // Unary and Binary operators
2460 // Implicit and Explicit
2464 // Just because of enum
2468 public readonly OpType OperatorType;
2470 static readonly string [] [] names;
2474 names = new string[(int)OpType.TOP][];
2475 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
2476 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
2477 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
2478 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
2479 names [(int) OpType.True] = new string [] { "true", "op_True" };
2480 names [(int) OpType.False] = new string [] { "false", "op_False" };
2481 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
2482 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
2483 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
2484 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
2485 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
2486 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
2487 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
2488 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
2489 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
2490 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
2491 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
2492 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
2493 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
2494 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
2495 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
2496 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
2497 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
2498 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
2499 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
2500 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
2503 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
2504 Modifiers mod_flags, ParametersCompiled parameters,
2505 ToplevelBlock block, Attributes attrs, Location loc)
2506 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
2507 new MemberName (GetMetadataName (type), loc), attrs, parameters)
2509 OperatorType = type;
2513 public override void Accept (StructuralVisitor visitor)
2515 visitor.Visit (this);
2518 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2520 if (a.Type == pa.Conditional) {
2521 Error_ConditionalAttributeIsNotValid ();
2525 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2528 public override bool Define ()
2530 const Modifiers RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
2531 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
2532 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
2535 if (!base.Define ())
2538 if (block != null && block.IsIterator) {
2540 // Current method is turned into automatically generated
2541 // wrapper which creates an instance of iterator
2543 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
2544 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
2547 // imlicit and explicit operator of same types are not allowed
2548 if (OperatorType == OpType.Explicit)
2549 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
2550 else if (OperatorType == OpType.Implicit)
2551 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
2553 TypeSpec declaring_type = Parent.CurrentType;
2554 TypeSpec return_type = MemberType;
2555 TypeSpec first_arg_type = ParameterTypes [0];
2557 TypeSpec first_arg_type_unwrap = first_arg_type;
2558 if (first_arg_type.IsNullableType)
2559 first_arg_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (first_arg_type);
2561 TypeSpec return_type_unwrap = return_type;
2562 if (return_type.IsNullableType)
2563 return_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (return_type);
2566 // Rules for conversion operators
2568 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2569 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type) {
2570 Report.Error (555, Location,
2571 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
2576 if (declaring_type == return_type || declaring_type == return_type_unwrap) {
2577 conv_type = first_arg_type;
2578 } else if (declaring_type == first_arg_type || declaring_type == first_arg_type_unwrap) {
2579 conv_type = return_type;
2581 Report.Error (556, Location,
2582 "User-defined conversion must convert to or from the enclosing type");
2586 if (conv_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2587 Report.Error (1964, Location,
2588 "User-defined conversion `{0}' cannot convert to or from the dynamic type",
2589 GetSignatureForError ());
2594 if (conv_type.IsInterface) {
2595 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
2596 GetSignatureForError ());
2600 if (conv_type.IsClass) {
2601 if (TypeSpec.IsBaseClass (declaring_type, conv_type, true)) {
2602 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
2603 GetSignatureForError ());
2607 if (TypeSpec.IsBaseClass (conv_type, declaring_type, false)) {
2608 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
2609 GetSignatureForError ());
2613 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
2614 if (first_arg_type != declaring_type || parameters.Types[1].BuiltinType != BuiltinTypeSpec.Type.Int) {
2615 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");
2618 } else if (parameters.Count == 1) {
2619 // Checks for Unary operators
2621 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
2622 if (return_type != declaring_type && !TypeSpec.IsBaseClass (return_type, declaring_type, false)) {
2623 Report.Error (448, Location,
2624 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
2627 if (first_arg_type != declaring_type) {
2629 559, Location, "The parameter type for ++ or -- operator must be the containing type");
2634 if (first_arg_type_unwrap != declaring_type) {
2635 Report.Error (562, Location,
2636 "The parameter type of a unary operator must be the containing type");
2640 if (OperatorType == OpType.True || OperatorType == OpType.False) {
2641 if (return_type.BuiltinType != BuiltinTypeSpec.Type.Bool) {
2644 "The return type of operator True or False " +
2650 } else if (first_arg_type_unwrap != declaring_type) {
2651 // Checks for Binary operators
2653 var second_arg_type = ParameterTypes[1];
2654 if (second_arg_type.IsNullableType)
2655 second_arg_type = Nullable.NullableInfo.GetUnderlyingType (second_arg_type);
2657 if (second_arg_type != declaring_type) {
2658 Report.Error (563, Location,
2659 "One of the parameters of a binary operator must be the containing type");
2667 protected override bool ResolveMemberType ()
2669 if (!base.ResolveMemberType ())
2672 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2676 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
2678 // Operator cannot be override
2679 bestCandidate = null;
2683 public static string GetName (OpType ot)
2685 return names [(int) ot] [0];
2688 public static string GetName (string metadata_name)
2690 for (int i = 0; i < names.Length; ++i) {
2691 if (names [i] [1] == metadata_name)
2692 return names [i] [0];
2697 public static string GetMetadataName (OpType ot)
2699 return names [(int) ot] [1];
2702 public static string GetMetadataName (string name)
2704 for (int i = 0; i < names.Length; ++i) {
2705 if (names [i] [0] == name)
2706 return names [i] [1];
2711 public static OpType? GetType (string metadata_name)
2713 for (int i = 0; i < names.Length; ++i) {
2714 if (names[i][1] == metadata_name)
2721 public OpType GetMatchingOperator ()
2723 switch (OperatorType) {
2724 case OpType.Equality:
2725 return OpType.Inequality;
2726 case OpType.Inequality:
2727 return OpType.Equality;
2729 return OpType.False;
2732 case OpType.GreaterThan:
2733 return OpType.LessThan;
2734 case OpType.LessThan:
2735 return OpType.GreaterThan;
2736 case OpType.GreaterThanOrEqual:
2737 return OpType.LessThanOrEqual;
2738 case OpType.LessThanOrEqual:
2739 return OpType.GreaterThanOrEqual;
2745 public override string GetSignatureForDocumentation ()
2747 string s = base.GetSignatureForDocumentation ();
2748 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2749 s = s + "~" + ReturnType.GetSignatureForDocumentation ();
2755 public override string GetSignatureForError ()
2757 StringBuilder sb = new StringBuilder ();
2758 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2759 sb.AppendFormat ("{0}.{1} operator {2}",
2760 Parent.GetSignatureForError (), GetName (OperatorType),
2761 member_type == null ? type_expr.GetSignatureForError () : member_type.GetSignatureForError ());
2764 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
2767 sb.Append (parameters.GetSignatureForError ());
2768 return sb.ToString ();