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.Security;
17 using System.Security.Permissions;
22 using XmlElement = System.Object;
28 using MetaType = IKVM.Reflection.Type;
29 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
30 using IKVM.Reflection;
31 using IKVM.Reflection.Emit;
33 using MetaType = System.Type;
34 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
35 using System.Reflection;
36 using System.Reflection.Emit;
39 using Mono.CompilerServices.SymbolWriter;
41 namespace Mono.CSharp {
43 public abstract class MethodCore : InterfaceMemberBase, IParametersMember
45 protected ParametersCompiled parameters;
46 protected ToplevelBlock block;
47 protected MethodSpec spec;
49 public MethodCore (DeclSpace parent, GenericMethod generic,
50 FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
51 MemberName name, Attributes attrs, ParametersCompiled parameters)
52 : base (parent, generic, type, mod, allowed_mod, name, attrs)
54 this.parameters = parameters;
58 // Returns the System.Type array for the parameters of this method
60 public TypeSpec [] ParameterTypes {
62 return parameters.Types;
66 public ParametersCompiled ParameterInfo {
72 AParametersCollection IParametersMember.Parameters {
73 get { return parameters; }
76 public ToplevelBlock Block {
86 public CallingConventions CallingConventions {
88 CallingConventions cc = parameters.CallingConvention;
90 if ((ModFlags & Modifiers.STATIC) == 0)
91 cc |= CallingConventions.HasThis;
93 // FIXME: How is `ExplicitThis' used in C#?
99 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
101 bool res = base.CheckOverrideAgainstBase (base_member);
104 // Check that the permissions are not being changed
106 if (!CheckAccessModifiers (this, base_member)) {
107 Error_CannotChangeAccessModifiers (this, base_member);
114 protected override bool CheckBase ()
116 // Check whether arguments were correct.
117 if (!DefineParameters (parameters))
120 return base.CheckBase ();
124 // Returns a string that represents the signature for this
125 // member which should be used in XML documentation.
127 public override string GetDocCommentName (DeclSpace ds)
129 return DocUtil.GetMethodDocCommentName (this, parameters, ds);
133 // Raised (and passed an XmlElement that contains the comment)
134 // when GenerateDocComment is writing documentation expectedly.
136 // FIXME: with a few effort, it could be done with XmlReader,
137 // that means removal of DOM use.
139 internal override void OnGenerateDocComment (XmlElement el)
141 DocUtil.OnMethodGenerateDocComment (this, el, Report);
145 // Represents header string for documentation comment.
147 public override string DocCommentHeader
152 public override bool EnableOverloadChecks (MemberCore overload)
154 if (overload is MethodCore) {
155 caching_flags |= Flags.MethodOverloadsExist;
159 if (overload is AbstractPropertyEventMethod)
162 return base.EnableOverloadChecks (overload);
165 public MethodSpec Spec {
169 protected override bool VerifyClsCompliance ()
171 if (!base.VerifyClsCompliance ())
174 if (parameters.HasArglist) {
175 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
178 if (member_type != null && !member_type.IsCLSCompliant ()) {
179 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
180 GetSignatureForError ());
183 parameters.VerifyClsCompliance (this);
188 public interface IGenericMethodDefinition : IMemberDefinition
190 TypeParameterSpec[] TypeParameters { get; }
191 int TypeParametersCount { get; }
193 // MethodInfo MakeGenericMethod (TypeSpec[] targs);
196 public class MethodSpec : MemberSpec, IParametersMember
199 AParametersCollection parameters;
203 TypeParameterSpec[] constraints;
205 public MethodSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition details, TypeSpec returnType,
206 MethodBase info, AParametersCollection parameters, Modifiers modifiers)
207 : base (kind, declaringType, details, modifiers)
209 this.metaInfo = info;
210 this.parameters = parameters;
211 this.returnType = returnType;
216 public override int Arity {
218 return IsGeneric ? GenericDefinition.TypeParametersCount : 0;
222 public TypeParameterSpec[] Constraints {
224 if (constraints == null && IsGeneric)
225 constraints = GenericDefinition.TypeParameters;
231 public bool IsConstructor {
233 return Kind == MemberKind.Constructor;
237 public IGenericMethodDefinition GenericDefinition {
239 return (IGenericMethodDefinition) definition;
243 public bool IsExtensionMethod {
245 return IsStatic && parameters.HasExtensionMethodType;
249 public bool IsSealed {
251 return (Modifiers & Modifiers.SEALED) != 0;
255 // When is virtual or abstract
256 public bool IsVirtual {
258 return (Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) != 0;
262 public bool IsReservedMethod {
264 return Kind == MemberKind.Operator || IsAccessor;
268 TypeSpec IInterfaceMemberSpec.MemberType {
274 public AParametersCollection Parameters {
280 public TypeSpec ReturnType {
286 public TypeSpec[] TypeArguments {
294 public MethodSpec GetGenericMethodDefinition ()
296 if (!IsGeneric && !DeclaringType.IsGeneric)
299 return MemberCache.GetMember (declaringType, this);
302 public MethodBase GetMetaInfo ()
304 if ((state & StateFlags.PendingMetaInflate) != 0) {
305 if (DeclaringType.IsTypeBuilder) {
307 metaInfo = TypeBuilder.GetConstructor (DeclaringType.GetMetaInfo (), (ConstructorInfo) metaInfo);
309 metaInfo = TypeBuilder.GetMethod (DeclaringType.GetMetaInfo (), (MethodInfo) metaInfo);
312 // it should not be reached
313 throw new NotImplementedException ();
315 metaInfo = MethodInfo.GetMethodFromHandle (metaInfo.MethodHandle, DeclaringType.GetMetaInfo ().TypeHandle);
319 state &= ~StateFlags.PendingMetaInflate;
322 if ((state & StateFlags.PendingMakeMethod) != 0) {
323 var sre_targs = new MetaType[targs.Length];
324 for (int i = 0; i < sre_targs.Length; ++i)
325 sre_targs[i] = targs[i].GetMetaInfo ();
327 metaInfo = ((MethodInfo) metaInfo).MakeGenericMethod (sre_targs);
328 state &= ~StateFlags.PendingMakeMethod;
334 public override string GetSignatureForError ()
338 name = DeclaringType.GetSignatureForError () + "." + DeclaringType.Name;
339 } else if (Kind == MemberKind.Operator) {
340 var op = Operator.GetType (Name).Value;
341 if (op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) {
342 name = DeclaringType.GetSignatureForError () + "." + Operator.GetName (op) + " operator " + returnType.GetSignatureForError ();
344 name = DeclaringType.GetSignatureForError () + ".operator " + Operator.GetName (op);
346 } else if (IsAccessor) {
347 int split = Name.IndexOf ('_');
348 name = Name.Substring (split + 1);
349 var postfix = Name.Substring (0, split);
351 var pc = parameters.Count;
352 if (pc > 0 && postfix == "get") {
353 name = "this" + parameters.GetSignatureForError ("[", "]", pc);
354 } else if (pc > 1 && postfix == "set") {
355 name = "this" + parameters.GetSignatureForError ("[", "]", pc - 1);
359 return DeclaringType.GetSignatureForError () + "." + name + "." + postfix;
361 name = base.GetSignatureForError ();
363 name += "<" + TypeManager.CSharpName (targs) + ">";
365 name += "<" + TypeManager.CSharpName (GenericDefinition.TypeParameters) + ">";
368 return name + parameters.GetSignatureForError ();
371 public override MemberSpec InflateMember (TypeParameterInflator inflator)
373 var ms = (MethodSpec) base.InflateMember (inflator);
374 ms.returnType = inflator.Inflate (returnType);
375 ms.parameters = parameters.Inflate (inflator);
377 ms.constraints = TypeParameterSpec.InflateConstraints (inflator, Constraints);
382 public MethodSpec MakeGenericMethod (params TypeSpec[] targs)
385 throw new ArgumentNullException ();
387 // if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
390 //if (generic_intances == null)
391 // generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
393 var inflator = new TypeParameterInflator (DeclaringType, GenericDefinition.TypeParameters, targs);
395 var inflated = (MethodSpec) MemberwiseClone ();
396 inflated.declaringType = inflator.TypeInstance;
397 inflated.returnType = inflator.Inflate (returnType);
398 inflated.parameters = parameters.Inflate (inflator);
399 inflated.targs = targs;
400 inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
401 inflated.state |= StateFlags.PendingMakeMethod;
403 // if (inflated.parent == null)
404 // inflated.parent = parent;
406 //generic_intances.Add (targs, inflated);
410 public MethodSpec Mutate (TypeParameterMutator mutator)
412 var targs = TypeArguments;
414 targs = mutator.Mutate (targs);
416 var decl = DeclaringType;
417 if (DeclaringType.IsGenericOrParentIsGeneric) {
418 decl = mutator.Mutate (decl);
421 if (targs == TypeArguments && decl == DeclaringType)
424 var ms = (MethodSpec) MemberwiseClone ();
425 if (decl != DeclaringType) {
426 // Gets back MethodInfo in case of metaInfo was inflated
427 ms.metaInfo = MemberCache.GetMember (TypeParameterMutator.GetMemberDeclaringType (DeclaringType), this).metaInfo;
429 ms.declaringType = decl;
430 ms.state |= StateFlags.PendingMetaInflate;
435 ms.state |= StateFlags.PendingMakeMethod;
441 public void SetMetaInfo (MethodInfo info)
443 if (this.metaInfo != null)
444 throw new InternalErrorException ("MetaInfo reset");
446 this.metaInfo = info;
450 public abstract class MethodOrOperator : MethodCore, IMethodData
452 public MethodBuilder MethodBuilder;
453 ReturnParameter return_attributes;
454 SecurityType declarative_security;
455 protected MethodData MethodData;
457 static string[] attribute_targets = new string [] { "method", "return" };
459 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, Modifiers mod,
460 Modifiers allowed_mod, MemberName name,
461 Attributes attrs, ParametersCompiled parameters)
462 : base (parent, generic, type, mod, allowed_mod, name,
467 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
469 if (a.Target == AttributeTargets.ReturnValue) {
470 if (return_attributes == null)
471 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
473 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
477 if (a.Type == pa.MethodImpl) {
478 is_external_implementation = a.IsInternalCall ();
481 if (a.Type == pa.DllImport) {
482 const Modifiers extern_static = Modifiers.EXTERN | Modifiers.STATIC;
483 if ((ModFlags & extern_static) != extern_static) {
484 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
486 is_external_implementation = true;
489 if (a.IsValidSecurityAttribute ()) {
490 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
494 if (MethodBuilder != null)
495 MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
498 public override AttributeTargets AttributeTargets {
500 return AttributeTargets.Method;
504 protected override bool CheckForDuplications ()
506 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
509 public virtual EmitContext CreateEmitContext (ILGenerator ig)
511 return new EmitContext (this, ig, MemberType);
514 public override bool Define ()
523 if (this is Operator)
524 kind = MemberKind.Operator;
525 else if (this is Destructor)
526 kind = MemberKind.Destructor;
528 kind = MemberKind.Method;
530 if (IsPartialDefinition) {
531 caching_flags &= ~Flags.Excluded_Undetected;
532 caching_flags |= Flags.Excluded;
534 // Add to member cache only when a partial method implementation has not been found yet
535 if ((caching_flags & Flags.PartialDefinitionExists) == 0) {
536 // MethodBase mb = new PartialMethodDefinitionInfo (this);
538 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, null, parameters, ModFlags);
539 Parent.MemberCache.AddMember (spec);
545 MethodData = new MethodData (
546 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
548 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName), Report))
551 MethodBuilder = MethodData.MethodBuilder;
553 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, MethodBuilder, parameters, ModFlags);
554 if (MemberName.Arity > 0)
555 spec.IsGeneric = true;
557 Parent.MemberCache.AddMember (this, MethodBuilder.Name, spec);
562 protected override void DoMemberTypeIndependentChecks ()
564 base.DoMemberTypeIndependentChecks ();
566 CheckAbstractAndExtern (block != null);
568 if ((ModFlags & Modifiers.PARTIAL) != 0) {
569 for (int i = 0; i < parameters.Count; ++i) {
570 IParameterData p = parameters.FixedParameters [i];
571 if (p.ModFlags == Parameter.Modifier.OUT) {
572 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
573 GetSignatureForError ());
576 if (p.HasDefaultValue && IsPartialImplementation)
577 ((Parameter) p).Warning_UselessOptionalParameter (Report);
582 protected override void DoMemberTypeDependentChecks ()
584 base.DoMemberTypeDependentChecks ();
586 if (MemberType.IsStatic) {
587 Error_StaticReturnType ();
591 public override void Emit ()
593 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
594 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (MethodBuilder);
595 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
596 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (MethodBuilder);
598 if (ReturnType == InternalType.Dynamic) {
599 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
600 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
601 } else if (ReturnType.HasDynamicElement) {
602 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
603 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
606 if (OptAttributes != null)
607 OptAttributes.Emit ();
609 if (declarative_security != null) {
610 foreach (var de in declarative_security) {
612 MethodBuilder.__AddDeclarativeSecurity (de);
614 MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
619 if (MethodData != null)
620 MethodData.Emit (Parent);
628 protected void Error_ConditionalAttributeIsNotValid ()
630 Report.Error (577, Location,
631 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
632 GetSignatureForError ());
635 public bool IsPartialDefinition {
637 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
641 public bool IsPartialImplementation {
643 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
647 public override string[] ValidAttributeTargets {
649 return attribute_targets;
653 #region IMethodData Members
655 public TypeSpec ReturnType {
661 public MemberName MethodName {
668 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
670 public override string[] ConditionalConditions ()
672 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
675 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
676 return new string [0];
678 caching_flags &= ~Flags.Excluded_Undetected;
681 if (base_method == null) {
682 if (OptAttributes == null)
685 Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
689 conditions = new string[attrs.Length];
690 for (int i = 0; i < conditions.Length; ++i)
691 conditions[i] = attrs[i].GetConditionalAttributeValue ();
693 conditions = base_method.MemberDefinition.ConditionalConditions();
696 if (conditions != null)
697 caching_flags |= Flags.Excluded;
702 GenericMethod IMethodData.GenericMethod {
704 return GenericMethod;
708 public virtual void EmitExtraSymbolInfo (SourceMethod source)
715 public class SourceMethod : IMethodDef
718 SourceMethodBuilder builder;
720 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
722 this.method = method;
724 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
728 get { return method.Name; }
733 if (method is MethodBuilder)
734 return ((MethodBuilder) method).GetToken ().Token;
735 else if (method is ConstructorBuilder)
736 return ((ConstructorBuilder) method).GetToken ().Token;
738 throw new NotSupportedException ();
742 public void CloseMethod ()
744 SymbolWriter.CloseMethod ();
747 public void SetRealMethodName (string name)
750 builder.SetRealMethodName (name);
753 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
755 if (!SymbolWriter.HasSymbolWriter)
760 Location start_loc = block.StartLocation;
761 if (start_loc.IsNull)
764 ICompileUnit compile_unit = start_loc.CompilationUnit;
765 if (compile_unit == null)
768 return new SourceMethod (parent, method, compile_unit);
772 public class Method : MethodOrOperator, IGenericMethodDefinition
774 Method partialMethodImplementation;
776 public Method (DeclSpace parent, GenericMethod generic,
777 FullNamedExpression return_type, Modifiers mod,
778 MemberName name, ParametersCompiled parameters, Attributes attrs)
779 : base (parent, generic, return_type, mod,
780 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
781 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
782 AllowedModifiersClass,
783 name, attrs, parameters)
787 protected Method (DeclSpace parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
788 MemberName name, ParametersCompiled parameters, Attributes attrs)
789 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
795 public override TypeParameter[] CurrentTypeParameters {
797 if (GenericMethod != null)
798 return GenericMethod.CurrentTypeParameters;
804 public override bool HasUnresolvedConstraints {
806 if (CurrentTypeParameters == null)
809 // When overriding base method constraints are fetched from
810 // base method but to find it we have to resolve parameters
811 // to find exact base method match
812 if (IsExplicitImpl || (ModFlags & Modifiers.OVERRIDE) != 0)
813 return base_method == null;
815 // Even for non-override generic method constraints check has to be
816 // delayed after all constraints are resolved
821 public TypeParameterSpec[] TypeParameters {
824 return CurrentTypeParameters.Select (l => l.Type).ToArray ();
828 public int TypeParametersCount {
830 return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Length;
836 public override string GetSignatureForError()
838 return base.GetSignatureForError () + parameters.GetSignatureForError ();
841 void Error_DuplicateEntryPoint (Method b)
843 Report.Error (17, b.Location,
844 "Program `{0}' has more than one entry point defined: `{1}'",
845 b.Module.Builder.ScopeName, b.GetSignatureForError ());
850 if (ReturnType != TypeManager.void_type &&
851 ReturnType != TypeManager.int32_type)
854 if (parameters.IsEmpty)
857 if (parameters.Count > 1)
860 var ac = parameters.Types [0] as ArrayContainer;
861 return ac != null && ac.Rank == 1 && ac.Element == TypeManager.string_type &&
862 (parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
865 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
868 TypeParameter[] tp = CurrentTypeParameters;
870 TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
872 return new TypeParameterExpr (t, loc);
876 return base.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
879 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
881 if (a.Type == pa.Conditional) {
882 if (IsExplicitImpl) {
883 Error_ConditionalAttributeIsNotValid ();
887 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
888 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
892 if (ReturnType != TypeManager.void_type) {
893 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
898 Report.Error (582, Location, "Conditional not valid on interface members");
902 if (MethodData.implementing != null) {
903 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
904 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
905 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
909 for (int i = 0; i < parameters.Count; ++i) {
910 if (parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
911 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
917 if (a.Type == pa.Extension) {
918 a.Error_MisusedExtensionAttribute ();
922 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
925 protected virtual void DefineTypeParameters ()
927 var tparams = CurrentTypeParameters;
929 TypeParameterSpec[] base_tparams = null;
930 TypeParameterSpec[] base_decl_tparams = TypeParameterSpec.EmptyTypes;
931 TypeSpec[] base_targs = TypeSpec.EmptyTypes;
932 if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
933 if (base_method != null) {
934 base_tparams = base_method.GenericDefinition.TypeParameters;
936 if (base_method.DeclaringType.IsGeneric) {
937 base_decl_tparams = base_method.DeclaringType.MemberDefinition.TypeParameters;
938 base_targs = Parent.BaseType.TypeArguments;
941 if (base_method.IsGeneric) {
942 if (base_decl_tparams.Length != 0) {
943 base_decl_tparams = base_decl_tparams.Concat (base_tparams).ToArray ();
944 base_targs = base_targs.Concat (tparams.Select<TypeParameter, TypeSpec> (l => l.Type)).ToArray ();
946 base_decl_tparams = base_tparams;
947 base_targs = tparams.Select (l => l.Type).ToArray ();
950 } else if (MethodData.implementing != null) {
951 base_tparams = MethodData.implementing.GenericDefinition.TypeParameters;
952 if (MethodData.implementing.DeclaringType.IsGeneric) {
953 base_decl_tparams = MethodData.implementing.DeclaringType.MemberDefinition.TypeParameters;
954 foreach (var iface in Parent.CurrentType.Interfaces) {
955 if (iface == MethodData.implementing.DeclaringType) {
956 base_targs = iface.TypeArguments;
964 for (int i = 0; i < tparams.Length; ++i) {
967 if (!tp.ResolveConstraints (this))
971 // Copy base constraints for override/explicit methods
973 if (base_tparams != null) {
974 var base_tparam = base_tparams[i];
975 var local_tparam = tp.Type;
976 local_tparam.SpecialConstraint = base_tparam.SpecialConstraint;
978 var inflator = new TypeParameterInflator (CurrentType, base_decl_tparams, base_targs);
979 base_tparam.InflateConstraints (inflator, local_tparam);
982 // Check all type argument constraints for possible collision
983 // introduced by inflating inherited constraints in this context
987 // class A<T> { virtual void Foo<U> () where U : class, T {} }
988 // class B : A<int> { override void Foo<U> {} }
990 var local_tparam_targs = local_tparam.TypeArguments;
991 if (local_tparam_targs != null) {
992 for (int ii = 0; ii < local_tparam_targs.Length; ++ii) {
993 var ta = local_tparam_targs [ii];
994 if (!ta.IsClass && !ta.IsStruct)
997 if (Constraints.CheckConflictingInheritedConstraint (local_tparam, ta, this, Location)) {
998 local_tparam.ChangeTypeArgumentToBaseType (ii);
1006 if (MethodData.implementing != null) {
1007 var base_tp = MethodData.implementing.Constraints[i];
1008 if (!tp.Type.HasSameConstraintsImplementation (base_tp)) {
1009 Report.SymbolRelatedToPreviousError (MethodData.implementing);
1010 Report.Error (425, Location,
1011 "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",
1012 tp.GetSignatureForError (), GetSignatureForError (), base_tp.GetSignatureForError (), MethodData.implementing.GetSignatureForError ());
1021 public override bool Define ()
1023 if (type_expr.Type == TypeManager.void_type && parameters.IsEmpty && MemberName.Arity == 0 && MemberName.Name == Destructor.MetadataName) {
1024 Report.Warning (465, 1, Location, "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
1027 if (!base.Define ())
1030 if (partialMethodImplementation != null && IsPartialDefinition)
1031 MethodBuilder = partialMethodImplementation.MethodBuilder;
1033 if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
1034 Error1599 (Location, ReturnType, Report);
1038 if (CurrentTypeParameters == null) {
1039 if (base_method != null) {
1040 if (parameters.Count == 1 && ParameterTypes[0] == TypeManager.object_type && Name == "Equals")
1041 Parent.PartialContainer.Mark_HasEquals ();
1042 else if (parameters.IsEmpty && Name == "GetHashCode")
1043 Parent.PartialContainer.Mark_HasGetHashCode ();
1047 DefineTypeParameters ();
1050 if (block != null && block.IsIterator) {
1052 // Current method is turned into automatically generated
1053 // wrapper which creates an instance of iterator
1055 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
1056 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
1059 if ((ModFlags & Modifiers.STATIC) == 0)
1062 if (parameters.HasExtensionMethodType) {
1063 if (Parent.PartialContainer.IsStatic && !Parent.IsGeneric) {
1064 if (!Parent.IsTopLevel)
1065 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
1066 GetSignatureForError ());
1068 PredefinedAttribute pa = Module.PredefinedAttributes.Extension;
1069 if (!pa.IsDefined) {
1070 Report.Error (1110, Location,
1071 "`{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",
1072 GetSignatureForError ());
1075 ModFlags |= Modifiers.METHOD_EXTENSION;
1076 Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
1077 Spec.DeclaringType.SetExtensionMethodContainer ();
1078 Parent.Module.HasExtensionMethod = true;
1080 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
1081 GetSignatureForError ());
1086 // This is used to track the Entry Point,
1088 if (RootContext.NeedsEntryPoint &&
1090 (RootContext.MainClass == null ||
1091 RootContext.MainClass == Parent.TypeBuilder.FullName)){
1092 if (IsEntryPoint ()) {
1094 if (Parent.DeclaringAssembly.EntryPoint == null) {
1095 if (Parent.IsGeneric || MemberName.IsGeneric) {
1096 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
1097 GetSignatureForError ());
1100 Parent.DeclaringAssembly.EntryPoint = this;
1103 Error_DuplicateEntryPoint (Parent.DeclaringAssembly.EntryPoint);
1104 Error_DuplicateEntryPoint (this);
1107 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
1108 GetSignatureForError ());
1118 public override void Emit ()
1121 if (IsPartialDefinition) {
1123 // Use partial method implementation builder for partial method declaration attributes
1125 if (partialMethodImplementation != null) {
1126 MethodBuilder = partialMethodImplementation.MethodBuilder;
1132 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
1133 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
1134 GetSignatureForError ());
1137 if (CurrentTypeParameters != null) {
1138 var ge = type_expr as GenericTypeExpr;
1140 ge.CheckConstraints (this);
1142 foreach (Parameter p in parameters.FixedParameters) {
1143 ge = p.TypeExpression as GenericTypeExpr;
1145 ge.CheckConstraints (this);
1148 for (int i = 0; i < CurrentTypeParameters.Length; ++i) {
1149 var tp = CurrentTypeParameters [i];
1150 tp.CheckGenericConstraints ();
1157 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
1158 Module.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
1160 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
1161 Location, MethodBuilder);
1166 public override bool EnableOverloadChecks (MemberCore overload)
1168 // TODO: It can be deleted when members will be defined in correct order
1169 if (overload is Operator)
1170 return overload.EnableOverloadChecks (this);
1172 if (overload is Indexer)
1175 return base.EnableOverloadChecks (overload);
1178 public static void Error1599 (Location loc, TypeSpec t, Report Report)
1180 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
1183 protected override bool ResolveMemberType ()
1185 if (GenericMethod != null) {
1186 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
1187 if (!GenericMethod.Define (this))
1191 return base.ResolveMemberType ();
1194 public void SetPartialDefinition (Method methodDefinition)
1196 caching_flags |= Flags.PartialDefinitionExists;
1197 methodDefinition.partialMethodImplementation = this;
1199 // Ensure we are always using method declaration parameters
1200 for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
1201 parameters [i].Name = methodDefinition.parameters [i].Name;
1202 parameters [i].DefaultValue = methodDefinition.parameters [i].DefaultValue;
1205 if (methodDefinition.attributes == null)
1208 if (attributes == null) {
1209 attributes = methodDefinition.attributes;
1211 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
1216 public abstract class ConstructorInitializer : ExpressionStatement
1218 Arguments argument_list;
1219 MethodSpec base_ctor;
1221 public ConstructorInitializer (Arguments argument_list, Location loc)
1223 this.argument_list = argument_list;
1227 public Arguments Arguments {
1229 return argument_list;
1233 public override Expression CreateExpressionTree (ResolveContext ec)
1235 throw new NotSupportedException ("ET");
1238 protected override Expression DoResolve (ResolveContext ec)
1240 eclass = ExprClass.Value;
1243 var caller_builder = (Constructor) ec.MemberContext;
1246 // Spec mandates that constructor initializer will not have `this' access
1248 using (ec.Set (ResolveContext.Options.BaseInitializer)) {
1249 if (argument_list != null) {
1251 argument_list.Resolve (ec, out dynamic);
1254 ec.Report.Error (1975, loc,
1255 "The constructor call cannot be dynamically dispatched within constructor initializer");
1261 type = ec.CurrentType;
1262 if (this is ConstructorBaseInitializer) {
1263 if (ec.CurrentType.BaseType == null)
1266 type = ec.CurrentType.BaseType;
1267 if (ec.CurrentType.IsStruct) {
1268 ec.Report.Error (522, loc,
1269 "`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
1274 // It is legal to have "this" initializers that take no arguments
1275 // in structs, they are just no-ops.
1277 // struct D { public D (int a) : this () {}
1279 if (TypeManager.IsStruct (ec.CurrentType) && argument_list == null)
1283 base_ctor = ConstructorLookup (ec, type, ref argument_list, loc);
1286 // TODO MemberCache: Does it work for inflated types ?
1287 if (base_ctor == caller_builder.Spec){
1288 ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
1289 caller_builder.GetSignatureForError ());
1295 public override void Emit (EmitContext ec)
1297 // It can be null for static initializers
1298 if (base_ctor == null)
1303 Invocation.EmitCall (ec, new CompilerGeneratedThis (type, loc), base_ctor, argument_list, loc);
1306 public override void EmitStatement (EmitContext ec)
1312 public class ConstructorBaseInitializer : ConstructorInitializer {
1313 public ConstructorBaseInitializer (Arguments argument_list, Location l) :
1314 base (argument_list, l)
1319 class GeneratedBaseInitializer: ConstructorBaseInitializer {
1320 public GeneratedBaseInitializer (Location loc):
1326 public class ConstructorThisInitializer : ConstructorInitializer {
1327 public ConstructorThisInitializer (Arguments argument_list, Location l) :
1328 base (argument_list, l)
1333 public class Constructor : MethodCore, IMethodData {
1334 public ConstructorBuilder ConstructorBuilder;
1335 public ConstructorInitializer Initializer;
1336 SecurityType declarative_security;
1337 bool has_compliant_args;
1340 // Modifiers allowed for a constructor.
1342 public const Modifiers AllowedModifiers =
1344 Modifiers.PROTECTED |
1345 Modifiers.INTERNAL |
1351 static readonly string[] attribute_targets = new string [] { "method" };
1353 public static readonly string ConstructorName = ".ctor";
1354 public static readonly string TypeConstructorName = ".cctor";
1357 // The spec claims that static is not permitted, but
1358 // my very own code has static constructors.
1360 public Constructor (DeclSpace parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args,
1361 ConstructorInitializer init, Location loc)
1362 : base (parent, null, null, mod, AllowedModifiers,
1363 new MemberName (name, loc), attrs, args)
1368 public bool HasCompliantArgs {
1369 get { return has_compliant_args; }
1372 public override AttributeTargets AttributeTargets {
1373 get { return AttributeTargets.Constructor; }
1377 // Returns true if this is a default constructor
1379 public bool IsDefault ()
1381 if ((ModFlags & Modifiers.STATIC) != 0)
1382 return parameters.IsEmpty;
1384 return parameters.IsEmpty &&
1385 (Initializer is ConstructorBaseInitializer) &&
1386 (Initializer.Arguments == null);
1389 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1391 if (a.IsValidSecurityAttribute ()) {
1392 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
1396 if (a.Type == pa.MethodImpl) {
1397 is_external_implementation = a.IsInternalCall ();
1400 ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1403 protected override bool CheckBase ()
1405 if ((ModFlags & Modifiers.STATIC) != 0) {
1406 if (!parameters.IsEmpty) {
1407 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
1408 GetSignatureForError ());
1412 // the rest can be ignored
1416 // Check whether arguments were correct.
1417 if (!DefineParameters (parameters))
1420 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1421 Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1423 if (Parent.PartialContainer.Kind == MemberKind.Struct && parameters.IsEmpty) {
1424 Report.Error (568, Location,
1425 "Structs cannot contain explicit parameterless constructors");
1429 CheckProtectedModifier ();
1435 // Creates the ConstructorBuilder
1437 public override bool Define ()
1439 if (ConstructorBuilder != null)
1442 var ca = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
1444 if ((ModFlags & Modifiers.STATIC) != 0) {
1445 ca |= MethodAttributes.Static | MethodAttributes.Private;
1447 ca |= ModifiersExtensions.MethodAttr (ModFlags);
1450 if (!CheckAbstractAndExtern (block != null))
1453 // Check if arguments were correct.
1457 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
1458 ca, CallingConventions,
1459 parameters.GetMetaInfo ());
1461 spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, TypeManager.void_type, ConstructorBuilder, parameters, ModFlags);
1463 Parent.MemberCache.AddMember (spec);
1465 // It's here only to report an error
1466 if (block != null && block.IsIterator) {
1467 member_type = TypeManager.void_type;
1468 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
1477 public override void Emit ()
1479 if (Parent.PartialContainer.IsComImport) {
1480 if (!IsDefault ()) {
1481 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
1482 Parent.GetSignatureForError ());
1485 // Set as internal implementation and reset block data
1486 // to ensure no IL is generated
1487 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
1491 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
1492 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (ConstructorBuilder);
1494 if (OptAttributes != null)
1495 OptAttributes.Emit ();
1500 // If we use a "this (...)" constructor initializer, then
1501 // do not emit field initializers, they are initialized in the other constructor
1503 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
1504 !(Initializer is ConstructorThisInitializer);
1506 BlockContext bc = new BlockContext (this, block, TypeManager.void_type);
1507 bc.Set (ResolveContext.Options.ConstructorScope);
1509 if (emit_field_initializers)
1510 Parent.PartialContainer.ResolveFieldInitializers (bc);
1512 if (block != null) {
1513 // If this is a non-static `struct' constructor and doesn't have any
1514 // initializer, it must initialize all of the struct's fields.
1515 if ((Parent.PartialContainer.Kind == MemberKind.Struct) &&
1516 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
1517 block.AddThisVariable (bc, Parent, Location);
1519 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
1520 if (Parent.PartialContainer.Kind == MemberKind.Class && Initializer == null)
1521 Initializer = new GeneratedBaseInitializer (Location);
1523 if (Initializer != null) {
1524 block.AddScopeStatement (new StatementExpression (Initializer));
1529 parameters.ApplyAttributes (this, ConstructorBuilder);
1531 SourceMethod source = SourceMethod.Create (Parent, ConstructorBuilder, block);
1533 if (block != null) {
1534 if (block.Resolve (null, bc, this)) {
1535 EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType);
1536 ec.With (EmitContext.Options.ConstructorScope, true);
1538 if (!ec.HasReturnLabel && bc.HasReturnLabel) {
1539 ec.ReturnLabel = bc.ReturnLabel;
1540 ec.HasReturnLabel = true;
1548 source.CloseMethod ();
1550 if (declarative_security != null) {
1551 foreach (var de in declarative_security) {
1553 ConstructorBuilder.__AddDeclarativeSecurity (de);
1555 ConstructorBuilder.AddDeclarativeSecurity (de.Key, de.Value);
1563 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate)
1565 // Is never override
1566 bestCandidate = null;
1570 public override string GetSignatureForError()
1572 return base.GetSignatureForError () + parameters.GetSignatureForError ();
1575 public override string[] ValidAttributeTargets {
1577 return attribute_targets;
1581 protected override bool VerifyClsCompliance ()
1583 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
1587 if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
1588 foreach (TypeSpec param in parameters.Types) {
1589 if (param.IsArray) {
1595 has_compliant_args = true;
1599 #region IMethodData Members
1601 public MemberName MethodName {
1607 public TypeSpec ReturnType {
1613 public EmitContext CreateEmitContext (ILGenerator ig)
1615 throw new NotImplementedException ();
1618 public bool IsExcluded()
1623 GenericMethod IMethodData.GenericMethod {
1629 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
1636 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
1638 public interface IMethodData
1640 CallingConventions CallingConventions { get; }
1641 Location Location { get; }
1642 MemberName MethodName { get; }
1643 TypeSpec ReturnType { get; }
1644 GenericMethod GenericMethod { get; }
1645 ParametersCompiled ParameterInfo { get; }
1646 MethodSpec Spec { get; }
1648 Attributes OptAttributes { get; }
1649 ToplevelBlock Block { get; set; }
1651 EmitContext CreateEmitContext (ILGenerator ig);
1652 string GetSignatureForError ();
1653 void EmitExtraSymbolInfo (SourceMethod source);
1657 // Encapsulates most of the Method's state
1659 public class MethodData {
1660 static FieldInfo methodbuilder_attrs_field;
1661 public readonly IMethodData method;
1663 public readonly GenericMethod GenericMethod;
1666 // Are we implementing an interface ?
1668 public MethodSpec implementing;
1673 protected InterfaceMemberBase member;
1674 protected Modifiers modifiers;
1675 protected MethodAttributes flags;
1676 protected TypeSpec declaring_type;
1677 protected MethodSpec parent_method;
1679 MethodBuilder builder;
1680 public MethodBuilder MethodBuilder {
1686 public TypeSpec DeclaringType {
1688 return declaring_type;
1692 public MethodData (InterfaceMemberBase member,
1693 Modifiers modifiers, MethodAttributes flags, IMethodData method)
1695 this.member = member;
1696 this.modifiers = modifiers;
1699 this.method = method;
1702 public MethodData (InterfaceMemberBase member,
1703 Modifiers modifiers, MethodAttributes flags,
1704 IMethodData method, MethodBuilder builder,
1705 GenericMethod generic, MethodSpec parent_method)
1706 : this (member, modifiers, flags, method)
1708 this.builder = builder;
1709 this.GenericMethod = generic;
1710 this.parent_method = parent_method;
1713 public bool Define (DeclSpace parent, string method_full_name, Report Report)
1715 TypeContainer container = parent.PartialContainer;
1717 PendingImplementation pending = container.PendingImplementations;
1718 if (pending != null){
1719 implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this);
1721 if (member.InterfaceType != null){
1722 if (implementing == null){
1723 if (member is PropertyBase) {
1724 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
1725 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
1726 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
1729 Report.Error (539, method.Location,
1730 "`{0}.{1}' in explicit interface declaration is not a member of interface",
1731 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
1735 if (implementing.IsAccessor && !(method is AbstractPropertyEventMethod)) {
1736 Report.SymbolRelatedToPreviousError (implementing);
1737 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
1738 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1742 if (implementing != null) {
1743 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
1744 if (prop_method == null) {
1745 if (implementing.IsAccessor) {
1746 Report.SymbolRelatedToPreviousError (implementing);
1747 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}'",
1748 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1750 } else if (implementing.DeclaringType.IsInterface) {
1751 if (!implementing.IsAccessor) {
1752 Report.SymbolRelatedToPreviousError (implementing);
1753 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
1754 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
1756 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
1757 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
1758 Report.SymbolRelatedToPreviousError (implementing);
1759 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
1760 method.GetSignatureForError (), implementing.GetSignatureForError ());
1769 // For implicit implementations, make sure we are public, for
1770 // explicit implementations, make sure we are private.
1772 if (implementing != null){
1774 // Setting null inside this block will trigger a more
1775 // verbose error reporting for missing interface implementations
1777 // The "candidate" function has been flagged already
1778 // but it wont get cleared
1780 if (member.IsExplicitImpl){
1781 if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
1782 Report.SymbolRelatedToPreviousError (implementing);
1783 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
1784 method.GetSignatureForError ());
1787 if (implementing.DeclaringType.IsInterface) {
1789 // If this is an interface method implementation,
1790 // check for public accessibility
1792 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
1794 implementing = null;
1796 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
1797 // We may never be private.
1798 implementing = null;
1800 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
1802 // We may be protected if we're overriding something.
1804 implementing = null;
1809 // Static is not allowed
1811 if ((modifiers & Modifiers.STATIC) != 0){
1812 implementing = null;
1817 // If implementing is still valid, set flags
1819 if (implementing != null){
1821 // When implementing interface methods, set NewSlot
1822 // unless, we are overwriting a method.
1824 if (implementing.DeclaringType.IsInterface){
1825 if ((modifiers & Modifiers.OVERRIDE) == 0)
1826 flags |= MethodAttributes.NewSlot;
1829 flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;
1831 // Set Final unless we're virtual, abstract or already overriding a method.
1832 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
1833 flags |= MethodAttributes.Final;
1836 // clear the pending implementation flag (requires explicit methods to be defined first)
1838 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName,
1839 member.InterfaceType, this, member.IsExplicitImpl);
1842 // Update indexer accessor name to match implementing abstract accessor
1844 if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
1845 method_full_name = implementing.MemberDefinition.Name;
1848 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
1850 if (builder == null)
1853 // if (container.CurrentType != null)
1854 // declaring_type = container.CurrentType;
1856 declaring_type = container.Definition;
1858 if (implementing != null && member.IsExplicitImpl) {
1859 container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
1867 /// Create the MethodBuilder for the method
1869 void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
1871 var return_type = method.ReturnType.GetMetaInfo ();
1872 var p_types = param.GetMetaInfo ();
1874 if (builder == null) {
1875 builder = container.TypeBuilder.DefineMethod (
1876 method_name, flags, method.CallingConventions,
1877 return_type, p_types);
1882 // Generic method has been already defined to resolve method parameters
1883 // correctly when they use type parameters
1885 builder.SetParameters (p_types);
1886 builder.SetReturnType (return_type);
1887 if (builder.Attributes != flags) {
1889 builder.__SetAttributes (flags);
1892 if (methodbuilder_attrs_field == null)
1893 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
1894 methodbuilder_attrs_field.SetValue (builder, flags);
1896 container.Compiler.Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
1905 public void Emit (DeclSpace parent)
1907 if (GenericMethod != null)
1908 GenericMethod.EmitAttributes ();
1910 var mc = (IMemberContext) method;
1912 method.ParameterInfo.ApplyAttributes (mc, MethodBuilder);
1914 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
1916 ToplevelBlock block = method.Block;
1917 if (block != null) {
1918 BlockContext bc = new BlockContext (mc, block, method.ReturnType);
1919 if (block.Resolve (null, bc, method)) {
1920 EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator ());
1921 if (!ec.HasReturnLabel && bc.HasReturnLabel) {
1922 ec.ReturnLabel = bc.ReturnLabel;
1923 ec.HasReturnLabel = true;
1930 if (source != null) {
1931 method.EmitExtraSymbolInfo (source);
1932 source.CloseMethod ();
1937 public class Destructor : MethodOrOperator
1939 const Modifiers AllowedModifiers =
1943 static readonly string[] attribute_targets = new string [] { "method" };
1945 public static readonly string MetadataName = "Finalize";
1947 public Destructor (DeclSpace parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
1948 : base (parent, null, null, mod, AllowedModifiers,
1949 new MemberName (MetadataName, l), attrs, parameters)
1951 ModFlags &= ~Modifiers.PRIVATE;
1952 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
1955 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1957 if (a.Type == pa.Conditional) {
1958 Error_ConditionalAttributeIsNotValid ();
1962 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1965 protected override bool CheckBase ()
1967 // Don't check base, destructors have special syntax
1971 public override void Emit()
1973 var base_type = Parent.PartialContainer.BaseType;
1974 if (base_type != null && Block != null) {
1975 var base_dtor = MemberCache.FindMember (base_type,
1976 new MemberFilter (MetadataName, 0, MemberKind.Destructor, null, null), BindingRestriction.InstanceOnly) as MethodSpec;
1978 if (base_dtor == null)
1979 throw new NotImplementedException ();
1981 MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
1982 method_expr.InstanceExpression = new BaseThis (base_type, Location);
1984 var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation);
1985 var finaly_block = new ExplicitBlock (block, Location, Location);
1988 // 0-size arguments to avoid CS0250 error
1989 // TODO: Should use AddScopeStatement or something else which emits correct
1992 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0))));
1994 var tf = new TryFinally (try_block, finaly_block, Location);
1995 block.WrapIntoDestructor (tf, try_block);
2001 public override string GetSignatureForError ()
2003 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
2006 protected override bool ResolveMemberType ()
2008 member_type = TypeManager.void_type;
2012 public override string[] ValidAttributeTargets {
2014 return attribute_targets;
2019 // Ooouh Martin, templates are missing here.
2020 // When it will be possible move here a lot of child code and template method type.
2021 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
2022 protected MethodData method_data;
2023 protected ToplevelBlock block;
2024 protected SecurityType declarative_security;
2026 protected readonly string prefix;
2028 ReturnParameter return_attributes;
2030 public AbstractPropertyEventMethod (InterfaceMemberBase member, string prefix, Attributes attrs, Location loc)
2031 : base (member.Parent, SetupName (prefix, member, loc), attrs)
2033 this.prefix = prefix;
2036 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
2038 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
2041 public void UpdateName (InterfaceMemberBase member)
2043 SetMemberName (SetupName (prefix, member, Location));
2046 #region IMethodData Members
2048 public ToplevelBlock Block {
2058 public CallingConventions CallingConventions {
2060 return CallingConventions.Standard;
2064 public EmitContext CreateEmitContext (ILGenerator ig)
2066 return new EmitContext (this, ig, ReturnType);
2069 public bool IsExcluded ()
2074 GenericMethod IMethodData.GenericMethod {
2080 public MemberName MethodName {
2086 public TypeSpec[] ParameterTypes {
2088 return ParameterInfo.Types;
2092 public abstract ParametersCompiled ParameterInfo { get ; }
2093 public abstract TypeSpec ReturnType { get; }
2097 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2099 if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
2100 Report.Error (1667, a.Location,
2101 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
2102 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
2106 if (a.IsValidSecurityAttribute ()) {
2107 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
2111 if (a.Target == AttributeTargets.Method) {
2112 method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
2116 if (a.Target == AttributeTargets.ReturnValue) {
2117 if (return_attributes == null)
2118 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2120 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
2124 ApplyToExtraTarget (a, ctor, cdata, pa);
2127 protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2129 throw new NotSupportedException ("You forgot to define special attribute target handling");
2132 // It is not supported for the accessors
2133 public sealed override bool Define()
2135 throw new NotSupportedException ();
2138 public virtual void Emit (DeclSpace parent)
2140 method_data.Emit (parent);
2142 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
2143 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
2144 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
2145 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
2147 if (ReturnType == InternalType.Dynamic) {
2148 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2149 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
2150 } else if (ReturnType.HasDynamicElement) {
2151 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2152 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
2155 if (OptAttributes != null)
2156 OptAttributes.Emit ();
2158 if (declarative_security != null) {
2159 foreach (var de in declarative_security) {
2161 method_data.MethodBuilder.__AddDeclarativeSecurity (de);
2163 method_data.MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2171 public override bool EnableOverloadChecks (MemberCore overload)
2173 if (overload is MethodCore) {
2174 caching_flags |= Flags.MethodOverloadsExist;
2178 // This can only happen with indexers and it will
2179 // be catched as indexer difference
2180 if (overload is AbstractPropertyEventMethod)
2186 public override bool IsClsComplianceRequired()
2191 public MethodSpec Spec { get; protected set; }
2194 // Represents header string for documentation comment.
2196 public override string DocCommentHeader {
2197 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
2200 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
2204 public class Operator : MethodOrOperator {
2206 const Modifiers AllowedModifiers =
2212 public enum OpType : byte {
2222 // Unary and Binary operators
2245 // Implicit and Explicit
2249 // Just because of enum
2253 public readonly OpType OperatorType;
2255 static readonly string [] [] names;
2259 names = new string[(int)OpType.TOP][];
2260 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
2261 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
2262 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
2263 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
2264 names [(int) OpType.True] = new string [] { "true", "op_True" };
2265 names [(int) OpType.False] = new string [] { "false", "op_False" };
2266 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
2267 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
2268 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
2269 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
2270 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
2271 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
2272 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
2273 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
2274 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
2275 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
2276 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
2277 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
2278 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
2279 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
2280 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
2281 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
2282 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
2283 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
2284 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
2285 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
2288 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
2289 Modifiers mod_flags, ParametersCompiled parameters,
2290 ToplevelBlock block, Attributes attrs, Location loc)
2291 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
2292 new MemberName (GetMetadataName (type), loc), attrs, parameters)
2294 OperatorType = type;
2298 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2300 if (a.Type == pa.Conditional) {
2301 Error_ConditionalAttributeIsNotValid ();
2305 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2308 public override bool Define ()
2310 const Modifiers RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
2311 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
2312 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
2315 if (!base.Define ())
2318 if (block != null && block.IsIterator) {
2320 // Current method is turned into automatically generated
2321 // wrapper which creates an instance of iterator
2323 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
2324 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
2327 // imlicit and explicit operator of same types are not allowed
2328 if (OperatorType == OpType.Explicit)
2329 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
2330 else if (OperatorType == OpType.Implicit)
2331 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
2333 TypeSpec declaring_type = Parent.CurrentType;
2334 TypeSpec return_type = MemberType;
2335 TypeSpec first_arg_type = ParameterTypes [0];
2337 TypeSpec first_arg_type_unwrap = first_arg_type;
2338 if (TypeManager.IsNullableType (first_arg_type))
2339 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
2341 TypeSpec return_type_unwrap = return_type;
2342 if (TypeManager.IsNullableType (return_type))
2343 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
2346 // Rules for conversion operators
2348 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2349 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type) {
2350 Report.Error (555, Location,
2351 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
2356 if (declaring_type == return_type || declaring_type == return_type_unwrap) {
2357 conv_type = first_arg_type;
2358 } else if (declaring_type == first_arg_type || declaring_type == first_arg_type_unwrap) {
2359 conv_type = return_type;
2361 Report.Error (556, Location,
2362 "User-defined conversion must convert to or from the enclosing type");
2366 if (conv_type == InternalType.Dynamic) {
2367 Report.Error (1964, Location,
2368 "User-defined conversion `{0}' cannot convert to or from the dynamic type",
2369 GetSignatureForError ());
2374 if (conv_type.IsInterface) {
2375 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
2376 GetSignatureForError ());
2380 if (conv_type.IsClass) {
2381 if (TypeSpec.IsBaseClass (declaring_type, conv_type, true)) {
2382 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
2383 GetSignatureForError ());
2387 if (TypeSpec.IsBaseClass (conv_type, declaring_type, false)) {
2388 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
2389 GetSignatureForError ());
2393 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
2394 if (first_arg_type != declaring_type || parameters.Types[1] != TypeManager.int32_type) {
2395 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");
2398 } else if (parameters.Count == 1) {
2399 // Checks for Unary operators
2401 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
2402 if (return_type != declaring_type && !TypeSpec.IsBaseClass (return_type, declaring_type, false)) {
2403 Report.Error (448, Location,
2404 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
2407 if (first_arg_type != declaring_type) {
2409 559, Location, "The parameter type for ++ or -- operator must be the containing type");
2414 if (first_arg_type_unwrap != declaring_type) {
2415 Report.Error (562, Location,
2416 "The parameter type of a unary operator must be the containing type");
2420 if (OperatorType == OpType.True || OperatorType == OpType.False) {
2421 if (return_type != TypeManager.bool_type) {
2424 "The return type of operator True or False " +
2430 } else if (first_arg_type_unwrap != declaring_type) {
2431 // Checks for Binary operators
2433 var second_arg_type = ParameterTypes[1];
2434 if (TypeManager.IsNullableType (second_arg_type))
2435 second_arg_type = TypeManager.GetTypeArguments (second_arg_type)[0];
2437 if (second_arg_type != declaring_type) {
2438 Report.Error (563, Location,
2439 "One of the parameters of a binary operator must be the containing type");
2447 protected override bool ResolveMemberType ()
2449 if (!base.ResolveMemberType ())
2452 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2456 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate)
2458 // Operator cannot be override
2459 bestCandidate = null;
2463 public static string GetName (OpType ot)
2465 return names [(int) ot] [0];
2468 public static string GetName (string metadata_name)
2470 for (int i = 0; i < names.Length; ++i) {
2471 if (names [i] [1] == metadata_name)
2472 return names [i] [0];
2477 public static string GetMetadataName (OpType ot)
2479 return names [(int) ot] [1];
2482 public static string GetMetadataName (string name)
2484 for (int i = 0; i < names.Length; ++i) {
2485 if (names [i] [0] == name)
2486 return names [i] [1];
2491 public static OpType? GetType (string metadata_name)
2493 for (int i = 0; i < names.Length; ++i) {
2494 if (names[i][1] == metadata_name)
2501 public OpType GetMatchingOperator ()
2503 switch (OperatorType) {
2504 case OpType.Equality:
2505 return OpType.Inequality;
2506 case OpType.Inequality:
2507 return OpType.Equality;
2509 return OpType.False;
2512 case OpType.GreaterThan:
2513 return OpType.LessThan;
2514 case OpType.LessThan:
2515 return OpType.GreaterThan;
2516 case OpType.GreaterThanOrEqual:
2517 return OpType.LessThanOrEqual;
2518 case OpType.LessThanOrEqual:
2519 return OpType.GreaterThanOrEqual;
2525 public override string GetSignatureForError ()
2527 StringBuilder sb = new StringBuilder ();
2528 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2529 sb.AppendFormat ("{0}.{1} operator {2}",
2530 Parent.GetSignatureForError (), GetName (OperatorType), type_expr.GetSignatureForError ());
2533 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
2536 sb.Append (parameters.GetSignatureForError ());
2537 return sb.ToString ();