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
15 using System.Collections.Generic;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Runtime.CompilerServices;
19 using System.Runtime.InteropServices;
20 using System.Security;
21 using System.Security.Permissions;
26 using XmlElement = System.Object;
31 using Mono.CompilerServices.SymbolWriter;
33 namespace Mono.CSharp {
35 public abstract class MethodCore : InterfaceMemberBase, IParametersMember
37 protected ParametersCompiled parameters;
38 protected ToplevelBlock block;
39 protected MethodSpec spec;
41 public MethodCore (DeclSpace parent, GenericMethod generic,
42 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
43 MemberName name, Attributes attrs, ParametersCompiled parameters)
44 : base (parent, generic, type, mod, allowed_mod, name, attrs)
46 this.parameters = parameters;
50 // Returns the System.Type array for the parameters of this method
52 public TypeSpec [] ParameterTypes {
54 return parameters.Types;
58 public ParametersCompiled ParameterInfo {
64 AParametersCollection IParametersMember.Parameters {
65 get { return parameters; }
68 public ToplevelBlock Block {
78 public CallingConventions CallingConventions {
80 CallingConventions cc = parameters.CallingConvention;
82 if ((ModFlags & Modifiers.STATIC) == 0)
83 cc |= CallingConventions.HasThis;
85 // FIXME: How is `ExplicitThis' used in C#?
91 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
93 bool res = base.CheckOverrideAgainstBase (base_member);
96 // Check that the permissions are not being changed
98 if (!CheckAccessModifiers (this, base_member)) {
99 Error_CannotChangeAccessModifiers (this, base_member);
106 protected override bool CheckBase ()
108 // Check whether arguments were correct.
109 if (!DefineParameters (parameters))
112 return base.CheckBase ();
116 // Returns a string that represents the signature for this
117 // member which should be used in XML documentation.
119 public override string GetDocCommentName (DeclSpace ds)
121 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
125 // Raised (and passed an XmlElement that contains the comment)
126 // when GenerateDocComment is writing documentation expectedly.
128 // FIXME: with a few effort, it could be done with XmlReader,
129 // that means removal of DOM use.
131 internal override void OnGenerateDocComment (XmlElement el)
133 DocUtil.OnMethodGenerateDocComment (this, el, Report);
137 // Represents header string for documentation comment.
139 public override string DocCommentHeader
144 public override bool EnableOverloadChecks (MemberCore overload)
146 if (overload is MethodCore) {
147 caching_flags |= Flags.MethodOverloadsExist;
151 if (overload is AbstractPropertyEventMethod)
154 return base.EnableOverloadChecks (overload);
157 public MethodSpec Spec {
161 protected override bool VerifyClsCompliance ()
163 if (!base.VerifyClsCompliance ())
166 if (parameters.HasArglist) {
167 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
170 if (member_type != null && !member_type.IsCLSCompliant ()) {
171 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
172 GetSignatureForError ());
175 parameters.VerifyClsCompliance (this);
180 public interface IGenericMethodDefinition : IMemberDefinition
182 TypeParameterSpec[] TypeParameters { get; }
183 int TypeParametersCount { get; }
185 // MethodInfo MakeGenericMethod (TypeSpec[] targs);
188 public class MethodSpec : MemberSpec, IParametersMember
191 AParametersCollection parameters;
195 TypeParameterSpec[] constraints;
197 public MethodSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition details, TypeSpec returnType,
198 MethodBase info, AParametersCollection parameters, Modifiers modifiers)
199 : base (kind, declaringType, details, modifiers)
201 this.metaInfo = info;
202 this.parameters = parameters;
203 this.returnType = returnType;
208 public override int Arity {
210 return IsGeneric ? GenericDefinition.TypeParametersCount : 0;
214 public TypeParameterSpec[] Constraints {
216 if (constraints == null && IsGeneric)
217 constraints = GenericDefinition.TypeParameters;
223 public bool IsConstructor {
225 return Kind == MemberKind.Constructor;
229 public IGenericMethodDefinition GenericDefinition {
231 return (IGenericMethodDefinition) definition;
235 public bool IsExtensionMethod {
237 return IsStatic && parameters.HasExtensionMethodType;
241 public bool IsSealed {
243 return (Modifiers & Modifiers.SEALED) != 0;
247 // When is virtual or abstract
248 public bool IsVirtual {
250 return (Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) != 0;
254 public bool IsReservedMethod {
256 return Kind == MemberKind.Operator || IsAccessor;
260 TypeSpec IInterfaceMemberSpec.MemberType {
266 public AParametersCollection Parameters {
272 public TypeSpec ReturnType {
278 public TypeSpec[] TypeArguments {
286 public MethodSpec GetGenericMethodDefinition ()
288 if (!IsGeneric && !DeclaringType.IsGeneric)
291 return MemberCache.GetMember (declaringType, this);
294 public MethodBase GetMetaInfo ()
296 if ((state & StateFlags.PendingMetaInflate) != 0) {
297 if (DeclaringType.IsTypeBuilder) {
299 metaInfo = TypeBuilder.GetConstructor (DeclaringType.GetMetaInfo (), (ConstructorInfo) metaInfo);
301 metaInfo = TypeBuilder.GetMethod (DeclaringType.GetMetaInfo (), (MethodInfo) metaInfo);
303 metaInfo = MethodInfo.GetMethodFromHandle (metaInfo.MethodHandle, DeclaringType.GetMetaInfo ().TypeHandle);
306 state &= ~StateFlags.PendingMetaInflate;
309 if ((state & StateFlags.PendingMakeMethod) != 0) {
310 var sre_targs = new Type[targs.Length];
311 for (int i = 0; i < sre_targs.Length; ++i)
312 sre_targs[i] = targs[i].GetMetaInfo ();
314 metaInfo = ((MethodInfo) metaInfo).MakeGenericMethod (sre_targs);
315 state &= ~StateFlags.PendingMakeMethod;
321 public override string GetSignatureForError ()
325 name = DeclaringType.GetSignatureForError () + "." + DeclaringType.Name;
326 } else if (Kind == MemberKind.Operator) {
327 var op = Operator.GetType (Name).Value;
328 if (op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) {
329 name = DeclaringType.GetSignatureForError () + "." + Operator.GetName (op) + " operator " + returnType.GetSignatureForError ();
331 name = DeclaringType.GetSignatureForError () + ".operator " + Operator.GetName (op);
333 } else if (IsAccessor) {
334 int split = Name.IndexOf ('_');
335 name = Name.Substring (split + 1);
336 var postfix = Name.Substring (0, split);
338 var pc = parameters.Count;
339 if (pc > 0 && postfix == "get") {
340 name = "this" + parameters.GetSignatureForError ("[", "]", pc);
341 } else if (pc > 1 && postfix == "set") {
342 name = "this" + parameters.GetSignatureForError ("[", "]", pc - 1);
346 return DeclaringType.GetSignatureForError () + "." + name + "." + postfix;
348 name = base.GetSignatureForError ();
350 name += "<" + TypeManager.CSharpName (targs) + ">";
352 name += "<" + TypeManager.CSharpName (GenericDefinition.TypeParameters) + ">";
355 return name + parameters.GetSignatureForError ();
358 public override MemberSpec InflateMember (TypeParameterInflator inflator)
360 var ms = (MethodSpec) base.InflateMember (inflator);
361 ms.returnType = inflator.Inflate (returnType);
362 ms.parameters = parameters.Inflate (inflator);
364 ms.constraints = TypeParameterSpec.InflateConstraints (inflator, GenericDefinition.TypeParameters);
369 public MethodSpec MakeGenericMethod (params TypeSpec[] targs)
372 throw new ArgumentNullException ();
374 // if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
377 //if (generic_intances == null)
378 // generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
380 var inflator = new TypeParameterInflator (DeclaringType, GenericDefinition.TypeParameters, targs);
382 var inflated = (MethodSpec) MemberwiseClone ();
383 inflated.declaringType = inflator.TypeInstance;
384 inflated.returnType = inflator.Inflate (returnType);
385 inflated.parameters = parameters.Inflate (inflator);
386 inflated.targs = targs;
387 inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
388 inflated.state |= StateFlags.PendingMakeMethod;
390 // if (inflated.parent == null)
391 // inflated.parent = parent;
393 //generic_intances.Add (targs, inflated);
397 public MethodSpec Mutate (TypeParameterMutator mutator)
399 var targs = TypeArguments;
401 targs = mutator.Mutate (targs);
403 var decl = DeclaringType;
404 if (DeclaringType.IsGenericOrParentIsGeneric) {
405 decl = mutator.Mutate (decl);
408 if (targs == TypeArguments && decl == DeclaringType)
411 var ms = (MethodSpec) MemberwiseClone ();
412 if (decl != DeclaringType) {
413 // Gets back MethodInfo in case of metaInfo was inflated
414 ms.metaInfo = MemberCache.GetMember (TypeParameterMutator.GetMemberDeclaringType (DeclaringType), this).metaInfo;
416 ms.declaringType = decl;
417 ms.state |= StateFlags.PendingMetaInflate;
422 ms.state |= StateFlags.PendingMakeMethod;
428 public void SetMetaInfo (MethodInfo info)
430 if (this.metaInfo != null)
431 throw new InternalErrorException ("MetaInfo reset");
433 this.metaInfo = info;
437 public abstract class MethodOrOperator : MethodCore, IMethodData
439 public MethodBuilder MethodBuilder;
440 ReturnParameter return_attributes;
441 Dictionary<SecurityAction, PermissionSet> declarative_security;
442 protected MethodData MethodData;
444 static string[] attribute_targets = new string [] { "method", "return" };
446 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, Modifiers mod,
447 Modifiers allowed_mod, MemberName name,
448 Attributes attrs, ParametersCompiled parameters)
449 : base (parent, generic, type, mod, allowed_mod, name,
454 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
456 if (a.Target == AttributeTargets.ReturnValue) {
457 if (return_attributes == null)
458 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
460 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
464 if (a.IsInternalMethodImplAttribute) {
465 is_external_implementation = true;
468 if (a.Type == pa.DllImport) {
469 const Modifiers extern_static = Modifiers.EXTERN | Modifiers.STATIC;
470 if ((ModFlags & extern_static) != extern_static) {
471 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
473 is_external_implementation = true;
476 if (a.IsValidSecurityAttribute ()) {
477 if (declarative_security == null)
478 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
479 a.ExtractSecurityPermissionSet (declarative_security);
483 if (MethodBuilder != null)
484 MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
487 public override AttributeTargets AttributeTargets {
489 return AttributeTargets.Method;
493 protected override bool CheckForDuplications ()
495 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
498 public virtual EmitContext CreateEmitContext (ILGenerator ig)
500 return new EmitContext (this, ig, MemberType);
503 public override bool Define ()
512 if (this is Operator)
513 kind = MemberKind.Operator;
514 else if (this is Destructor)
515 kind = MemberKind.Destructor;
517 kind = MemberKind.Method;
519 if (IsPartialDefinition) {
520 caching_flags &= ~Flags.Excluded_Undetected;
521 caching_flags |= Flags.Excluded;
523 // Add to member cache only when a partial method implementation has not been found yet
524 if ((caching_flags & Flags.PartialDefinitionExists) == 0) {
525 // MethodBase mb = new PartialMethodDefinitionInfo (this);
527 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, null, parameters, ModFlags);
528 Parent.MemberCache.AddMember (spec);
534 MethodData = new MethodData (
535 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
537 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName), Report))
540 MethodBuilder = MethodData.MethodBuilder;
542 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, MethodBuilder, parameters, ModFlags);
543 if (MemberName.Arity > 0)
544 spec.IsGeneric = true;
546 Parent.MemberCache.AddMember (this, MethodBuilder.Name, spec);
551 protected override void DoMemberTypeIndependentChecks ()
553 base.DoMemberTypeIndependentChecks ();
555 CheckAbstractAndExtern (block != null);
557 if ((ModFlags & Modifiers.PARTIAL) != 0) {
558 for (int i = 0; i < parameters.Count; ++i) {
559 IParameterData p = parameters.FixedParameters [i];
560 if (p.ModFlags == Parameter.Modifier.OUT) {
561 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
562 GetSignatureForError ());
565 if (p.HasDefaultValue && IsPartialImplementation)
566 ((Parameter) p).Warning_UselessOptionalParameter (Report);
571 protected override void DoMemberTypeDependentChecks ()
573 base.DoMemberTypeDependentChecks ();
575 if (MemberType.IsStatic) {
576 Error_StaticReturnType ();
580 public override void Emit ()
582 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
583 Compiler.PredefinedAttributes.CompilerGenerated.EmitAttribute (MethodBuilder);
584 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
585 Compiler.PredefinedAttributes.DebuggerHidden.EmitAttribute (MethodBuilder);
587 if (ReturnType == InternalType.Dynamic) {
588 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
589 Compiler.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
591 var trans_flags = TypeManager.HasDynamicTypeUsed (ReturnType);
592 if (trans_flags != null) {
593 var pa = Compiler.PredefinedAttributes.DynamicTransform;
594 if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
595 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
596 return_attributes.Builder.SetCustomAttribute (
597 new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
602 if (OptAttributes != null)
603 OptAttributes.Emit ();
605 if (declarative_security != null) {
606 foreach (var de in declarative_security) {
607 MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
611 if (MethodData != null)
612 MethodData.Emit (Parent);
620 protected void Error_ConditionalAttributeIsNotValid ()
622 Report.Error (577, Location,
623 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
624 GetSignatureForError ());
627 public bool IsPartialDefinition {
629 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
633 public bool IsPartialImplementation {
635 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
639 public override string[] ValidAttributeTargets {
641 return attribute_targets;
645 #region IMethodData Members
647 public TypeSpec ReturnType {
653 public MemberName MethodName {
660 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
662 public override string[] ConditionalConditions ()
664 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
667 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
668 return new string [0];
670 caching_flags &= ~Flags.Excluded_Undetected;
673 if (base_method == null) {
674 if (OptAttributes == null)
677 Attribute[] attrs = OptAttributes.SearchMulti (Compiler.PredefinedAttributes.Conditional);
681 conditions = new string[attrs.Length];
682 for (int i = 0; i < conditions.Length; ++i)
683 conditions[i] = attrs[i].GetConditionalAttributeValue ();
685 conditions = base_method.MemberDefinition.ConditionalConditions();
688 if (conditions != null)
689 caching_flags |= Flags.Excluded;
694 GenericMethod IMethodData.GenericMethod {
696 return GenericMethod;
700 public virtual void EmitExtraSymbolInfo (SourceMethod source)
707 public class SourceMethod : IMethodDef
710 SourceMethodBuilder builder;
712 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
714 this.method = method;
716 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
720 get { return method.Name; }
725 if (method is MethodBuilder)
726 return ((MethodBuilder) method).GetToken ().Token;
727 else if (method is ConstructorBuilder)
728 return ((ConstructorBuilder) method).GetToken ().Token;
730 throw new NotSupportedException ();
734 public void CloseMethod ()
736 SymbolWriter.CloseMethod ();
739 public void SetRealMethodName (string name)
742 builder.SetRealMethodName (name);
745 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
747 if (!SymbolWriter.HasSymbolWriter)
752 Location start_loc = block.StartLocation;
753 if (start_loc.IsNull)
756 ICompileUnit compile_unit = start_loc.CompilationUnit;
757 if (compile_unit == null)
760 return new SourceMethod (parent, method, compile_unit);
764 public class Method : MethodOrOperator, IGenericMethodDefinition
766 Method partialMethodImplementation;
768 public Method (DeclSpace parent, GenericMethod generic,
769 FullNamedExpression return_type, Modifiers mod,
770 MemberName name, ParametersCompiled parameters, Attributes attrs)
771 : base (parent, generic, return_type, mod,
772 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersClass :
773 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
774 AllowedModifiersClass,
775 name, attrs, parameters)
779 protected Method (DeclSpace parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
780 MemberName name, ParametersCompiled parameters, Attributes attrs)
781 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
787 public override TypeParameter[] CurrentTypeParameters {
789 if (GenericMethod != null)
790 return GenericMethod.CurrentTypeParameters;
796 public override bool HasUnresolvedConstraints {
798 if (CurrentTypeParameters == null)
801 // When overriding base method constraints are fetched from
802 // base method but to find it we have to resolve parameters
803 // to find exact base method match
804 if (IsExplicitImpl || (ModFlags & Modifiers.OVERRIDE) != 0)
805 return base_method == null;
807 // Even for non-override generic method constraints check has to be
808 // delayed after all constraints are resolved
813 public TypeParameterSpec[] TypeParameters {
816 return CurrentTypeParameters.Select (l => l.Type).ToArray ();
820 public int TypeParametersCount {
822 return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Length;
828 public override string GetSignatureForError()
830 return base.GetSignatureForError () + parameters.GetSignatureForError ();
833 void Error_DuplicateEntryPoint (Method b)
835 Report.Error (17, b.Location,
836 "Program `{0}' has more than one entry point defined: `{1}'",
837 CodeGen.FileName, b.GetSignatureForError ());
842 if (ReturnType != TypeManager.void_type &&
843 ReturnType != TypeManager.int32_type)
846 if (parameters.IsEmpty)
849 if (parameters.Count > 1)
852 var ac = parameters.Types [0] as ArrayContainer;
853 return ac != null && ac.Rank == 1 && ac.Element == TypeManager.string_type &&
854 (parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
857 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
860 TypeParameter[] tp = CurrentTypeParameters;
862 TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
864 return new TypeParameterExpr (t, loc);
868 return base.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
871 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
873 if (a.Type == pa.Conditional) {
874 if (IsExplicitImpl) {
875 Error_ConditionalAttributeIsNotValid ();
879 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
880 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
884 if (ReturnType != TypeManager.void_type) {
885 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
890 Report.Error (582, Location, "Conditional not valid on interface members");
894 if (MethodData.implementing != null) {
895 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
896 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
897 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
901 for (int i = 0; i < parameters.Count; ++i) {
902 if (parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
903 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
909 if (a.Type == pa.Extension) {
910 a.Error_MisusedExtensionAttribute ();
914 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
917 protected virtual void DefineTypeParameters ()
919 var tparams = CurrentTypeParameters;
921 TypeParameterSpec[] base_tparams = null;
922 TypeParameterSpec[] base_decl_tparams = TypeParameterSpec.EmptyTypes;
923 TypeSpec[] base_targs = TypeSpec.EmptyTypes;
924 if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
925 if (base_method != null) {
926 base_tparams = base_method.GenericDefinition.TypeParameters;
928 if (base_method.DeclaringType.IsGeneric) {
929 base_decl_tparams = base_method.DeclaringType.MemberDefinition.TypeParameters;
930 base_targs = Parent.BaseType.TypeArguments;
933 if (base_method.IsGeneric) {
934 if (base_decl_tparams.Length != 0) {
935 base_decl_tparams = base_decl_tparams.Concat (base_tparams).ToArray ();
936 base_targs = base_targs.Concat (tparams.Select<TypeParameter, TypeSpec> (l => l.Type)).ToArray ();
938 base_decl_tparams = base_tparams;
939 base_targs = tparams.Select (l => l.Type).ToArray ();
942 } else if (MethodData.implementing != null) {
943 base_tparams = MethodData.implementing.GenericDefinition.TypeParameters;
944 if (MethodData.implementing.DeclaringType.IsGeneric) {
945 base_decl_tparams = MethodData.implementing.DeclaringType.MemberDefinition.TypeParameters;
946 foreach (var iface in Parent.CurrentType.Interfaces) {
947 if (iface == MethodData.implementing.DeclaringType) {
948 base_targs = iface.TypeArguments;
956 for (int i = 0; i < tparams.Length; ++i) {
959 if (!tp.ResolveConstraints (this))
963 // Copy base constraints for override/explicit methods
965 if (base_tparams != null) {
966 var base_tparam = base_tparams[i];
967 tp.Type.SpecialConstraint = base_tparam.SpecialConstraint;
969 var inflator = new TypeParameterInflator (CurrentType, base_decl_tparams, base_targs);
970 base_tparam.InflateConstraints (inflator, tp.Type);
971 } else if (MethodData.implementing != null) {
972 var base_tp = MethodData.implementing.Constraints[i];
973 if (!tp.Type.HasSameConstraintsImplementation (base_tp)) {
974 Report.SymbolRelatedToPreviousError (MethodData.implementing);
975 Report.Error (425, Location,
976 "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",
977 tp.GetSignatureForError (), GetSignatureForError (), base_tp.GetSignatureForError (), MethodData.implementing.GetSignatureForError ());
986 public override bool Define ()
988 if (type_expr.Type == TypeManager.void_type && parameters.IsEmpty && MemberName.Arity == 0 && MemberName.Name == Destructor.MetadataName) {
989 Report.Warning (465, 1, Location, "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
995 if (partialMethodImplementation != null && IsPartialDefinition)
996 MethodBuilder = partialMethodImplementation.MethodBuilder;
998 if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
999 Error1599 (Location, ReturnType, Report);
1003 if (CurrentTypeParameters == null) {
1004 if (base_method != null) {
1005 if (parameters.Count == 1 && ParameterTypes[0] == TypeManager.object_type && Name == "Equals")
1006 Parent.PartialContainer.Mark_HasEquals ();
1007 else if (parameters.IsEmpty && Name == "GetHashCode")
1008 Parent.PartialContainer.Mark_HasGetHashCode ();
1012 DefineTypeParameters ();
1015 if (block != null && block.IsIterator) {
1017 // Current method is turned into automatically generated
1018 // wrapper which creates an instance of iterator
1020 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
1021 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
1024 if ((ModFlags & Modifiers.STATIC) == 0)
1027 if (parameters.HasExtensionMethodType) {
1028 if (Parent.PartialContainer.IsStatic && !Parent.IsGeneric) {
1029 if (!Parent.IsTopLevel)
1030 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
1031 GetSignatureForError ());
1033 PredefinedAttribute pa = Compiler.PredefinedAttributes.Extension;
1034 if (!pa.IsDefined) {
1035 Report.Error (1110, Location,
1036 "`{0}': Extension methods cannot be declared without a reference to System.Core.dll assembly. Add the assembly reference or remove `this' modifer from the first parameter",
1037 GetSignatureForError ());
1040 ModFlags |= Modifiers.METHOD_EXTENSION;
1041 Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
1042 Spec.DeclaringType.SetExtensionMethodContainer ();
1043 CodeGen.Assembly.HasExtensionMethods = true;
1045 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
1046 GetSignatureForError ());
1051 // This is used to track the Entry Point,
1053 if (RootContext.NeedsEntryPoint &&
1055 (RootContext.MainClass == null ||
1056 RootContext.MainClass == Parent.TypeBuilder.FullName)){
1057 if (IsEntryPoint ()) {
1059 if (RootContext.EntryPoint == null) {
1060 if (Parent.IsGeneric || MemberName.IsGeneric) {
1061 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
1062 GetSignatureForError ());
1065 RootContext.EntryPoint = this;
1068 Error_DuplicateEntryPoint (RootContext.EntryPoint);
1069 Error_DuplicateEntryPoint (this);
1072 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
1073 GetSignatureForError ());
1083 public override void Emit ()
1086 if (IsPartialDefinition) {
1088 // Use partial method implementation builder for partial method declaration attributes
1090 if (partialMethodImplementation != null) {
1091 MethodBuilder = partialMethodImplementation.MethodBuilder;
1097 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
1098 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
1099 GetSignatureForError ());
1102 if (CurrentTypeParameters != null) {
1103 var ge = type_expr as GenericTypeExpr;
1105 ge.CheckConstraints (this);
1107 foreach (Parameter p in parameters.FixedParameters) {
1108 ge = p.TypeExpression as GenericTypeExpr;
1110 ge.CheckConstraints (this);
1113 for (int i = 0; i < CurrentTypeParameters.Length; ++i) {
1114 var tp = CurrentTypeParameters [i];
1115 tp.CheckGenericConstraints ();
1122 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
1123 Compiler.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
1125 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
1126 Location, MethodBuilder);
1131 public override bool EnableOverloadChecks (MemberCore overload)
1133 // TODO: It can be deleted when members will be defined in correct order
1134 if (overload is Operator)
1135 return overload.EnableOverloadChecks (this);
1137 if (overload is Indexer)
1140 return base.EnableOverloadChecks (overload);
1143 public static void Error1599 (Location loc, TypeSpec t, Report Report)
1145 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
1148 protected override bool ResolveMemberType ()
1150 if (GenericMethod != null) {
1151 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
1152 if (!GenericMethod.Define (this))
1156 return base.ResolveMemberType ();
1159 public void SetPartialDefinition (Method methodDefinition)
1161 caching_flags |= Flags.PartialDefinitionExists;
1162 methodDefinition.partialMethodImplementation = this;
1164 // Ensure we are always using method declaration parameters
1165 for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
1166 parameters [i].Name = methodDefinition.parameters [i].Name;
1167 parameters [i].DefaultValue = methodDefinition.parameters [i].DefaultValue;
1170 if (methodDefinition.attributes == null)
1173 if (attributes == null) {
1174 attributes = methodDefinition.attributes;
1176 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
1181 public abstract class ConstructorInitializer : ExpressionStatement
1183 Arguments argument_list;
1184 MethodSpec base_ctor;
1186 public ConstructorInitializer (Arguments argument_list, Location loc)
1188 this.argument_list = argument_list;
1192 public Arguments Arguments {
1194 return argument_list;
1198 public override Expression CreateExpressionTree (ResolveContext ec)
1200 throw new NotSupportedException ("ET");
1203 protected override Expression DoResolve (ResolveContext ec)
1205 eclass = ExprClass.Value;
1208 var caller_builder = (Constructor) ec.MemberContext;
1210 if (argument_list != null) {
1214 // Spec mandates that constructor initializer will not have `this' access
1216 using (ec.Set (ResolveContext.Options.BaseInitializer)) {
1217 argument_list.Resolve (ec, out dynamic);
1221 ec.Report.Error (1975, loc,
1222 "The constructor call cannot be dynamically dispatched within constructor initializer");
1228 type = ec.CurrentType;
1229 if (this is ConstructorBaseInitializer) {
1230 if (ec.CurrentType.BaseType == null)
1233 type = ec.CurrentType.BaseType;
1234 if (ec.CurrentType.IsStruct) {
1235 ec.Report.Error (522, loc,
1236 "`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
1241 // It is legal to have "this" initializers that take no arguments
1242 // in structs, they are just no-ops.
1244 // struct D { public D (int a) : this () {}
1246 if (TypeManager.IsStruct (ec.CurrentType) && argument_list == null)
1250 base_ctor = ConstructorLookup (ec, type, ref argument_list, loc);
1252 // TODO MemberCache: Does it work for inflated types ?
1253 if (base_ctor == caller_builder.Spec){
1254 ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
1255 caller_builder.GetSignatureForError ());
1261 public override void Emit (EmitContext ec)
1263 // It can be null for static initializers
1264 if (base_ctor == null)
1269 Invocation.EmitCall (ec, new CompilerGeneratedThis (type, loc), base_ctor, argument_list, loc);
1272 public override void EmitStatement (EmitContext ec)
1278 public class ConstructorBaseInitializer : ConstructorInitializer {
1279 public ConstructorBaseInitializer (Arguments argument_list, Location l) :
1280 base (argument_list, l)
1285 class GeneratedBaseInitializer: ConstructorBaseInitializer {
1286 public GeneratedBaseInitializer (Location loc):
1292 public class ConstructorThisInitializer : ConstructorInitializer {
1293 public ConstructorThisInitializer (Arguments argument_list, Location l) :
1294 base (argument_list, l)
1299 public class Constructor : MethodCore, IMethodData {
1300 public ConstructorBuilder ConstructorBuilder;
1301 public ConstructorInitializer Initializer;
1302 Dictionary<SecurityAction, PermissionSet> declarative_security;
1303 bool has_compliant_args;
1306 // Modifiers allowed for a constructor.
1308 public const Modifiers AllowedModifiers =
1310 Modifiers.PROTECTED |
1311 Modifiers.INTERNAL |
1317 static readonly string[] attribute_targets = new string [] { "method" };
1320 // The spec claims that static is not permitted, but
1321 // my very own code has static constructors.
1323 public Constructor (DeclSpace parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args,
1324 ConstructorInitializer init, Location loc)
1325 : base (parent, null, null, mod, AllowedModifiers,
1326 new MemberName (name, loc), attrs, args)
1331 public bool HasCompliantArgs {
1332 get { return has_compliant_args; }
1335 public override AttributeTargets AttributeTargets {
1336 get { return AttributeTargets.Constructor; }
1340 // Returns true if this is a default constructor
1342 public bool IsDefault ()
1344 if ((ModFlags & Modifiers.STATIC) != 0)
1345 return parameters.IsEmpty;
1347 return parameters.IsEmpty &&
1348 (Initializer is ConstructorBaseInitializer) &&
1349 (Initializer.Arguments == null);
1352 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1354 if (a.IsValidSecurityAttribute ()) {
1355 if (declarative_security == null) {
1356 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
1358 a.ExtractSecurityPermissionSet (declarative_security);
1362 if (a.IsInternalMethodImplAttribute) {
1363 is_external_implementation = true;
1366 ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1369 protected override bool CheckBase ()
1371 if ((ModFlags & Modifiers.STATIC) != 0) {
1372 if (!parameters.IsEmpty) {
1373 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
1374 GetSignatureForError ());
1378 // the rest can be ignored
1382 // Check whether arguments were correct.
1383 if (!DefineParameters (parameters))
1386 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1387 Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1389 if (Parent.PartialContainer.Kind == MemberKind.Struct && parameters.IsEmpty) {
1390 Report.Error (568, Location,
1391 "Structs cannot contain explicit parameterless constructors");
1395 CheckProtectedModifier ();
1401 // Creates the ConstructorBuilder
1403 public override bool Define ()
1405 if (ConstructorBuilder != null)
1408 var ca = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
1410 if ((ModFlags & Modifiers.STATIC) != 0) {
1411 ca |= MethodAttributes.Static | MethodAttributes.Private;
1413 ca |= ModifiersExtensions.MethodAttr (ModFlags);
1416 if (!CheckAbstractAndExtern (block != null))
1419 // Check if arguments were correct.
1423 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
1424 ca, CallingConventions,
1425 parameters.GetMetaInfo ());
1427 spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, TypeManager.void_type, ConstructorBuilder, parameters, ModFlags);
1429 Parent.MemberCache.AddMember (spec);
1431 // It's here only to report an error
1432 if (block != null && block.IsIterator) {
1433 member_type = TypeManager.void_type;
1434 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
1443 public override void Emit ()
1445 if (Parent.PartialContainer.IsComImport) {
1446 if (!IsDefault ()) {
1447 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
1448 Parent.GetSignatureForError ());
1450 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
1453 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
1454 Compiler.PredefinedAttributes.DebuggerHidden.EmitAttribute (ConstructorBuilder);
1456 if (OptAttributes != null)
1457 OptAttributes.Emit ();
1462 // If we use a "this (...)" constructor initializer, then
1463 // do not emit field initializers, they are initialized in the other constructor
1465 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
1466 !(Initializer is ConstructorThisInitializer);
1468 BlockContext bc = new BlockContext (this, block, TypeManager.void_type);
1469 bc.Set (ResolveContext.Options.ConstructorScope);
1471 if (emit_field_initializers)
1472 Parent.PartialContainer.ResolveFieldInitializers (bc);
1474 if (block != null) {
1475 // If this is a non-static `struct' constructor and doesn't have any
1476 // initializer, it must initialize all of the struct's fields.
1477 if ((Parent.PartialContainer.Kind == MemberKind.Struct) &&
1478 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
1479 block.AddThisVariable (bc, Parent, Location);
1481 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
1482 if (Parent.PartialContainer.Kind == MemberKind.Class && Initializer == null)
1483 Initializer = new GeneratedBaseInitializer (Location);
1485 if (Initializer != null) {
1486 block.AddScopeStatement (new StatementExpression (Initializer));
1491 parameters.ApplyAttributes (this, ConstructorBuilder);
1493 SourceMethod source = SourceMethod.Create (Parent, ConstructorBuilder, block);
1495 if (block != null) {
1496 if (block.Resolve (null, bc, this)) {
1497 EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType);
1498 ec.With (EmitContext.Options.ConstructorScope, true);
1500 if (!ec.HasReturnLabel && bc.HasReturnLabel) {
1501 ec.ReturnLabel = bc.ReturnLabel;
1502 ec.HasReturnLabel = true;
1510 source.CloseMethod ();
1512 if (declarative_security != null) {
1513 foreach (var de in declarative_security) {
1514 ConstructorBuilder.AddDeclarativeSecurity (de.Key, de.Value);
1521 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate)
1523 // Is never override
1524 bestCandidate = null;
1528 public override string GetSignatureForError()
1530 return base.GetSignatureForError () + parameters.GetSignatureForError ();
1533 public override string[] ValidAttributeTargets {
1535 return attribute_targets;
1539 protected override bool VerifyClsCompliance ()
1541 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
1545 if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
1546 foreach (TypeSpec param in parameters.Types) {
1547 if (param.IsArray) {
1553 has_compliant_args = true;
1557 #region IMethodData Members
1559 public MemberName MethodName {
1565 public TypeSpec ReturnType {
1571 public EmitContext CreateEmitContext (ILGenerator ig)
1573 throw new NotImplementedException ();
1576 public bool IsExcluded()
1581 GenericMethod IMethodData.GenericMethod {
1587 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
1594 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
1596 public interface IMethodData
1598 CallingConventions CallingConventions { get; }
1599 Location Location { get; }
1600 MemberName MethodName { get; }
1601 TypeSpec ReturnType { get; }
1602 GenericMethod GenericMethod { get; }
1603 ParametersCompiled ParameterInfo { get; }
1604 MethodSpec Spec { get; }
1606 Attributes OptAttributes { get; }
1607 ToplevelBlock Block { get; set; }
1609 EmitContext CreateEmitContext (ILGenerator ig);
1610 string GetSignatureForError ();
1611 void EmitExtraSymbolInfo (SourceMethod source);
1615 // Encapsulates most of the Method's state
1617 public class MethodData {
1618 static FieldInfo methodbuilder_attrs_field;
1619 public readonly IMethodData method;
1621 public readonly GenericMethod GenericMethod;
1624 // Are we implementing an interface ?
1626 public MethodSpec implementing;
1631 protected InterfaceMemberBase member;
1632 protected Modifiers modifiers;
1633 protected MethodAttributes flags;
1634 protected TypeSpec declaring_type;
1635 protected MethodSpec parent_method;
1637 MethodBuilder builder;
1638 public MethodBuilder MethodBuilder {
1644 public TypeSpec DeclaringType {
1646 return declaring_type;
1650 public MethodData (InterfaceMemberBase member,
1651 Modifiers modifiers, MethodAttributes flags, IMethodData method)
1653 this.member = member;
1654 this.modifiers = modifiers;
1657 this.method = method;
1660 public MethodData (InterfaceMemberBase member,
1661 Modifiers modifiers, MethodAttributes flags,
1662 IMethodData method, MethodBuilder builder,
1663 GenericMethod generic, MethodSpec parent_method)
1664 : this (member, modifiers, flags, method)
1666 this.builder = builder;
1667 this.GenericMethod = generic;
1668 this.parent_method = parent_method;
1671 public bool Define (DeclSpace parent, string method_full_name, Report Report)
1673 TypeContainer container = parent.PartialContainer;
1675 PendingImplementation pending = container.PendingImplementations;
1676 if (pending != null){
1677 implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this);
1679 if (member.InterfaceType != null){
1680 if (implementing == null){
1681 if (member is PropertyBase) {
1682 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
1683 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
1684 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
1687 Report.Error (539, method.Location,
1688 "`{0}.{1}' in explicit interface declaration is not a member of interface",
1689 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
1693 if (implementing.IsAccessor && !(method is AbstractPropertyEventMethod)) {
1694 Report.SymbolRelatedToPreviousError (implementing);
1695 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
1696 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1700 if (implementing != null) {
1701 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
1702 if (prop_method == null) {
1703 if (implementing.IsAccessor) {
1704 Report.SymbolRelatedToPreviousError (implementing);
1705 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}'",
1706 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1708 } else if (implementing.DeclaringType.IsInterface) {
1709 if (!implementing.IsAccessor) {
1710 Report.SymbolRelatedToPreviousError (implementing);
1711 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
1712 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
1714 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
1715 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
1716 Report.SymbolRelatedToPreviousError (implementing);
1717 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
1718 method.GetSignatureForError (), implementing.GetSignatureForError ());
1727 // For implicit implementations, make sure we are public, for
1728 // explicit implementations, make sure we are private.
1730 if (implementing != null){
1732 // Setting null inside this block will trigger a more
1733 // verbose error reporting for missing interface implementations
1735 // The "candidate" function has been flagged already
1736 // but it wont get cleared
1738 if (member.IsExplicitImpl){
1739 if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
1740 Report.SymbolRelatedToPreviousError (implementing);
1741 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
1742 method.GetSignatureForError ());
1745 if (implementing.DeclaringType.IsInterface) {
1747 // If this is an interface method implementation,
1748 // check for public accessibility
1750 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
1752 implementing = null;
1754 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
1755 // We may never be private.
1756 implementing = null;
1758 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
1760 // We may be protected if we're overriding something.
1762 implementing = null;
1767 // Static is not allowed
1769 if ((modifiers & Modifiers.STATIC) != 0){
1770 implementing = null;
1775 // If implementing is still valid, set flags
1777 if (implementing != null){
1779 // When implementing interface methods, set NewSlot
1780 // unless, we are overwriting a method.
1782 if (implementing.DeclaringType.IsInterface){
1783 if ((modifiers & Modifiers.OVERRIDE) == 0)
1784 flags |= MethodAttributes.NewSlot;
1787 flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;
1789 // Set Final unless we're virtual, abstract or already overriding a method.
1790 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
1791 flags |= MethodAttributes.Final;
1794 // clear the pending implementation flag (requires explicit methods to be defined first)
1796 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName,
1797 member.InterfaceType, this, member.IsExplicitImpl);
1800 // Update indexer accessor name to match implementing abstract accessor
1802 if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
1803 method_full_name = implementing.MemberDefinition.Name;
1806 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
1808 if (builder == null)
1811 // if (container.CurrentType != null)
1812 // declaring_type = container.CurrentType;
1814 declaring_type = container.Definition;
1816 if (implementing != null && member.IsExplicitImpl) {
1817 container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
1825 /// Create the MethodBuilder for the method
1827 void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
1829 var return_type = method.ReturnType.GetMetaInfo ();
1830 var p_types = param.GetMetaInfo ();
1832 if (builder == null) {
1833 builder = container.TypeBuilder.DefineMethod (
1834 method_name, flags, method.CallingConventions,
1835 return_type, p_types);
1840 // Generic method has been already defined to resolve method parameters
1841 // correctly when they use type parameters
1843 builder.SetParameters (p_types);
1844 builder.SetReturnType (return_type);
1845 if (builder.Attributes != flags) {
1847 if (methodbuilder_attrs_field == null)
1848 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
1849 methodbuilder_attrs_field.SetValue (builder, flags);
1851 container.Compiler.Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
1859 public void Emit (DeclSpace parent)
1861 if (GenericMethod != null)
1862 GenericMethod.EmitAttributes ();
1864 var mc = (IMemberContext) method;
1866 method.ParameterInfo.ApplyAttributes (mc, MethodBuilder);
1868 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
1870 ToplevelBlock block = method.Block;
1871 if (block != null) {
1872 BlockContext bc = new BlockContext (mc, block, method.ReturnType);
1873 if (block.Resolve (null, bc, method)) {
1874 EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator ());
1875 if (!ec.HasReturnLabel && bc.HasReturnLabel) {
1876 ec.ReturnLabel = bc.ReturnLabel;
1877 ec.HasReturnLabel = true;
1884 if (source != null) {
1885 method.EmitExtraSymbolInfo (source);
1886 source.CloseMethod ();
1891 public class Destructor : MethodOrOperator
1893 const Modifiers AllowedModifiers =
1897 static readonly string[] attribute_targets = new string [] { "method" };
1899 public static readonly string MetadataName = "Finalize";
1901 public Destructor (DeclSpace parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
1902 : base (parent, null, null, mod, AllowedModifiers,
1903 new MemberName (MetadataName, l), attrs, parameters)
1905 ModFlags &= ~Modifiers.PRIVATE;
1906 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
1909 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1911 if (a.Type == pa.Conditional) {
1912 Error_ConditionalAttributeIsNotValid ();
1916 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1919 protected override bool CheckBase ()
1921 // Don't check base, destructors have special syntax
1925 public override void Emit()
1927 var base_type = Parent.PartialContainer.BaseType;
1928 if (base_type != null && Block != null) {
1929 var base_dtor = MemberCache.FindMember (base_type,
1930 new MemberFilter (MetadataName, 0, MemberKind.Destructor, null, null), BindingRestriction.InstanceOnly) as MethodSpec;
1932 if (base_dtor == null)
1933 throw new NotImplementedException ();
1935 MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
1936 method_expr.InstanceExpression = new BaseThis (base_type, Location);
1938 var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation);
1939 var finaly_block = new ExplicitBlock (block, Location, Location);
1942 // 0-size arguments to avoid CS0250 error
1943 // TODO: Should use AddScopeStatement or something else which emits correct
1946 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0))));
1948 var tf = new TryFinally (try_block, finaly_block, Location);
1949 block.WrapIntoDestructor (tf, try_block);
1955 public override string GetSignatureForError ()
1957 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
1960 protected override bool ResolveMemberType ()
1962 member_type = TypeManager.void_type;
1966 public override string[] ValidAttributeTargets {
1968 return attribute_targets;
1973 // Ooouh Martin, templates are missing here.
1974 // When it will be possible move here a lot of child code and template method type.
1975 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
1976 protected MethodData method_data;
1977 protected ToplevelBlock block;
1978 protected Dictionary<SecurityAction, PermissionSet> declarative_security;
1980 protected readonly string prefix;
1982 ReturnParameter return_attributes;
1984 public AbstractPropertyEventMethod (InterfaceMemberBase member, string prefix, Attributes attrs, Location loc)
1985 : base (member.Parent, SetupName (prefix, member, loc), attrs)
1987 this.prefix = prefix;
1990 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
1992 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
1995 public void UpdateName (InterfaceMemberBase member)
1997 SetMemberName (SetupName (prefix, member, Location));
2000 #region IMethodData Members
2002 public ToplevelBlock Block {
2012 public CallingConventions CallingConventions {
2014 return CallingConventions.Standard;
2018 public EmitContext CreateEmitContext (ILGenerator ig)
2020 return new EmitContext (this, ig, ReturnType);
2023 public bool IsExcluded ()
2028 GenericMethod IMethodData.GenericMethod {
2034 public MemberName MethodName {
2040 public TypeSpec[] ParameterTypes {
2042 return ParameterInfo.Types;
2046 public abstract ParametersCompiled ParameterInfo { get ; }
2047 public abstract TypeSpec ReturnType { get; }
2051 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2053 if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
2054 Report.Error (1667, a.Location,
2055 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
2056 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
2060 if (a.IsValidSecurityAttribute ()) {
2061 if (declarative_security == null)
2062 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
2063 a.ExtractSecurityPermissionSet (declarative_security);
2067 if (a.Target == AttributeTargets.Method) {
2068 method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
2072 if (a.Target == AttributeTargets.ReturnValue) {
2073 if (return_attributes == null)
2074 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2076 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
2080 ApplyToExtraTarget (a, ctor, cdata, pa);
2083 protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2085 throw new NotSupportedException ("You forgot to define special attribute target handling");
2088 // It is not supported for the accessors
2089 public sealed override bool Define()
2091 throw new NotSupportedException ();
2094 public virtual void Emit (DeclSpace parent)
2096 method_data.Emit (parent);
2098 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
2099 Compiler.PredefinedAttributes.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
2100 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
2101 Compiler.PredefinedAttributes.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
2103 if (ReturnType == InternalType.Dynamic) {
2104 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2105 Compiler.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
2107 var trans_flags = TypeManager.HasDynamicTypeUsed (ReturnType);
2108 if (trans_flags != null) {
2109 var pa = Compiler.PredefinedAttributes.DynamicTransform;
2110 if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
2111 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2112 return_attributes.Builder.SetCustomAttribute (
2113 new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
2118 if (OptAttributes != null)
2119 OptAttributes.Emit ();
2121 if (declarative_security != null) {
2122 foreach (var de in declarative_security) {
2123 method_data.MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2130 public override bool EnableOverloadChecks (MemberCore overload)
2132 if (overload is MethodCore) {
2133 caching_flags |= Flags.MethodOverloadsExist;
2137 // This can only happen with indexers and it will
2138 // be catched as indexer difference
2139 if (overload is AbstractPropertyEventMethod)
2145 public override bool IsClsComplianceRequired()
2150 public MethodSpec Spec { get; protected set; }
2153 // Represents header string for documentation comment.
2155 public override string DocCommentHeader {
2156 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
2159 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
2163 public class Operator : MethodOrOperator {
2165 const Modifiers AllowedModifiers =
2171 public enum OpType : byte {
2181 // Unary and Binary operators
2204 // Implicit and Explicit
2208 // Just because of enum
2212 public readonly OpType OperatorType;
2214 static readonly string [] [] names;
2218 names = new string[(int)OpType.TOP][];
2219 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
2220 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
2221 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
2222 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
2223 names [(int) OpType.True] = new string [] { "true", "op_True" };
2224 names [(int) OpType.False] = new string [] { "false", "op_False" };
2225 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
2226 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
2227 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
2228 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
2229 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
2230 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
2231 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
2232 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
2233 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
2234 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
2235 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
2236 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
2237 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
2238 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
2239 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
2240 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
2241 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
2242 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
2243 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
2244 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
2247 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
2248 Modifiers mod_flags, ParametersCompiled parameters,
2249 ToplevelBlock block, Attributes attrs, Location loc)
2250 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
2251 new MemberName (GetMetadataName (type), loc), attrs, parameters)
2253 OperatorType = type;
2257 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2259 if (a.Type == pa.Conditional) {
2260 Error_ConditionalAttributeIsNotValid ();
2264 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2267 public override bool Define ()
2269 const Modifiers RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
2270 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
2271 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
2274 if (!base.Define ())
2277 if (block != null && block.IsIterator) {
2279 // Current method is turned into automatically generated
2280 // wrapper which creates an instance of iterator
2282 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
2283 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
2286 // imlicit and explicit operator of same types are not allowed
2287 if (OperatorType == OpType.Explicit)
2288 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
2289 else if (OperatorType == OpType.Implicit)
2290 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
2292 TypeSpec declaring_type = Parent.CurrentType;
2293 TypeSpec return_type = MemberType;
2294 TypeSpec first_arg_type = ParameterTypes [0];
2296 TypeSpec first_arg_type_unwrap = first_arg_type;
2297 if (TypeManager.IsNullableType (first_arg_type))
2298 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
2300 TypeSpec return_type_unwrap = return_type;
2301 if (TypeManager.IsNullableType (return_type))
2302 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
2305 // Rules for conversion operators
2307 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2308 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type) {
2309 Report.Error (555, Location,
2310 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
2315 if (declaring_type == return_type || declaring_type == return_type_unwrap) {
2316 conv_type = first_arg_type;
2317 } else if (declaring_type == first_arg_type || declaring_type == first_arg_type_unwrap) {
2318 conv_type = return_type;
2320 Report.Error (556, Location,
2321 "User-defined conversion must convert to or from the enclosing type");
2325 if (conv_type == InternalType.Dynamic) {
2326 Report.Error (1964, Location,
2327 "User-defined conversion `{0}' cannot convert to or from the dynamic type",
2328 GetSignatureForError ());
2333 if (conv_type.IsInterface) {
2334 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
2335 GetSignatureForError ());
2339 if (conv_type.IsClass) {
2340 if (TypeSpec.IsBaseClass (declaring_type, conv_type, true)) {
2341 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
2342 GetSignatureForError ());
2346 if (TypeSpec.IsBaseClass (conv_type, declaring_type, false)) {
2347 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
2348 GetSignatureForError ());
2352 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
2353 if (first_arg_type != declaring_type || parameters.Types[1] != TypeManager.int32_type) {
2354 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");
2357 } else if (parameters.Count == 1) {
2358 // Checks for Unary operators
2360 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
2361 if (return_type != declaring_type && !TypeSpec.IsBaseClass (return_type, declaring_type, false)) {
2362 Report.Error (448, Location,
2363 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
2366 if (first_arg_type != declaring_type) {
2368 559, Location, "The parameter type for ++ or -- operator must be the containing type");
2373 if (first_arg_type_unwrap != declaring_type) {
2374 Report.Error (562, Location,
2375 "The parameter type of a unary operator must be the containing type");
2379 if (OperatorType == OpType.True || OperatorType == OpType.False) {
2380 if (return_type != TypeManager.bool_type) {
2383 "The return type of operator True or False " +
2389 } else if (first_arg_type_unwrap != declaring_type) {
2390 // Checks for Binary operators
2392 var second_arg_type = ParameterTypes[1];
2393 if (TypeManager.IsNullableType (second_arg_type))
2394 second_arg_type = TypeManager.GetTypeArguments (second_arg_type)[0];
2396 if (second_arg_type != declaring_type) {
2397 Report.Error (563, Location,
2398 "One of the parameters of a binary operator must be the containing type");
2406 protected override bool ResolveMemberType ()
2408 if (!base.ResolveMemberType ())
2411 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2415 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate)
2417 // Operator cannot be override
2418 bestCandidate = null;
2422 public static string GetName (OpType ot)
2424 return names [(int) ot] [0];
2427 public static string GetName (string metadata_name)
2429 for (int i = 0; i < names.Length; ++i) {
2430 if (names [i] [1] == metadata_name)
2431 return names [i] [0];
2436 public static string GetMetadataName (OpType ot)
2438 return names [(int) ot] [1];
2441 public static string GetMetadataName (string name)
2443 for (int i = 0; i < names.Length; ++i) {
2444 if (names [i] [0] == name)
2445 return names [i] [1];
2450 public static OpType? GetType (string metadata_name)
2452 for (int i = 0; i < names.Length; ++i) {
2453 if (names[i][1] == metadata_name)
2460 public OpType GetMatchingOperator ()
2462 switch (OperatorType) {
2463 case OpType.Equality:
2464 return OpType.Inequality;
2465 case OpType.Inequality:
2466 return OpType.Equality;
2468 return OpType.False;
2471 case OpType.GreaterThan:
2472 return OpType.LessThan;
2473 case OpType.LessThan:
2474 return OpType.GreaterThan;
2475 case OpType.GreaterThanOrEqual:
2476 return OpType.LessThanOrEqual;
2477 case OpType.LessThanOrEqual:
2478 return OpType.GreaterThanOrEqual;
2484 public override string GetSignatureForError ()
2486 StringBuilder sb = new StringBuilder ();
2487 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2488 sb.AppendFormat ("{0}.{1} operator {2}",
2489 Parent.GetSignatureForError (), GetName (OperatorType), type_expr.GetSignatureForError ());
2492 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
2495 sb.Append (parameters.GetSignatureForError ());
2496 return sb.ToString ();