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 sealed class MethodSpec : MemberSpec, IParametersMember
198 MethodBase metaInfo, inflatedMetaInfo;
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 ()
305 // inflatedMetaInfo is extra field needed for cases where we
306 // inflate method but another nested type can later inflate
307 // again (the cache would be build with inflated metaInfo) and
308 // TypeBuilder can work with method definitions only
310 if (inflatedMetaInfo == null) {
311 if ((state & StateFlags.PendingMetaInflate) != 0) {
312 var dt_meta = DeclaringType.GetMetaInfo ();
314 if (DeclaringType.IsTypeBuilder) {
316 inflatedMetaInfo = TypeBuilder.GetConstructor (dt_meta, (ConstructorInfo) metaInfo);
318 inflatedMetaInfo = TypeBuilder.GetMethod (dt_meta, (MethodInfo) metaInfo);
321 // it should not be reached
322 throw new NotImplementedException ();
324 inflatedMetaInfo = MethodInfo.GetMethodFromHandle (metaInfo.MethodHandle, dt_meta.TypeHandle);
328 state &= ~StateFlags.PendingMetaInflate;
330 inflatedMetaInfo = metaInfo;
334 if ((state & StateFlags.PendingMakeMethod) != 0) {
335 var sre_targs = new MetaType[targs.Length];
336 for (int i = 0; i < sre_targs.Length; ++i)
337 sre_targs[i] = targs[i].GetMetaInfo ();
339 inflatedMetaInfo = ((MethodInfo) inflatedMetaInfo).MakeGenericMethod (sre_targs);
340 state &= ~StateFlags.PendingMakeMethod;
343 return inflatedMetaInfo;
346 public override string GetSignatureForError ()
350 name = DeclaringType.GetSignatureForError () + "." + DeclaringType.Name;
351 } else if (Kind == MemberKind.Operator) {
352 var op = Operator.GetType (Name).Value;
353 if (op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) {
354 name = DeclaringType.GetSignatureForError () + "." + Operator.GetName (op) + " operator " + returnType.GetSignatureForError ();
356 name = DeclaringType.GetSignatureForError () + ".operator " + Operator.GetName (op);
358 } else if (IsAccessor) {
359 int split = Name.IndexOf ('_');
360 name = Name.Substring (split + 1);
361 var postfix = Name.Substring (0, split);
363 var pc = parameters.Count;
364 if (pc > 0 && postfix == "get") {
365 name = "this" + parameters.GetSignatureForError ("[", "]", pc);
366 } else if (pc > 1 && postfix == "set") {
367 name = "this" + parameters.GetSignatureForError ("[", "]", pc - 1);
371 return DeclaringType.GetSignatureForError () + "." + name + "." + postfix;
373 name = base.GetSignatureForError ();
375 name += "<" + TypeManager.CSharpName (targs) + ">";
377 name += "<" + TypeManager.CSharpName (GenericDefinition.TypeParameters) + ">";
380 return name + parameters.GetSignatureForError ();
383 public override MemberSpec InflateMember (TypeParameterInflator inflator)
385 var ms = (MethodSpec) base.InflateMember (inflator);
386 ms.inflatedMetaInfo = null;
387 ms.returnType = inflator.Inflate (returnType);
388 ms.parameters = parameters.Inflate (inflator);
390 ms.constraints = TypeParameterSpec.InflateConstraints (inflator, Constraints);
395 public MethodSpec MakeGenericMethod (IMemberContext context, params TypeSpec[] targs)
398 throw new ArgumentNullException ();
400 // if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
403 //if (generic_intances == null)
404 // generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
406 var inflator = new TypeParameterInflator (context, DeclaringType, GenericDefinition.TypeParameters, targs);
408 var inflated = (MethodSpec) MemberwiseClone ();
409 inflated.declaringType = inflator.TypeInstance;
410 inflated.returnType = inflator.Inflate (returnType);
411 inflated.parameters = parameters.Inflate (inflator);
412 inflated.targs = targs;
413 inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
414 inflated.state |= StateFlags.PendingMakeMethod;
416 // if (inflated.parent == null)
417 // inflated.parent = parent;
419 //generic_intances.Add (targs, inflated);
423 public MethodSpec Mutate (TypeParameterMutator mutator)
425 var targs = TypeArguments;
427 targs = mutator.Mutate (targs);
429 var decl = DeclaringType;
430 if (DeclaringType.IsGenericOrParentIsGeneric) {
431 decl = mutator.Mutate (decl);
434 if (targs == TypeArguments && decl == DeclaringType)
437 var ms = (MethodSpec) MemberwiseClone ();
438 if (decl != DeclaringType) {
439 ms.inflatedMetaInfo = null;
440 ms.declaringType = decl;
441 ms.state |= StateFlags.PendingMetaInflate;
446 ms.state |= StateFlags.PendingMakeMethod;
452 public override List<TypeSpec> ResolveMissingDependencies ()
454 var missing = returnType.ResolveMissingDependencies ();
455 foreach (var pt in parameters.Types) {
456 var m = pt.GetMissingDependencies ();
461 missing = new List<TypeSpec> ();
463 missing.AddRange (m);
469 public void SetMetaInfo (MethodInfo info)
471 if (this.metaInfo != null)
472 throw new InternalErrorException ("MetaInfo reset");
474 this.metaInfo = info;
478 public abstract class MethodOrOperator : MethodCore, IMethodData
480 public MethodBuilder MethodBuilder;
481 ReturnParameter return_attributes;
482 SecurityType declarative_security;
483 protected MethodData MethodData;
485 static readonly string[] attribute_targets = new string [] { "method", "return" };
487 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, Modifiers mod,
488 Modifiers allowed_mod, MemberName name,
489 Attributes attrs, ParametersCompiled parameters)
490 : base (parent, generic, type, mod, allowed_mod, name,
495 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
497 if (a.Target == AttributeTargets.ReturnValue) {
498 if (return_attributes == null)
499 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
501 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
505 if (a.Type == pa.MethodImpl) {
506 is_external_implementation = a.IsInternalCall ();
509 if (a.Type == pa.DllImport) {
510 const Modifiers extern_static = Modifiers.EXTERN | Modifiers.STATIC;
511 if ((ModFlags & extern_static) != extern_static) {
512 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
514 is_external_implementation = true;
517 if (a.IsValidSecurityAttribute ()) {
518 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
522 if (MethodBuilder != null)
523 MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
526 public override AttributeTargets AttributeTargets {
528 return AttributeTargets.Method;
532 protected override bool CheckForDuplications ()
534 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
537 public virtual EmitContext CreateEmitContext (ILGenerator ig)
539 return new EmitContext (this, ig, MemberType);
542 public override bool Define ()
551 if (this is Operator)
552 kind = MemberKind.Operator;
553 else if (this is Destructor)
554 kind = MemberKind.Destructor;
556 kind = MemberKind.Method;
558 if (IsPartialDefinition) {
559 caching_flags &= ~Flags.Excluded_Undetected;
560 caching_flags |= Flags.Excluded;
562 // Add to member cache only when a partial method implementation has not been found yet
563 if ((caching_flags & Flags.PartialDefinitionExists) == 0) {
564 // MethodBase mb = new PartialMethodDefinitionInfo (this);
566 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, null, parameters, ModFlags);
567 Parent.MemberCache.AddMember (spec);
573 MethodData = new MethodData (
574 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
576 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName), Report))
579 MethodBuilder = MethodData.MethodBuilder;
581 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, MethodBuilder, parameters, ModFlags);
582 if (MemberName.Arity > 0)
583 spec.IsGeneric = true;
585 Parent.MemberCache.AddMember (this, MethodBuilder.Name, spec);
590 protected override void DoMemberTypeIndependentChecks ()
592 base.DoMemberTypeIndependentChecks ();
594 CheckAbstractAndExtern (block != null);
596 if ((ModFlags & Modifiers.PARTIAL) != 0) {
597 for (int i = 0; i < parameters.Count; ++i) {
598 IParameterData p = parameters.FixedParameters [i];
599 if (p.ModFlags == Parameter.Modifier.OUT) {
600 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
601 GetSignatureForError ());
604 if (p.HasDefaultValue && IsPartialImplementation)
605 ((Parameter) p).Warning_UselessOptionalParameter (Report);
610 protected override void DoMemberTypeDependentChecks ()
612 base.DoMemberTypeDependentChecks ();
614 if (MemberType.IsStatic) {
615 Error_StaticReturnType ();
619 public override void Emit ()
621 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
622 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (MethodBuilder);
623 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
624 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (MethodBuilder);
626 if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
627 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
628 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
629 } else if (ReturnType.HasDynamicElement) {
630 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
631 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
634 if (OptAttributes != null)
635 OptAttributes.Emit ();
637 if (declarative_security != null) {
638 foreach (var de in declarative_security) {
640 MethodBuilder.__AddDeclarativeSecurity (de);
642 MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
647 if (MethodData != null)
648 MethodData.Emit (Parent);
656 protected void Error_ConditionalAttributeIsNotValid ()
658 Report.Error (577, Location,
659 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
660 GetSignatureForError ());
663 public bool IsPartialDefinition {
665 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
669 public bool IsPartialImplementation {
671 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
675 public override string[] ValidAttributeTargets {
677 return attribute_targets;
681 #region IMethodData Members
683 public TypeSpec ReturnType {
689 public MemberName MethodName {
696 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
698 public override string[] ConditionalConditions ()
700 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
703 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
704 return new string [0];
706 caching_flags &= ~Flags.Excluded_Undetected;
709 if (base_method == null) {
710 if (OptAttributes == null)
713 Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
717 conditions = new string[attrs.Length];
718 for (int i = 0; i < conditions.Length; ++i)
719 conditions[i] = attrs[i].GetConditionalAttributeValue ();
721 conditions = base_method.MemberDefinition.ConditionalConditions();
724 if (conditions != null)
725 caching_flags |= Flags.Excluded;
730 GenericMethod IMethodData.GenericMethod {
732 return GenericMethod;
736 public virtual void EmitExtraSymbolInfo (SourceMethod source)
743 public class SourceMethod : IMethodDef
746 SourceMethodBuilder builder;
748 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
750 this.method = method;
752 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
756 get { return method.Name; }
762 var mb = method as MethodBuilder;
764 token = mb.GetToken ();
766 token = ((ConstructorBuilder) method).GetToken ();
768 if (token.IsPseudoToken)
769 return ((ModuleBuilder) method.Module).ResolvePseudoToken (token.Token);
775 public void CloseMethod ()
777 SymbolWriter.CloseMethod ();
780 public void SetRealMethodName (string name)
783 builder.SetRealMethodName (name);
786 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
788 if (!SymbolWriter.HasSymbolWriter)
793 Location start_loc = block.StartLocation;
794 if (start_loc.IsNull)
797 ICompileUnit compile_unit = start_loc.CompilationUnit;
798 if (compile_unit == null)
801 return new SourceMethod (parent, method, compile_unit);
805 public class Method : MethodOrOperator, IGenericMethodDefinition
807 Method partialMethodImplementation;
809 public Method (DeclSpace parent, GenericMethod generic,
810 FullNamedExpression return_type, Modifiers mod,
811 MemberName name, ParametersCompiled parameters, Attributes attrs)
812 : base (parent, generic, return_type, mod,
813 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
814 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
815 AllowedModifiersClass,
816 name, attrs, parameters)
820 protected Method (DeclSpace parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
821 MemberName name, ParametersCompiled parameters, Attributes attrs)
822 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
828 public override TypeParameter[] CurrentTypeParameters {
830 if (GenericMethod != null)
831 return GenericMethod.CurrentTypeParameters;
837 public override bool HasUnresolvedConstraints {
839 if (CurrentTypeParameters == null)
842 // When overriding base method constraints are fetched from
843 // base method but to find it we have to resolve parameters
844 // to find exact base method match
845 if (IsExplicitImpl || (ModFlags & Modifiers.OVERRIDE) != 0)
846 return base_method == null;
848 // Even for non-override generic method constraints check has to be
849 // delayed after all constraints are resolved
854 public TypeParameterSpec[] TypeParameters {
857 return CurrentTypeParameters.Select (l => l.Type).ToArray ();
861 public int TypeParametersCount {
863 return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Length;
869 public override string GetSignatureForError()
871 return base.GetSignatureForError () + parameters.GetSignatureForError ();
874 void Error_DuplicateEntryPoint (Method b)
876 Report.Error (17, b.Location,
877 "Program `{0}' has more than one entry point defined: `{1}'",
878 b.Module.Builder.ScopeName, b.GetSignatureForError ());
883 if (ReturnType.Kind != MemberKind.Void && ReturnType.BuiltinType != BuiltinTypeSpec.Type.Int)
886 if (parameters.IsEmpty)
889 if (parameters.Count > 1)
892 var ac = parameters.Types [0] as ArrayContainer;
893 return ac != null && ac.Rank == 1 && ac.Element.BuiltinType == BuiltinTypeSpec.Type.String &&
894 (parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
897 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
900 TypeParameter[] tp = CurrentTypeParameters;
902 TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
904 return new TypeParameterExpr (t, loc);
908 return base.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
911 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
913 if (a.Type == pa.Conditional) {
914 if (IsExplicitImpl) {
915 Error_ConditionalAttributeIsNotValid ();
919 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
920 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
924 if (ReturnType.Kind != MemberKind.Void) {
925 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
930 Report.Error (582, Location, "Conditional not valid on interface members");
934 if (MethodData.implementing != null) {
935 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
936 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
937 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
941 for (int i = 0; i < parameters.Count; ++i) {
942 if (parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
943 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
949 if (a.Type == pa.Extension) {
950 a.Error_MisusedExtensionAttribute ();
954 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
957 protected virtual void DefineTypeParameters ()
959 var tparams = CurrentTypeParameters;
961 TypeParameterSpec[] base_tparams = null;
962 TypeParameterSpec[] base_decl_tparams = TypeParameterSpec.EmptyTypes;
963 TypeSpec[] base_targs = TypeSpec.EmptyTypes;
964 if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
965 if (base_method != null) {
966 base_tparams = base_method.GenericDefinition.TypeParameters;
968 if (base_method.DeclaringType.IsGeneric) {
969 base_decl_tparams = base_method.DeclaringType.MemberDefinition.TypeParameters;
971 var base_type_parent = CurrentType;
972 while (base_type_parent.BaseType != base_method.DeclaringType) {
973 base_type_parent = base_type_parent.BaseType;
976 base_targs = base_type_parent.BaseType.TypeArguments;
979 if (base_method.IsGeneric) {
980 ObsoleteAttribute oa;
981 foreach (var base_tp in base_tparams) {
982 oa = base_tp.BaseType.GetAttributeObsolete ();
984 AttributeTester.Report_ObsoleteMessage (oa, base_tp.BaseType.GetSignatureForError (), Location, Report);
987 if (base_tp.InterfacesDefined != null) {
988 foreach (var iface in base_tp.InterfacesDefined) {
989 oa = iface.GetAttributeObsolete ();
991 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
997 if (base_decl_tparams.Length != 0) {
998 base_decl_tparams = base_decl_tparams.Concat (base_tparams).ToArray ();
999 base_targs = base_targs.Concat (tparams.Select<TypeParameter, TypeSpec> (l => l.Type)).ToArray ();
1001 base_decl_tparams = base_tparams;
1002 base_targs = tparams.Select (l => l.Type).ToArray ();
1005 } else if (MethodData.implementing != null) {
1006 base_tparams = MethodData.implementing.GenericDefinition.TypeParameters;
1007 if (MethodData.implementing.DeclaringType.IsGeneric) {
1008 base_decl_tparams = MethodData.implementing.DeclaringType.MemberDefinition.TypeParameters;
1009 foreach (var iface in Parent.CurrentType.Interfaces) {
1010 if (iface == MethodData.implementing.DeclaringType) {
1011 base_targs = iface.TypeArguments;
1019 for (int i = 0; i < tparams.Length; ++i) {
1020 var tp = tparams[i];
1022 if (!tp.ResolveConstraints (this))
1026 // Copy base constraints for override/explicit methods
1028 if (base_tparams != null) {
1029 var base_tparam = base_tparams[i];
1030 var local_tparam = tp.Type;
1031 local_tparam.SpecialConstraint = base_tparam.SpecialConstraint;
1033 var inflator = new TypeParameterInflator (this, CurrentType, base_decl_tparams, base_targs);
1034 base_tparam.InflateConstraints (inflator, local_tparam);
1037 // Check all type argument constraints for possible collision
1038 // introduced by inflating inherited constraints in this context
1040 // Conflict example:
1042 // class A<T> { virtual void Foo<U> () where U : class, T {} }
1043 // class B : A<int> { override void Foo<U> {} }
1045 var local_tparam_targs = local_tparam.TypeArguments;
1046 if (local_tparam_targs != null) {
1047 for (int ii = 0; ii < local_tparam_targs.Length; ++ii) {
1048 var ta = local_tparam_targs [ii];
1049 if (!ta.IsClass && !ta.IsStruct)
1052 if (Constraints.CheckConflictingInheritedConstraint (local_tparam, ta, this, Location)) {
1053 local_tparam.ChangeTypeArgumentToBaseType (ii);
1061 if (MethodData.implementing != null) {
1062 var base_tp = MethodData.implementing.Constraints[i];
1063 if (!tp.Type.HasSameConstraintsImplementation (base_tp)) {
1064 Report.SymbolRelatedToPreviousError (MethodData.implementing);
1065 Report.Error (425, Location,
1066 "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",
1067 tp.GetSignatureForError (), GetSignatureForError (), base_tp.GetSignatureForError (), MethodData.implementing.GetSignatureForError ());
1076 public override bool Define ()
1078 if (!base.Define ())
1081 if (type_expr.Type.Kind == MemberKind.Void && parameters.IsEmpty && MemberName.Arity == 0 && MemberName.Name == Destructor.MetadataName) {
1082 Report.Warning (465, 1, Location,
1083 "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
1086 if (partialMethodImplementation != null && IsPartialDefinition)
1087 MethodBuilder = partialMethodImplementation.MethodBuilder;
1089 if (Compiler.Settings.StdLib && ReturnType.IsSpecialRuntimeType) {
1090 Error1599 (Location, ReturnType, Report);
1094 if (CurrentTypeParameters == null) {
1095 if (base_method != null) {
1096 if (parameters.Count == 1 && ParameterTypes[0].BuiltinType == BuiltinTypeSpec.Type.Object && Name == "Equals")
1097 Parent.PartialContainer.Mark_HasEquals ();
1098 else if (parameters.IsEmpty && Name == "GetHashCode")
1099 Parent.PartialContainer.Mark_HasGetHashCode ();
1103 DefineTypeParameters ();
1106 if (block != null && block.IsIterator) {
1108 // Current method is turned into automatically generated
1109 // wrapper which creates an instance of iterator
1111 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1112 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
1115 if ((ModFlags & Modifiers.STATIC) == 0)
1118 if (parameters.HasExtensionMethodType) {
1119 if (Parent.PartialContainer.IsStatic && !Parent.IsGeneric) {
1120 if (!Parent.IsTopLevel)
1121 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
1122 GetSignatureForError ());
1124 PredefinedAttribute pa = Module.PredefinedAttributes.Extension;
1125 if (!pa.IsDefined) {
1126 Report.Error (1110, Location,
1127 "`{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",
1128 GetSignatureForError ());
1131 ModFlags |= Modifiers.METHOD_EXTENSION;
1132 Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
1133 Spec.DeclaringType.SetExtensionMethodContainer ();
1134 Parent.Module.HasExtensionMethod = true;
1136 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
1137 GetSignatureForError ());
1142 // This is used to track the Entry Point,
1144 var settings = Compiler.Settings;
1145 if (settings.NeedsEntryPoint && Name == "Main" && (settings.MainClass == null || settings.MainClass == Parent.TypeBuilder.FullName)) {
1146 if (IsEntryPoint ()) {
1147 if (Parent.DeclaringAssembly.EntryPoint == null) {
1148 if (Parent.IsGeneric || MemberName.IsGeneric) {
1149 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
1150 GetSignatureForError ());
1153 Parent.DeclaringAssembly.EntryPoint = this;
1156 Error_DuplicateEntryPoint (Parent.DeclaringAssembly.EntryPoint);
1157 Error_DuplicateEntryPoint (this);
1160 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
1161 GetSignatureForError ());
1171 public override void Emit ()
1174 if (IsPartialDefinition) {
1176 // Use partial method implementation builder for partial method declaration attributes
1178 if (partialMethodImplementation != null) {
1179 MethodBuilder = partialMethodImplementation.MethodBuilder;
1185 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
1186 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
1187 GetSignatureForError ());
1190 if (CurrentTypeParameters != null) {
1191 var ge = type_expr as GenericTypeExpr;
1193 ge.CheckConstraints (this);
1195 foreach (Parameter p in parameters.FixedParameters) {
1196 ge = p.TypeExpression as GenericTypeExpr;
1198 ge.CheckConstraints (this);
1201 for (int i = 0; i < CurrentTypeParameters.Length; ++i) {
1202 var tp = CurrentTypeParameters [i];
1203 tp.CheckGenericConstraints ();
1210 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
1211 Module.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
1213 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
1214 Location, MethodBuilder);
1219 public override bool EnableOverloadChecks (MemberCore overload)
1221 // TODO: It can be deleted when members will be defined in correct order
1222 if (overload is Operator)
1223 return overload.EnableOverloadChecks (this);
1225 if (overload is Indexer)
1228 return base.EnableOverloadChecks (overload);
1231 public static void Error1599 (Location loc, TypeSpec t, Report Report)
1233 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
1236 protected override bool ResolveMemberType ()
1238 if (GenericMethod != null) {
1239 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
1240 if (!GenericMethod.Define (this))
1244 return base.ResolveMemberType ();
1247 public void SetPartialDefinition (Method methodDefinition)
1249 caching_flags |= Flags.PartialDefinitionExists;
1250 methodDefinition.partialMethodImplementation = this;
1252 // Ensure we are always using method declaration parameters
1253 for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
1254 parameters [i].Name = methodDefinition.parameters [i].Name;
1255 parameters [i].DefaultValue = methodDefinition.parameters [i].DefaultValue;
1258 if (methodDefinition.attributes == null)
1261 if (attributes == null) {
1262 attributes = methodDefinition.attributes;
1264 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
1269 public abstract class ConstructorInitializer : ExpressionStatement
1271 Arguments argument_list;
1272 MethodSpec base_ctor;
1274 public ConstructorInitializer (Arguments argument_list, Location loc)
1276 this.argument_list = argument_list;
1280 public Arguments Arguments {
1282 return argument_list;
1286 public override Expression CreateExpressionTree (ResolveContext ec)
1288 throw new NotSupportedException ("ET");
1291 protected override Expression DoResolve (ResolveContext ec)
1293 eclass = ExprClass.Value;
1296 var caller_builder = (Constructor) ec.MemberContext;
1299 // Spec mandates that constructor initializer will not have `this' access
1301 using (ec.Set (ResolveContext.Options.BaseInitializer)) {
1302 if (argument_list != null) {
1304 argument_list.Resolve (ec, out dynamic);
1307 ec.Report.Error (1975, loc,
1308 "The constructor call cannot be dynamically dispatched within constructor initializer");
1314 type = ec.CurrentType;
1315 if (this is ConstructorBaseInitializer) {
1316 if (ec.CurrentType.BaseType == null)
1319 type = ec.CurrentType.BaseType;
1320 if (ec.CurrentType.IsStruct) {
1321 ec.Report.Error (522, loc,
1322 "`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
1327 // It is legal to have "this" initializers that take no arguments
1328 // in structs, they are just no-ops.
1330 // struct D { public D (int a) : this () {}
1332 if (ec.CurrentType.IsStruct && argument_list == null)
1336 base_ctor = ConstructorLookup (ec, type, ref argument_list, loc);
1339 // TODO MemberCache: Does it work for inflated types ?
1340 if (base_ctor == caller_builder.Spec){
1341 ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
1342 caller_builder.GetSignatureForError ());
1348 public override void Emit (EmitContext ec)
1350 // It can be null for static initializers
1351 if (base_ctor == null)
1356 Invocation.EmitCall (ec, new CompilerGeneratedThis (type, loc), base_ctor, argument_list, loc);
1359 public override void EmitStatement (EmitContext ec)
1365 public class ConstructorBaseInitializer : ConstructorInitializer {
1366 public ConstructorBaseInitializer (Arguments argument_list, Location l) :
1367 base (argument_list, l)
1372 class GeneratedBaseInitializer: ConstructorBaseInitializer {
1373 public GeneratedBaseInitializer (Location loc):
1379 public class ConstructorThisInitializer : ConstructorInitializer {
1380 public ConstructorThisInitializer (Arguments argument_list, Location l) :
1381 base (argument_list, l)
1386 public class Constructor : MethodCore, IMethodData {
1387 public ConstructorBuilder ConstructorBuilder;
1388 public ConstructorInitializer Initializer;
1389 SecurityType declarative_security;
1390 bool has_compliant_args;
1393 // Modifiers allowed for a constructor.
1395 public const Modifiers AllowedModifiers =
1397 Modifiers.PROTECTED |
1398 Modifiers.INTERNAL |
1404 static readonly string[] attribute_targets = new string [] { "method" };
1406 public static readonly string ConstructorName = ".ctor";
1407 public static readonly string TypeConstructorName = ".cctor";
1410 // The spec claims that static is not permitted, but
1411 // my very own code has static constructors.
1413 public Constructor (DeclSpace parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args,
1414 ConstructorInitializer init, Location loc)
1415 : base (parent, null, null, mod, AllowedModifiers,
1416 new MemberName (name, loc), attrs, args)
1421 public bool HasCompliantArgs {
1422 get { return has_compliant_args; }
1425 public override AttributeTargets AttributeTargets {
1426 get { return AttributeTargets.Constructor; }
1430 // Returns true if this is a default constructor
1432 public bool IsDefault ()
1434 if ((ModFlags & Modifiers.STATIC) != 0)
1435 return parameters.IsEmpty;
1437 return parameters.IsEmpty &&
1438 (Initializer is ConstructorBaseInitializer) &&
1439 (Initializer.Arguments == null);
1442 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1444 if (a.IsValidSecurityAttribute ()) {
1445 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
1449 if (a.Type == pa.MethodImpl) {
1450 is_external_implementation = a.IsInternalCall ();
1453 ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1456 protected override bool CheckBase ()
1458 if ((ModFlags & Modifiers.STATIC) != 0) {
1459 if (!parameters.IsEmpty) {
1460 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
1461 GetSignatureForError ());
1465 // the rest can be ignored
1469 // Check whether arguments were correct.
1470 if (!DefineParameters (parameters))
1473 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1474 Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1476 if (Parent.PartialContainer.Kind == MemberKind.Struct && parameters.IsEmpty) {
1477 Report.Error (568, Location,
1478 "Structs cannot contain explicit parameterless constructors");
1482 CheckProtectedModifier ();
1488 // Creates the ConstructorBuilder
1490 public override bool Define ()
1492 if (ConstructorBuilder != null)
1495 var ca = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
1497 if ((ModFlags & Modifiers.STATIC) != 0) {
1498 ca |= MethodAttributes.Static | MethodAttributes.Private;
1500 ca |= ModifiersExtensions.MethodAttr (ModFlags);
1503 if (!CheckAbstractAndExtern (block != null))
1506 // Check if arguments were correct.
1510 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
1511 ca, CallingConventions,
1512 parameters.GetMetaInfo ());
1514 spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, Compiler.BuiltinTypes.Void, ConstructorBuilder, parameters, ModFlags);
1516 Parent.MemberCache.AddMember (spec);
1518 // It's here only to report an error
1519 if (block != null && block.IsIterator) {
1520 member_type = Compiler.BuiltinTypes.Void;
1521 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1530 public override void Emit ()
1532 if (Parent.PartialContainer.IsComImport) {
1533 if (!IsDefault ()) {
1534 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
1535 Parent.GetSignatureForError ());
1538 // Set as internal implementation and reset block data
1539 // to ensure no IL is generated
1540 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
1544 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
1545 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (ConstructorBuilder);
1547 if (OptAttributes != null)
1548 OptAttributes.Emit ();
1553 // If we use a "this (...)" constructor initializer, then
1554 // do not emit field initializers, they are initialized in the other constructor
1556 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
1557 !(Initializer is ConstructorThisInitializer);
1559 BlockContext bc = new BlockContext (this, block, Compiler.BuiltinTypes.Void);
1560 bc.Set (ResolveContext.Options.ConstructorScope);
1562 if (emit_field_initializers)
1563 Parent.PartialContainer.ResolveFieldInitializers (bc);
1565 if (block != null) {
1566 // If this is a non-static `struct' constructor and doesn't have any
1567 // initializer, it must initialize all of the struct's fields.
1568 if ((Parent.PartialContainer.Kind == MemberKind.Struct) &&
1569 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
1570 block.AddThisVariable (bc, Parent, Location);
1572 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
1573 if (Parent.PartialContainer.Kind == MemberKind.Class && Initializer == null)
1574 Initializer = new GeneratedBaseInitializer (Location);
1576 if (Initializer != null) {
1577 block.AddScopeStatement (new StatementExpression (Initializer));
1582 parameters.ApplyAttributes (this, ConstructorBuilder);
1584 SourceMethod source = SourceMethod.Create (Parent, ConstructorBuilder, block);
1586 if (block != null) {
1587 if (block.Resolve (null, bc, this)) {
1588 EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType);
1589 ec.With (EmitContext.Options.ConstructorScope, true);
1591 if (!ec.HasReturnLabel && bc.HasReturnLabel) {
1592 ec.ReturnLabel = bc.ReturnLabel;
1593 ec.HasReturnLabel = true;
1601 source.CloseMethod ();
1603 if (declarative_security != null) {
1604 foreach (var de in declarative_security) {
1606 ConstructorBuilder.__AddDeclarativeSecurity (de);
1608 ConstructorBuilder.AddDeclarativeSecurity (de.Key, de.Value);
1616 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate)
1618 // Is never override
1619 bestCandidate = null;
1623 public override string GetSignatureForError()
1625 return base.GetSignatureForError () + parameters.GetSignatureForError ();
1628 public override string[] ValidAttributeTargets {
1630 return attribute_targets;
1634 protected override bool VerifyClsCompliance ()
1636 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
1640 if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
1641 foreach (TypeSpec param in parameters.Types) {
1642 if (param.IsArray) {
1648 has_compliant_args = true;
1652 #region IMethodData Members
1654 public MemberName MethodName {
1660 public TypeSpec ReturnType {
1666 public EmitContext CreateEmitContext (ILGenerator ig)
1668 throw new NotImplementedException ();
1671 public bool IsExcluded()
1676 GenericMethod IMethodData.GenericMethod {
1682 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
1689 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
1691 public interface IMethodData : IMemberContext
1693 CallingConventions CallingConventions { get; }
1694 Location Location { get; }
1695 MemberName MethodName { get; }
1696 TypeSpec ReturnType { get; }
1697 GenericMethod GenericMethod { get; }
1698 ParametersCompiled ParameterInfo { get; }
1699 MethodSpec Spec { get; }
1701 Attributes OptAttributes { get; }
1702 ToplevelBlock Block { get; set; }
1704 EmitContext CreateEmitContext (ILGenerator ig);
1705 void EmitExtraSymbolInfo (SourceMethod source);
1709 // Encapsulates most of the Method's state
1711 public class MethodData
1714 static FieldInfo methodbuilder_attrs_field;
1717 public readonly IMethodData method;
1719 public readonly GenericMethod GenericMethod;
1722 // Are we implementing an interface ?
1724 public MethodSpec implementing;
1729 protected InterfaceMemberBase member;
1730 protected Modifiers modifiers;
1731 protected MethodAttributes flags;
1732 protected TypeSpec declaring_type;
1733 protected MethodSpec parent_method;
1735 MethodBuilder builder;
1736 public MethodBuilder MethodBuilder {
1742 public TypeSpec DeclaringType {
1744 return declaring_type;
1748 public MethodData (InterfaceMemberBase member,
1749 Modifiers modifiers, MethodAttributes flags, IMethodData method)
1751 this.member = member;
1752 this.modifiers = modifiers;
1755 this.method = method;
1758 public MethodData (InterfaceMemberBase member,
1759 Modifiers modifiers, MethodAttributes flags,
1760 IMethodData method, MethodBuilder builder,
1761 GenericMethod generic, MethodSpec parent_method)
1762 : this (member, modifiers, flags, method)
1764 this.builder = builder;
1765 this.GenericMethod = generic;
1766 this.parent_method = parent_method;
1769 public bool Define (DeclSpace parent, string method_full_name, Report Report)
1771 TypeContainer container = parent.PartialContainer;
1773 PendingImplementation pending = container.PendingImplementations;
1774 if (pending != null){
1775 implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this);
1777 if (member.InterfaceType != null){
1778 if (implementing == null){
1779 if (member is PropertyBase) {
1780 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
1781 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
1782 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
1785 Report.Error (539, method.Location,
1786 "`{0}.{1}' in explicit interface declaration is not a member of interface",
1787 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
1791 if (implementing.IsAccessor && !(method is AbstractPropertyEventMethod)) {
1792 Report.SymbolRelatedToPreviousError (implementing);
1793 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
1794 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1798 if (implementing != null) {
1799 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
1800 if (prop_method == null) {
1801 if (implementing.IsAccessor) {
1802 Report.SymbolRelatedToPreviousError (implementing);
1803 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}'",
1804 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1806 } else if (implementing.DeclaringType.IsInterface) {
1807 if (!implementing.IsAccessor) {
1808 Report.SymbolRelatedToPreviousError (implementing);
1809 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
1810 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
1812 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
1813 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
1814 Report.SymbolRelatedToPreviousError (implementing);
1815 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
1816 method.GetSignatureForError (), implementing.GetSignatureForError ());
1825 // For implicit implementations, make sure we are public, for
1826 // explicit implementations, make sure we are private.
1828 if (implementing != null){
1830 // Setting null inside this block will trigger a more
1831 // verbose error reporting for missing interface implementations
1833 // The "candidate" function has been flagged already
1834 // but it wont get cleared
1836 if (member.IsExplicitImpl){
1837 if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
1838 Report.SymbolRelatedToPreviousError (implementing);
1839 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
1840 method.GetSignatureForError ());
1843 if (implementing.DeclaringType.IsInterface) {
1845 // If this is an interface method implementation,
1846 // check for public accessibility
1848 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
1850 implementing = null;
1852 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
1853 // We may never be private.
1854 implementing = null;
1856 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
1858 // We may be protected if we're overriding something.
1860 implementing = null;
1865 // Static is not allowed
1867 if ((modifiers & Modifiers.STATIC) != 0){
1868 implementing = null;
1873 // If implementing is still valid, set flags
1875 if (implementing != null){
1877 // When implementing interface methods, set NewSlot
1878 // unless, we are overwriting a method.
1880 if (implementing.DeclaringType.IsInterface){
1881 if ((modifiers & Modifiers.OVERRIDE) == 0)
1882 flags |= MethodAttributes.NewSlot;
1885 flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;
1887 // Set Final unless we're virtual, abstract or already overriding a method.
1888 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
1889 flags |= MethodAttributes.Final;
1892 // clear the pending implementation flag (requires explicit methods to be defined first)
1894 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName,
1895 member.InterfaceType, this, member.IsExplicitImpl);
1898 // Update indexer accessor name to match implementing abstract accessor
1900 if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
1901 method_full_name = implementing.MemberDefinition.Name;
1904 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
1906 if (builder == null)
1909 // if (container.CurrentType != null)
1910 // declaring_type = container.CurrentType;
1912 declaring_type = container.Definition;
1914 if (implementing != null && member.IsExplicitImpl) {
1915 container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
1923 /// Create the MethodBuilder for the method
1925 void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
1927 var return_type = method.ReturnType.GetMetaInfo ();
1928 var p_types = param.GetMetaInfo ();
1930 if (builder == null) {
1931 builder = container.TypeBuilder.DefineMethod (
1932 method_name, flags, method.CallingConventions,
1933 return_type, p_types);
1938 // Generic method has been already defined to resolve method parameters
1939 // correctly when they use type parameters
1941 builder.SetParameters (p_types);
1942 builder.SetReturnType (return_type);
1943 if (builder.Attributes != flags) {
1945 builder.__SetAttributes (flags);
1948 if (methodbuilder_attrs_field == null)
1949 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
1950 methodbuilder_attrs_field.SetValue (builder, flags);
1952 container.Compiler.Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
1961 public void Emit (DeclSpace parent)
1963 if (GenericMethod != null)
1964 GenericMethod.EmitAttributes ();
1966 var mc = (IMemberContext) method;
1968 method.ParameterInfo.ApplyAttributes (mc, MethodBuilder);
1970 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
1972 ToplevelBlock block = method.Block;
1973 if (block != null) {
1974 BlockContext bc = new BlockContext (mc, block, method.ReturnType);
1975 if (block.Resolve (null, bc, method)) {
1976 EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator ());
1977 if (!ec.HasReturnLabel && bc.HasReturnLabel) {
1978 ec.ReturnLabel = bc.ReturnLabel;
1979 ec.HasReturnLabel = true;
1986 if (source != null) {
1987 method.EmitExtraSymbolInfo (source);
1988 source.CloseMethod ();
1993 public class Destructor : MethodOrOperator
1995 const Modifiers AllowedModifiers =
1999 static readonly string[] attribute_targets = new string [] { "method" };
2001 public static readonly string MetadataName = "Finalize";
2003 public Destructor (DeclSpace parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
2004 : base (parent, null, null, mod, AllowedModifiers,
2005 new MemberName (MetadataName, l), attrs, parameters)
2007 ModFlags &= ~Modifiers.PRIVATE;
2008 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
2011 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2013 if (a.Type == pa.Conditional) {
2014 Error_ConditionalAttributeIsNotValid ();
2018 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2021 protected override bool CheckBase ()
2023 // Don't check base, destructors have special syntax
2027 public override void Emit()
2029 var base_type = Parent.PartialContainer.BaseType;
2030 if (base_type != null && Block != null) {
2031 var base_dtor = MemberCache.FindMember (base_type,
2032 new MemberFilter (MetadataName, 0, MemberKind.Destructor, null, null), BindingRestriction.InstanceOnly) as MethodSpec;
2034 if (base_dtor == null)
2035 throw new NotImplementedException ();
2037 MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
2038 method_expr.InstanceExpression = new BaseThis (base_type, Location);
2040 var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation);
2041 var finaly_block = new ExplicitBlock (block, Location, Location);
2044 // 0-size arguments to avoid CS0250 error
2045 // TODO: Should use AddScopeStatement or something else which emits correct
2048 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0))));
2050 var tf = new TryFinally (try_block, finaly_block, Location);
2051 block.WrapIntoDestructor (tf, try_block);
2057 public override string GetSignatureForError ()
2059 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
2062 protected override bool ResolveMemberType ()
2064 member_type = Compiler.BuiltinTypes.Void;
2068 public override string[] ValidAttributeTargets {
2070 return attribute_targets;
2075 // Ooouh Martin, templates are missing here.
2076 // When it will be possible move here a lot of child code and template method type.
2077 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
2078 protected MethodData method_data;
2079 protected ToplevelBlock block;
2080 protected SecurityType declarative_security;
2082 protected readonly string prefix;
2084 ReturnParameter return_attributes;
2086 public AbstractPropertyEventMethod (InterfaceMemberBase member, string prefix, Attributes attrs, Location loc)
2087 : base (member.Parent, SetupName (prefix, member, loc), attrs)
2089 this.prefix = prefix;
2092 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
2094 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
2097 public void UpdateName (InterfaceMemberBase member)
2099 SetMemberName (SetupName (prefix, member, Location));
2102 #region IMethodData Members
2104 public ToplevelBlock Block {
2114 public CallingConventions CallingConventions {
2116 return CallingConventions.Standard;
2120 public EmitContext CreateEmitContext (ILGenerator ig)
2122 return new EmitContext (this, ig, ReturnType);
2125 public bool IsExcluded ()
2130 GenericMethod IMethodData.GenericMethod {
2136 public MemberName MethodName {
2142 public TypeSpec[] ParameterTypes {
2144 return ParameterInfo.Types;
2148 public abstract ParametersCompiled ParameterInfo { get ; }
2149 public abstract TypeSpec ReturnType { get; }
2153 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2155 if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
2156 Report.Error (1667, a.Location,
2157 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
2158 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
2162 if (a.IsValidSecurityAttribute ()) {
2163 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
2167 if (a.Target == AttributeTargets.Method) {
2168 method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
2172 if (a.Target == AttributeTargets.ReturnValue) {
2173 if (return_attributes == null)
2174 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2176 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
2180 ApplyToExtraTarget (a, ctor, cdata, pa);
2183 protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2185 throw new NotSupportedException ("You forgot to define special attribute target handling");
2188 // It is not supported for the accessors
2189 public sealed override bool Define()
2191 throw new NotSupportedException ();
2194 public virtual void Emit (DeclSpace parent)
2196 method_data.Emit (parent);
2198 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
2199 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
2200 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
2201 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
2203 if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2204 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2205 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
2206 } else if (ReturnType.HasDynamicElement) {
2207 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2208 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
2211 if (OptAttributes != null)
2212 OptAttributes.Emit ();
2214 if (declarative_security != null) {
2215 foreach (var de in declarative_security) {
2217 method_data.MethodBuilder.__AddDeclarativeSecurity (de);
2219 method_data.MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2227 public override bool EnableOverloadChecks (MemberCore overload)
2229 if (overload is MethodCore) {
2230 caching_flags |= Flags.MethodOverloadsExist;
2234 // This can only happen with indexers and it will
2235 // be catched as indexer difference
2236 if (overload is AbstractPropertyEventMethod)
2242 public override bool IsClsComplianceRequired()
2247 public MethodSpec Spec { get; protected set; }
2250 // Represents header string for documentation comment.
2252 public override string DocCommentHeader {
2253 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
2256 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
2260 public class Operator : MethodOrOperator {
2262 const Modifiers AllowedModifiers =
2268 public enum OpType : byte {
2278 // Unary and Binary operators
2301 // Implicit and Explicit
2305 // Just because of enum
2309 public readonly OpType OperatorType;
2311 static readonly string [] [] names;
2315 names = new string[(int)OpType.TOP][];
2316 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
2317 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
2318 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
2319 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
2320 names [(int) OpType.True] = new string [] { "true", "op_True" };
2321 names [(int) OpType.False] = new string [] { "false", "op_False" };
2322 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
2323 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
2324 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
2325 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
2326 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
2327 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
2328 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
2329 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
2330 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
2331 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
2332 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
2333 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
2334 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
2335 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
2336 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
2337 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
2338 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
2339 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
2340 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
2341 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
2344 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
2345 Modifiers mod_flags, ParametersCompiled parameters,
2346 ToplevelBlock block, Attributes attrs, Location loc)
2347 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
2348 new MemberName (GetMetadataName (type), loc), attrs, parameters)
2350 OperatorType = type;
2354 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2356 if (a.Type == pa.Conditional) {
2357 Error_ConditionalAttributeIsNotValid ();
2361 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2364 public override bool Define ()
2366 const Modifiers RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
2367 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
2368 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
2371 if (!base.Define ())
2374 if (block != null && block.IsIterator) {
2376 // Current method is turned into automatically generated
2377 // wrapper which creates an instance of iterator
2379 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
2380 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
2383 // imlicit and explicit operator of same types are not allowed
2384 if (OperatorType == OpType.Explicit)
2385 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
2386 else if (OperatorType == OpType.Implicit)
2387 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
2389 TypeSpec declaring_type = Parent.CurrentType;
2390 TypeSpec return_type = MemberType;
2391 TypeSpec first_arg_type = ParameterTypes [0];
2393 TypeSpec first_arg_type_unwrap = first_arg_type;
2394 if (first_arg_type.IsNullableType)
2395 first_arg_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (first_arg_type);
2397 TypeSpec return_type_unwrap = return_type;
2398 if (return_type.IsNullableType)
2399 return_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (return_type);
2402 // Rules for conversion operators
2404 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2405 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type) {
2406 Report.Error (555, Location,
2407 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
2412 if (declaring_type == return_type || declaring_type == return_type_unwrap) {
2413 conv_type = first_arg_type;
2414 } else if (declaring_type == first_arg_type || declaring_type == first_arg_type_unwrap) {
2415 conv_type = return_type;
2417 Report.Error (556, Location,
2418 "User-defined conversion must convert to or from the enclosing type");
2422 if (conv_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2423 Report.Error (1964, Location,
2424 "User-defined conversion `{0}' cannot convert to or from the dynamic type",
2425 GetSignatureForError ());
2430 if (conv_type.IsInterface) {
2431 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
2432 GetSignatureForError ());
2436 if (conv_type.IsClass) {
2437 if (TypeSpec.IsBaseClass (declaring_type, conv_type, true)) {
2438 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
2439 GetSignatureForError ());
2443 if (TypeSpec.IsBaseClass (conv_type, declaring_type, false)) {
2444 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
2445 GetSignatureForError ());
2449 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
2450 if (first_arg_type != declaring_type || parameters.Types[1].BuiltinType != BuiltinTypeSpec.Type.Int) {
2451 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");
2454 } else if (parameters.Count == 1) {
2455 // Checks for Unary operators
2457 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
2458 if (return_type != declaring_type && !TypeSpec.IsBaseClass (return_type, declaring_type, false)) {
2459 Report.Error (448, Location,
2460 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
2463 if (first_arg_type != declaring_type) {
2465 559, Location, "The parameter type for ++ or -- operator must be the containing type");
2470 if (first_arg_type_unwrap != declaring_type) {
2471 Report.Error (562, Location,
2472 "The parameter type of a unary operator must be the containing type");
2476 if (OperatorType == OpType.True || OperatorType == OpType.False) {
2477 if (return_type.BuiltinType != BuiltinTypeSpec.Type.Bool) {
2480 "The return type of operator True or False " +
2486 } else if (first_arg_type_unwrap != declaring_type) {
2487 // Checks for Binary operators
2489 var second_arg_type = ParameterTypes[1];
2490 if (second_arg_type.IsNullableType)
2491 second_arg_type = Nullable.NullableInfo.GetUnderlyingType (second_arg_type);
2493 if (second_arg_type != declaring_type) {
2494 Report.Error (563, Location,
2495 "One of the parameters of a binary operator must be the containing type");
2503 protected override bool ResolveMemberType ()
2505 if (!base.ResolveMemberType ())
2508 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2512 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate)
2514 // Operator cannot be override
2515 bestCandidate = null;
2519 public static string GetName (OpType ot)
2521 return names [(int) ot] [0];
2524 public static string GetName (string metadata_name)
2526 for (int i = 0; i < names.Length; ++i) {
2527 if (names [i] [1] == metadata_name)
2528 return names [i] [0];
2533 public static string GetMetadataName (OpType ot)
2535 return names [(int) ot] [1];
2538 public static string GetMetadataName (string name)
2540 for (int i = 0; i < names.Length; ++i) {
2541 if (names [i] [0] == name)
2542 return names [i] [1];
2547 public static OpType? GetType (string metadata_name)
2549 for (int i = 0; i < names.Length; ++i) {
2550 if (names[i][1] == metadata_name)
2557 public OpType GetMatchingOperator ()
2559 switch (OperatorType) {
2560 case OpType.Equality:
2561 return OpType.Inequality;
2562 case OpType.Inequality:
2563 return OpType.Equality;
2565 return OpType.False;
2568 case OpType.GreaterThan:
2569 return OpType.LessThan;
2570 case OpType.LessThan:
2571 return OpType.GreaterThan;
2572 case OpType.GreaterThanOrEqual:
2573 return OpType.LessThanOrEqual;
2574 case OpType.LessThanOrEqual:
2575 return OpType.GreaterThanOrEqual;
2581 public override string GetSignatureForError ()
2583 StringBuilder sb = new StringBuilder ();
2584 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2585 sb.AppendFormat ("{0}.{1} operator {2}",
2586 Parent.GetSignatureForError (), GetName (OperatorType), type_expr.GetSignatureForError ());
2589 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
2592 sb.Append (parameters.GetSignatureForError ());
2593 return sb.ToString ();