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;
57 public override Variance ExpectedMemberTypeVariance {
59 return Variance.Covariant;
64 // Returns the System.Type array for the parameters of this method
66 public TypeSpec [] ParameterTypes {
68 return parameters.Types;
72 public ParametersCompiled ParameterInfo {
78 AParametersCollection IParametersMember.Parameters {
79 get { return parameters; }
82 public ToplevelBlock Block {
92 public CallingConventions CallingConventions {
94 CallingConventions cc = parameters.CallingConvention;
96 if ((ModFlags & Modifiers.STATIC) == 0)
97 cc |= CallingConventions.HasThis;
99 // FIXME: How is `ExplicitThis' used in C#?
105 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
107 bool res = base.CheckOverrideAgainstBase (base_member);
110 // Check that the permissions are not being changed
112 if (!CheckAccessModifiers (this, base_member)) {
113 Error_CannotChangeAccessModifiers (this, base_member);
120 protected override bool CheckBase ()
122 // Check whether arguments were correct.
123 if (!DefineParameters (parameters))
126 return base.CheckBase ();
130 // Represents header string for documentation comment.
132 public override string DocCommentHeader
137 public override void Emit ()
139 if ((ModFlags & Modifiers.COMPILER_GENERATED) == 0) {
140 parameters.CheckConstraints (this);
146 public override bool EnableOverloadChecks (MemberCore overload)
148 if (overload is MethodCore) {
149 caching_flags |= Flags.MethodOverloadsExist;
153 if (overload is AbstractPropertyEventMethod)
156 return base.EnableOverloadChecks (overload);
159 public override string GetSignatureForDocumentation ()
161 string s = base.GetSignatureForDocumentation ();
162 if (MemberName.Arity > 0)
163 s += "``" + MemberName.Arity.ToString ();
165 return s + parameters.GetSignatureForDocumentation ();
168 public MethodSpec Spec {
172 protected override bool VerifyClsCompliance ()
174 if (!base.VerifyClsCompliance ())
177 if (parameters.HasArglist) {
178 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
181 if (member_type != null && !member_type.IsCLSCompliant ()) {
182 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
183 GetSignatureForError ());
186 parameters.VerifyClsCompliance (this);
191 public interface IGenericMethodDefinition : IMemberDefinition
193 TypeParameterSpec[] TypeParameters { get; }
194 int TypeParametersCount { get; }
196 // MethodInfo MakeGenericMethod (TypeSpec[] targs);
199 public sealed class MethodSpec : MemberSpec, IParametersMember
201 MethodBase metaInfo, inflatedMetaInfo;
202 AParametersCollection parameters;
206 TypeParameterSpec[] constraints;
208 public MethodSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition details, TypeSpec returnType,
209 MethodBase info, AParametersCollection parameters, Modifiers modifiers)
210 : base (kind, declaringType, details, modifiers)
212 this.metaInfo = info;
213 this.parameters = parameters;
214 this.returnType = returnType;
219 public override int Arity {
221 return IsGeneric ? GenericDefinition.TypeParametersCount : 0;
225 public TypeParameterSpec[] Constraints {
227 if (constraints == null && IsGeneric)
228 constraints = GenericDefinition.TypeParameters;
234 public bool IsConstructor {
236 return Kind == MemberKind.Constructor;
240 public IGenericMethodDefinition GenericDefinition {
242 return (IGenericMethodDefinition) definition;
246 public bool IsExtensionMethod {
248 return IsStatic && parameters.HasExtensionMethodType;
252 public bool IsSealed {
254 return (Modifiers & Modifiers.SEALED) != 0;
258 // When is virtual or abstract
259 public bool IsVirtual {
261 return (Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) != 0;
265 public bool IsReservedMethod {
267 return Kind == MemberKind.Operator || IsAccessor;
271 TypeSpec IInterfaceMemberSpec.MemberType {
277 public AParametersCollection Parameters {
283 public TypeSpec ReturnType {
289 public TypeSpec[] TypeArguments {
297 public MethodSpec GetGenericMethodDefinition ()
299 if (!IsGeneric && !DeclaringType.IsGeneric)
302 return MemberCache.GetMember (declaringType, this);
305 public MethodBase GetMetaInfo ()
308 // inflatedMetaInfo is extra field needed for cases where we
309 // inflate method but another nested type can later inflate
310 // again (the cache would be build with inflated metaInfo) and
311 // TypeBuilder can work with method definitions only
313 if (inflatedMetaInfo == null) {
314 if ((state & StateFlags.PendingMetaInflate) != 0) {
315 var dt_meta = DeclaringType.GetMetaInfo ();
317 if (DeclaringType.IsTypeBuilder) {
319 inflatedMetaInfo = TypeBuilder.GetConstructor (dt_meta, (ConstructorInfo) metaInfo);
321 inflatedMetaInfo = TypeBuilder.GetMethod (dt_meta, (MethodInfo) metaInfo);
324 // it should not be reached
325 throw new NotImplementedException ();
327 inflatedMetaInfo = MethodInfo.GetMethodFromHandle (metaInfo.MethodHandle, dt_meta.TypeHandle);
331 state &= ~StateFlags.PendingMetaInflate;
333 inflatedMetaInfo = metaInfo;
337 if ((state & StateFlags.PendingMakeMethod) != 0) {
338 var sre_targs = new MetaType[targs.Length];
339 for (int i = 0; i < sre_targs.Length; ++i)
340 sre_targs[i] = targs[i].GetMetaInfo ();
342 inflatedMetaInfo = ((MethodInfo) inflatedMetaInfo).MakeGenericMethod (sre_targs);
343 state &= ~StateFlags.PendingMakeMethod;
346 return inflatedMetaInfo;
349 public override string GetSignatureForDocumentation ()
353 case MemberKind.Constructor:
356 case MemberKind.Method:
358 name = Name + "``" + Arity.ToString ();
368 name = DeclaringType.GetSignatureForDocumentation () + "." + name + parameters.GetSignatureForDocumentation ();
369 if (Kind == MemberKind.Operator) {
370 var op = Operator.GetType (Name).Value;
371 if (op == Operator.OpType.Explicit || op == Operator.OpType.Implicit) {
372 name += "~" + ReturnType.GetSignatureForDocumentation ();
379 public override string GetSignatureForError ()
383 name = DeclaringType.GetSignatureForError () + "." + DeclaringType.Name;
384 } else if (Kind == MemberKind.Operator) {
385 var op = Operator.GetType (Name).Value;
386 if (op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) {
387 name = DeclaringType.GetSignatureForError () + "." + Operator.GetName (op) + " operator " + returnType.GetSignatureForError ();
389 name = DeclaringType.GetSignatureForError () + ".operator " + Operator.GetName (op);
391 } else if (IsAccessor) {
392 int split = Name.IndexOf ('_');
393 name = Name.Substring (split + 1);
394 var postfix = Name.Substring (0, split);
396 var pc = parameters.Count;
397 if (pc > 0 && postfix == "get") {
398 name = "this" + parameters.GetSignatureForError ("[", "]", pc);
399 } else if (pc > 1 && postfix == "set") {
400 name = "this" + parameters.GetSignatureForError ("[", "]", pc - 1);
404 return DeclaringType.GetSignatureForError () + "." + name + "." + postfix;
406 name = base.GetSignatureForError ();
408 name += "<" + TypeManager.CSharpName (targs) + ">";
410 name += "<" + TypeManager.CSharpName (GenericDefinition.TypeParameters) + ">";
413 return name + parameters.GetSignatureForError ();
416 public override MemberSpec InflateMember (TypeParameterInflator inflator)
418 var ms = (MethodSpec) base.InflateMember (inflator);
419 ms.inflatedMetaInfo = null;
420 ms.returnType = inflator.Inflate (returnType);
421 ms.parameters = parameters.Inflate (inflator);
423 ms.constraints = TypeParameterSpec.InflateConstraints (inflator, Constraints);
428 public MethodSpec MakeGenericMethod (IMemberContext context, params TypeSpec[] targs)
431 throw new ArgumentNullException ();
433 // if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
436 //if (generic_intances == null)
437 // generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
439 var inflator = new TypeParameterInflator (context, DeclaringType, GenericDefinition.TypeParameters, targs);
441 var inflated = (MethodSpec) MemberwiseClone ();
442 inflated.declaringType = inflator.TypeInstance;
443 inflated.returnType = inflator.Inflate (returnType);
444 inflated.parameters = parameters.Inflate (inflator);
445 inflated.targs = targs;
446 inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
447 inflated.state |= StateFlags.PendingMakeMethod;
449 // if (inflated.parent == null)
450 // inflated.parent = parent;
452 //generic_intances.Add (targs, inflated);
456 public MethodSpec Mutate (TypeParameterMutator mutator)
458 var targs = TypeArguments;
460 targs = mutator.Mutate (targs);
462 var decl = DeclaringType;
463 if (DeclaringType.IsGenericOrParentIsGeneric) {
464 decl = mutator.Mutate (decl);
467 if (targs == TypeArguments && decl == DeclaringType)
470 var ms = (MethodSpec) MemberwiseClone ();
471 if (decl != DeclaringType) {
472 ms.inflatedMetaInfo = null;
473 ms.declaringType = decl;
474 ms.state |= StateFlags.PendingMetaInflate;
479 ms.state |= StateFlags.PendingMakeMethod;
485 public override List<TypeSpec> ResolveMissingDependencies ()
487 var missing = returnType.ResolveMissingDependencies ();
488 foreach (var pt in parameters.Types) {
489 var m = pt.GetMissingDependencies ();
494 missing = new List<TypeSpec> ();
496 missing.AddRange (m);
502 public void SetMetaInfo (MethodInfo info)
504 if (this.metaInfo != null)
505 throw new InternalErrorException ("MetaInfo reset");
507 this.metaInfo = info;
511 public abstract class MethodOrOperator : MethodCore, IMethodData
513 public MethodBuilder MethodBuilder;
514 ReturnParameter return_attributes;
515 SecurityType declarative_security;
516 protected MethodData MethodData;
518 static readonly string[] attribute_targets = new string [] { "method", "return" };
520 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, Modifiers mod,
521 Modifiers allowed_mod, MemberName name,
522 Attributes attrs, ParametersCompiled parameters)
523 : base (parent, generic, type, mod, allowed_mod, name,
528 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
530 if (a.Target == AttributeTargets.ReturnValue) {
531 if (return_attributes == null)
532 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
534 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
538 if (a.Type == pa.MethodImpl) {
539 is_external_implementation = a.IsInternalCall ();
542 if (a.Type == pa.DllImport) {
543 const Modifiers extern_static = Modifiers.EXTERN | Modifiers.STATIC;
544 if ((ModFlags & extern_static) != extern_static) {
545 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
547 is_external_implementation = true;
550 if (a.IsValidSecurityAttribute ()) {
551 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
555 if (MethodBuilder != null)
556 MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
559 public override AttributeTargets AttributeTargets {
561 return AttributeTargets.Method;
565 protected override bool CheckForDuplications ()
567 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
570 public virtual EmitContext CreateEmitContext (ILGenerator ig)
572 return new EmitContext (this, ig, MemberType);
575 public override bool Define ()
584 if (this is Operator)
585 kind = MemberKind.Operator;
586 else if (this is Destructor)
587 kind = MemberKind.Destructor;
589 kind = MemberKind.Method;
591 if (IsPartialDefinition) {
592 caching_flags &= ~Flags.Excluded_Undetected;
593 caching_flags |= Flags.Excluded;
595 // Add to member cache only when a partial method implementation has not been found yet
596 if ((caching_flags & Flags.PartialDefinitionExists) == 0) {
597 // MethodBase mb = new PartialMethodDefinitionInfo (this);
599 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, null, parameters, ModFlags);
600 Parent.MemberCache.AddMember (spec);
606 MethodData = new MethodData (
607 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
609 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName), Report))
612 MethodBuilder = MethodData.MethodBuilder;
614 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, MethodBuilder, parameters, ModFlags);
615 if (MemberName.Arity > 0)
616 spec.IsGeneric = true;
618 Parent.MemberCache.AddMember (this, MethodBuilder.Name, spec);
623 protected override void DoMemberTypeIndependentChecks ()
625 base.DoMemberTypeIndependentChecks ();
627 CheckAbstractAndExtern (block != null);
629 if ((ModFlags & Modifiers.PARTIAL) != 0) {
630 for (int i = 0; i < parameters.Count; ++i) {
631 IParameterData p = parameters.FixedParameters [i];
632 if (p.ModFlags == Parameter.Modifier.OUT) {
633 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
634 GetSignatureForError ());
637 if (p.HasDefaultValue && IsPartialImplementation)
638 ((Parameter) p).Warning_UselessOptionalParameter (Report);
643 protected override void DoMemberTypeDependentChecks ()
645 base.DoMemberTypeDependentChecks ();
647 if (MemberType.IsStatic) {
648 Error_StaticReturnType ();
652 public override void Emit ()
654 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
655 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (MethodBuilder);
656 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
657 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (MethodBuilder);
659 if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
660 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
661 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
662 } else if (ReturnType.HasDynamicElement) {
663 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
664 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
667 if (OptAttributes != null)
668 OptAttributes.Emit ();
670 if (declarative_security != null) {
671 foreach (var de in declarative_security) {
673 MethodBuilder.__AddDeclarativeSecurity (de);
675 MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
680 if (type_expr != null)
681 ConstraintChecker.Check (this, member_type, type_expr.Location);
685 if (MethodData != null)
686 MethodData.Emit (Parent);
692 protected void Error_ConditionalAttributeIsNotValid ()
694 Report.Error (577, Location,
695 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
696 GetSignatureForError ());
699 public bool IsPartialDefinition {
701 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
705 public bool IsPartialImplementation {
707 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
711 public override string[] ValidAttributeTargets {
713 return attribute_targets;
717 #region IMethodData Members
719 bool IMethodData.IsAccessor {
725 public TypeSpec ReturnType {
731 public MemberName MethodName {
738 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
740 public override string[] ConditionalConditions ()
742 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
745 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
746 return new string [0];
748 caching_flags &= ~Flags.Excluded_Undetected;
751 if (base_method == null) {
752 if (OptAttributes == null)
755 Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
759 conditions = new string[attrs.Length];
760 for (int i = 0; i < conditions.Length; ++i)
761 conditions[i] = attrs[i].GetConditionalAttributeValue ();
763 conditions = base_method.MemberDefinition.ConditionalConditions();
766 if (conditions != null)
767 caching_flags |= Flags.Excluded;
772 GenericMethod IMethodData.GenericMethod {
774 return GenericMethod;
778 public virtual void EmitExtraSymbolInfo (SourceMethod source)
785 public class SourceMethod : IMethodDef
788 SourceMethodBuilder builder;
790 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
792 this.method = method;
794 builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
798 get { return method.Name; }
804 var mb = method as MethodBuilder;
806 token = mb.GetToken ();
808 token = ((ConstructorBuilder) method).GetToken ();
810 if (token.IsPseudoToken)
811 return ((ModuleBuilder) method.Module).ResolvePseudoToken (token.Token);
817 public void CloseMethod ()
819 SymbolWriter.CloseMethod ();
822 public void SetRealMethodName (string name)
825 builder.SetRealMethodName (name);
828 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
830 if (!SymbolWriter.HasSymbolWriter)
835 Location start_loc = block.StartLocation;
836 if (start_loc.IsNull)
839 ICompileUnit compile_unit = start_loc.CompilationUnit;
840 if (compile_unit == null)
843 return new SourceMethod (parent, method, compile_unit);
847 public class Method : MethodOrOperator, IGenericMethodDefinition
849 Method partialMethodImplementation;
851 public Method (DeclSpace parent, GenericMethod generic,
852 FullNamedExpression return_type, Modifiers mod,
853 MemberName name, ParametersCompiled parameters, Attributes attrs)
854 : base (parent, generic, return_type, mod,
855 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
856 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct | Modifiers.ASYNC :
857 AllowedModifiersClass | Modifiers.ASYNC,
858 name, attrs, parameters)
862 protected Method (DeclSpace parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
863 MemberName name, ParametersCompiled parameters, Attributes attrs)
864 : base (parent, null, return_type, mod, amod, name, attrs, parameters)
870 public override TypeParameter[] CurrentTypeParameters {
872 if (GenericMethod != null)
873 return GenericMethod.CurrentTypeParameters;
879 public TypeParameterSpec[] TypeParameters {
882 return CurrentTypeParameters.Select (l => l.Type).ToArray ();
886 public int TypeParametersCount {
888 return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Length;
894 public override string GetSignatureForError()
896 return base.GetSignatureForError () + parameters.GetSignatureForError ();
899 void Error_DuplicateEntryPoint (Method b)
901 Report.Error (17, b.Location,
902 "Program `{0}' has more than one entry point defined: `{1}'",
903 b.Module.Builder.ScopeName, b.GetSignatureForError ());
908 if (ReturnType.Kind != MemberKind.Void && ReturnType.BuiltinType != BuiltinTypeSpec.Type.Int)
911 if (parameters.IsEmpty)
914 if (parameters.Count > 1)
917 var ac = parameters.Types [0] as ArrayContainer;
918 return ac != null && ac.Rank == 1 && ac.Element.BuiltinType == BuiltinTypeSpec.Type.String &&
919 (parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
922 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
925 TypeParameter[] tp = CurrentTypeParameters;
927 TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
929 return new TypeParameterExpr (t, loc);
933 return base.LookupNamespaceOrType (name, arity, mode, loc);
936 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
938 if (a.Type == pa.Conditional) {
939 if (IsExplicitImpl) {
940 Error_ConditionalAttributeIsNotValid ();
944 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
945 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
949 if (ReturnType.Kind != MemberKind.Void) {
950 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
955 Report.Error (582, Location, "Conditional not valid on interface members");
959 if (MethodData.implementing != null) {
960 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
961 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
962 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
966 for (int i = 0; i < parameters.Count; ++i) {
967 if (parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
968 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
974 if (a.Type == pa.Extension) {
975 a.Error_MisusedExtensionAttribute ();
979 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
982 protected virtual void DefineTypeParameters ()
984 var tparams = CurrentTypeParameters;
986 TypeParameterSpec[] base_tparams = null;
987 TypeParameterSpec[] base_decl_tparams = TypeParameterSpec.EmptyTypes;
988 TypeSpec[] base_targs = TypeSpec.EmptyTypes;
989 if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
990 if (base_method != null) {
991 base_tparams = base_method.GenericDefinition.TypeParameters;
993 if (base_method.DeclaringType.IsGeneric) {
994 base_decl_tparams = base_method.DeclaringType.MemberDefinition.TypeParameters;
996 var base_type_parent = CurrentType;
997 while (base_type_parent.BaseType != base_method.DeclaringType) {
998 base_type_parent = base_type_parent.BaseType;
1001 base_targs = base_type_parent.BaseType.TypeArguments;
1004 if (base_method.IsGeneric) {
1005 ObsoleteAttribute oa;
1006 foreach (var base_tp in base_tparams) {
1007 oa = base_tp.BaseType.GetAttributeObsolete ();
1009 AttributeTester.Report_ObsoleteMessage (oa, base_tp.BaseType.GetSignatureForError (), Location, Report);
1012 if (base_tp.InterfacesDefined != null) {
1013 foreach (var iface in base_tp.InterfacesDefined) {
1014 oa = iface.GetAttributeObsolete ();
1016 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1022 if (base_decl_tparams.Length != 0) {
1023 base_decl_tparams = base_decl_tparams.Concat (base_tparams).ToArray ();
1024 base_targs = base_targs.Concat (tparams.Select<TypeParameter, TypeSpec> (l => l.Type)).ToArray ();
1026 base_decl_tparams = base_tparams;
1027 base_targs = tparams.Select (l => l.Type).ToArray ();
1030 } else if (MethodData.implementing != null) {
1031 base_tparams = MethodData.implementing.GenericDefinition.TypeParameters;
1032 if (MethodData.implementing.DeclaringType.IsGeneric) {
1033 base_decl_tparams = MethodData.implementing.DeclaringType.MemberDefinition.TypeParameters;
1034 foreach (var iface in Parent.CurrentType.Interfaces) {
1035 if (iface == MethodData.implementing.DeclaringType) {
1036 base_targs = iface.TypeArguments;
1044 for (int i = 0; i < tparams.Length; ++i) {
1045 var tp = tparams[i];
1047 if (!tp.ResolveConstraints (this))
1051 // Copy base constraints for override/explicit methods
1053 if (base_tparams != null) {
1054 var base_tparam = base_tparams[i];
1055 var local_tparam = tp.Type;
1056 local_tparam.SpecialConstraint = base_tparam.SpecialConstraint;
1058 var inflator = new TypeParameterInflator (this, CurrentType, base_decl_tparams, base_targs);
1059 base_tparam.InflateConstraints (inflator, local_tparam);
1062 // Check all type argument constraints for possible collision
1063 // introduced by inflating inherited constraints in this context
1065 // Conflict example:
1067 // class A<T> { virtual void Foo<U> () where U : class, T {} }
1068 // class B : A<int> { override void Foo<U> {} }
1070 var local_tparam_targs = local_tparam.TypeArguments;
1071 if (local_tparam_targs != null) {
1072 for (int ii = 0; ii < local_tparam_targs.Length; ++ii) {
1073 var ta = local_tparam_targs [ii];
1074 if (!ta.IsClass && !ta.IsStruct)
1077 if (Constraints.CheckConflictingInheritedConstraint (local_tparam, ta, this, Location)) {
1078 local_tparam.ChangeTypeArgumentToBaseType (ii);
1086 if (MethodData.implementing != null) {
1087 var base_tp = MethodData.implementing.Constraints[i];
1088 if (!tp.Type.HasSameConstraintsImplementation (base_tp)) {
1089 Report.SymbolRelatedToPreviousError (MethodData.implementing);
1090 Report.Error (425, Location,
1091 "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",
1092 tp.GetSignatureForError (), GetSignatureForError (), base_tp.GetSignatureForError (), MethodData.implementing.GetSignatureForError ());
1101 public override bool Define ()
1103 if (!base.Define ())
1106 if (member_type.Kind == MemberKind.Void && parameters.IsEmpty && MemberName.Arity == 0 && MemberName.Name == Destructor.MetadataName) {
1107 Report.Warning (465, 1, Location,
1108 "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
1111 if (partialMethodImplementation != null && IsPartialDefinition)
1112 MethodBuilder = partialMethodImplementation.MethodBuilder;
1114 if (Compiler.Settings.StdLib && ReturnType.IsSpecialRuntimeType) {
1115 Error1599 (Location, ReturnType, Report);
1119 if (CurrentTypeParameters == null) {
1120 if (base_method != null) {
1121 if (parameters.Count == 1 && ParameterTypes[0].BuiltinType == BuiltinTypeSpec.Type.Object && Name == "Equals")
1122 Parent.PartialContainer.Mark_HasEquals ();
1123 else if (parameters.IsEmpty && Name == "GetHashCode")
1124 Parent.PartialContainer.Mark_HasGetHashCode ();
1128 DefineTypeParameters ();
1131 if (block != null) {
1132 if (block.IsIterator) {
1134 // Current method is turned into automatically generated
1135 // wrapper which creates an instance of iterator
1137 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1138 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
1141 if ((ModFlags & Modifiers.ASYNC) != 0) {
1142 if (ReturnType.Kind != MemberKind.Void && ReturnType != Module.PredefinedTypes.Task.TypeSpec && ReturnType != Module.PredefinedTypes.TaskGeneric.TypeSpec) {
1143 Report.Error (1983, type_expr.Location, "The return type of an async method `{0}' must be void, Task, or Task<T>",
1144 GetSignatureForError ());
1147 if (!block.IsAsync) {
1151 AsyncInitializer.Create (block, Parent.PartialContainer, ReturnType);
1155 if ((ModFlags & Modifiers.STATIC) == 0)
1158 if (parameters.HasExtensionMethodType) {
1159 if (Parent.PartialContainer.IsStatic && !Parent.IsGeneric) {
1160 if (!Parent.IsTopLevel)
1161 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
1162 GetSignatureForError ());
1164 PredefinedAttribute pa = Module.PredefinedAttributes.Extension;
1165 if (!pa.IsDefined) {
1166 Report.Error (1110, Location,
1167 "`{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",
1168 GetSignatureForError ());
1171 ModFlags |= Modifiers.METHOD_EXTENSION;
1172 Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
1173 Spec.DeclaringType.SetExtensionMethodContainer ();
1174 Parent.Module.HasExtensionMethod = true;
1176 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
1177 GetSignatureForError ());
1182 // This is used to track the Entry Point,
1184 var settings = Compiler.Settings;
1185 if (settings.NeedsEntryPoint && Name == "Main" && (settings.MainClass == null || settings.MainClass == Parent.TypeBuilder.FullName)) {
1186 if (IsEntryPoint ()) {
1187 if (Parent.DeclaringAssembly.EntryPoint == null) {
1188 if (Parent.IsGeneric || MemberName.IsGeneric) {
1189 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
1190 GetSignatureForError ());
1193 Parent.DeclaringAssembly.EntryPoint = this;
1196 Error_DuplicateEntryPoint (Parent.DeclaringAssembly.EntryPoint);
1197 Error_DuplicateEntryPoint (this);
1200 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
1201 GetSignatureForError ());
1211 public override void Emit ()
1214 if (IsPartialDefinition) {
1216 // Use partial method implementation builder for partial method declaration attributes
1218 if (partialMethodImplementation != null) {
1219 MethodBuilder = partialMethodImplementation.MethodBuilder;
1225 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
1226 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
1227 GetSignatureForError ());
1230 if (CurrentTypeParameters != null) {
1231 for (int i = 0; i < CurrentTypeParameters.Length; ++i) {
1232 var tp = CurrentTypeParameters [i];
1233 tp.CheckGenericConstraints (false);
1240 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
1241 Module.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
1243 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
1244 Location, MethodBuilder);
1249 public override bool EnableOverloadChecks (MemberCore overload)
1251 // TODO: It can be deleted when members will be defined in correct order
1252 if (overload is Operator)
1253 return overload.EnableOverloadChecks (this);
1255 if (overload is Indexer)
1258 return base.EnableOverloadChecks (overload);
1261 public static void Error1599 (Location loc, TypeSpec t, Report Report)
1263 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
1266 protected override bool ResolveMemberType ()
1268 if (GenericMethod != null) {
1269 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
1270 if (!GenericMethod.Define (this))
1274 return base.ResolveMemberType ();
1277 public void SetPartialDefinition (Method methodDefinition)
1279 caching_flags |= Flags.PartialDefinitionExists;
1280 methodDefinition.partialMethodImplementation = this;
1282 // Ensure we are always using method declaration parameters
1283 for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
1284 parameters [i].Name = methodDefinition.parameters [i].Name;
1285 parameters [i].DefaultValue = methodDefinition.parameters [i].DefaultValue;
1288 if (methodDefinition.attributes == null)
1291 if (attributes == null) {
1292 attributes = methodDefinition.attributes;
1294 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
1299 public abstract class ConstructorInitializer : ExpressionStatement
1301 Arguments argument_list;
1302 MethodSpec base_ctor;
1304 public ConstructorInitializer (Arguments argument_list, Location loc)
1306 this.argument_list = argument_list;
1310 public Arguments Arguments {
1312 return argument_list;
1316 public override Expression CreateExpressionTree (ResolveContext ec)
1318 throw new NotSupportedException ("ET");
1321 protected override Expression DoResolve (ResolveContext ec)
1323 eclass = ExprClass.Value;
1326 var caller_builder = (Constructor) ec.MemberContext;
1329 // Spec mandates that constructor initializer will not have `this' access
1331 using (ec.Set (ResolveContext.Options.BaseInitializer)) {
1332 if (argument_list != null) {
1334 argument_list.Resolve (ec, out dynamic);
1337 ec.Report.Error (1975, loc,
1338 "The constructor call cannot be dynamically dispatched within constructor initializer");
1344 type = ec.CurrentType;
1345 if (this is ConstructorBaseInitializer) {
1346 if (ec.CurrentType.BaseType == null)
1349 type = ec.CurrentType.BaseType;
1350 if (ec.CurrentType.IsStruct) {
1351 ec.Report.Error (522, loc,
1352 "`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
1357 // It is legal to have "this" initializers that take no arguments
1358 // in structs, they are just no-ops.
1360 // struct D { public D (int a) : this () {}
1362 if (ec.CurrentType.IsStruct && argument_list == null)
1366 base_ctor = ConstructorLookup (ec, type, ref argument_list, loc);
1369 // TODO MemberCache: Does it work for inflated types ?
1370 if (base_ctor == caller_builder.Spec){
1371 ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
1372 caller_builder.GetSignatureForError ());
1378 public override void Emit (EmitContext ec)
1380 // It can be null for static initializers
1381 if (base_ctor == null)
1386 Invocation.EmitCall (ec, new CompilerGeneratedThis (type, loc), base_ctor, argument_list, loc);
1389 public override void EmitStatement (EmitContext ec)
1395 public class ConstructorBaseInitializer : ConstructorInitializer {
1396 public ConstructorBaseInitializer (Arguments argument_list, Location l) :
1397 base (argument_list, l)
1402 class GeneratedBaseInitializer: ConstructorBaseInitializer {
1403 public GeneratedBaseInitializer (Location loc):
1409 public class ConstructorThisInitializer : ConstructorInitializer {
1410 public ConstructorThisInitializer (Arguments argument_list, Location l) :
1411 base (argument_list, l)
1416 public class Constructor : MethodCore, IMethodData {
1417 public ConstructorBuilder ConstructorBuilder;
1418 public ConstructorInitializer Initializer;
1419 SecurityType declarative_security;
1420 bool has_compliant_args;
1423 // Modifiers allowed for a constructor.
1425 public const Modifiers AllowedModifiers =
1427 Modifiers.PROTECTED |
1428 Modifiers.INTERNAL |
1434 static readonly string[] attribute_targets = new string [] { "method" };
1436 public static readonly string ConstructorName = ".ctor";
1437 public static readonly string TypeConstructorName = ".cctor";
1440 // The spec claims that static is not permitted, but
1441 // my very own code has static constructors.
1443 public Constructor (DeclSpace parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args,
1444 ConstructorInitializer init, Location loc)
1445 : base (parent, null, null, mod, AllowedModifiers,
1446 new MemberName (name, loc), attrs, args)
1451 public bool HasCompliantArgs {
1452 get { return has_compliant_args; }
1455 public override AttributeTargets AttributeTargets {
1457 return AttributeTargets.Constructor;
1461 bool IMethodData.IsAccessor {
1468 // Returns true if this is a default constructor
1470 public bool IsDefault ()
1472 if ((ModFlags & Modifiers.STATIC) != 0)
1473 return parameters.IsEmpty;
1475 return parameters.IsEmpty &&
1476 (Initializer is ConstructorBaseInitializer) &&
1477 (Initializer.Arguments == null);
1480 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1482 if (a.IsValidSecurityAttribute ()) {
1483 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
1487 if (a.Type == pa.MethodImpl) {
1488 is_external_implementation = a.IsInternalCall ();
1491 ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1494 protected override bool CheckBase ()
1496 if ((ModFlags & Modifiers.STATIC) != 0) {
1497 if (!parameters.IsEmpty) {
1498 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
1499 GetSignatureForError ());
1503 // the rest can be ignored
1507 // Check whether arguments were correct.
1508 if (!DefineParameters (parameters))
1511 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1512 Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1514 if (Parent.PartialContainer.Kind == MemberKind.Struct && parameters.IsEmpty) {
1515 Report.Error (568, Location,
1516 "Structs cannot contain explicit parameterless constructors");
1520 CheckProtectedModifier ();
1526 // Creates the ConstructorBuilder
1528 public override bool Define ()
1530 if (ConstructorBuilder != null)
1533 var ca = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
1535 if ((ModFlags & Modifiers.STATIC) != 0) {
1536 ca |= MethodAttributes.Static | MethodAttributes.Private;
1538 ca |= ModifiersExtensions.MethodAttr (ModFlags);
1541 if (!CheckAbstractAndExtern (block != null))
1544 // Check if arguments were correct.
1548 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
1549 ca, CallingConventions,
1550 parameters.GetMetaInfo ());
1552 spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, Compiler.BuiltinTypes.Void, ConstructorBuilder, parameters, ModFlags);
1554 Parent.MemberCache.AddMember (spec);
1556 // It's here only to report an error
1557 if (block != null && block.IsIterator) {
1558 member_type = Compiler.BuiltinTypes.Void;
1559 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1568 public override void Emit ()
1570 if (Parent.PartialContainer.IsComImport) {
1571 if (!IsDefault ()) {
1572 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
1573 Parent.GetSignatureForError ());
1576 // Set as internal implementation and reset block data
1577 // to ensure no IL is generated
1578 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
1582 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
1583 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (ConstructorBuilder);
1585 if (OptAttributes != null)
1586 OptAttributes.Emit ();
1589 parameters.ApplyAttributes (this, ConstructorBuilder);
1592 // If we use a "this (...)" constructor initializer, then
1593 // do not emit field initializers, they are initialized in the other constructor
1595 bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
1596 !(Initializer is ConstructorThisInitializer);
1598 BlockContext bc = new BlockContext (this, block, Compiler.BuiltinTypes.Void);
1599 bc.Set (ResolveContext.Options.ConstructorScope);
1601 if (emit_field_initializers)
1602 Parent.PartialContainer.ResolveFieldInitializers (bc);
1604 if (block != null) {
1605 // If this is a non-static `struct' constructor and doesn't have any
1606 // initializer, it must initialize all of the struct's fields.
1607 if ((Parent.PartialContainer.Kind == MemberKind.Struct) &&
1608 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
1609 block.AddThisVariable (bc, Parent, Location);
1611 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
1612 if (Parent.PartialContainer.Kind == MemberKind.Class && Initializer == null)
1613 Initializer = new GeneratedBaseInitializer (Location);
1615 if (Initializer != null) {
1616 block.AddScopeStatement (new StatementExpression (Initializer));
1621 SourceMethod source = SourceMethod.Create (Parent, ConstructorBuilder, block);
1623 if (block != null) {
1624 if (block.Resolve (null, bc, this)) {
1625 EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType);
1626 ec.With (EmitContext.Options.ConstructorScope, true);
1628 if (!ec.HasReturnLabel && bc.HasReturnLabel) {
1629 ec.ReturnLabel = bc.ReturnLabel;
1630 ec.HasReturnLabel = true;
1638 source.CloseMethod ();
1640 if (declarative_security != null) {
1641 foreach (var de in declarative_security) {
1643 ConstructorBuilder.__AddDeclarativeSecurity (de);
1645 ConstructorBuilder.AddDeclarativeSecurity (de.Key, de.Value);
1653 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
1655 // Is never override
1656 bestCandidate = null;
1660 public override string GetSignatureForDocumentation ()
1662 return Parent.GetSignatureForDocumentation () + ".#ctor" + parameters.GetSignatureForDocumentation ();
1665 public override string GetSignatureForError()
1667 return base.GetSignatureForError () + parameters.GetSignatureForError ();
1670 public override string[] ValidAttributeTargets {
1672 return attribute_targets;
1676 protected override bool VerifyClsCompliance ()
1678 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
1682 if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
1683 foreach (TypeSpec param in parameters.Types) {
1684 if (param.IsArray) {
1690 has_compliant_args = true;
1694 #region IMethodData Members
1696 public MemberName MethodName {
1702 public TypeSpec ReturnType {
1708 public EmitContext CreateEmitContext (ILGenerator ig)
1710 throw new NotImplementedException ();
1713 public bool IsExcluded()
1718 GenericMethod IMethodData.GenericMethod {
1724 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
1731 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
1733 public interface IMethodData : IMemberContext
1735 CallingConventions CallingConventions { get; }
1736 Location Location { get; }
1737 MemberName MethodName { get; }
1738 TypeSpec ReturnType { get; }
1739 GenericMethod GenericMethod { get; }
1740 ParametersCompiled ParameterInfo { get; }
1741 MethodSpec Spec { get; }
1742 bool IsAccessor { get; }
1744 Attributes OptAttributes { get; }
1745 ToplevelBlock Block { get; set; }
1747 EmitContext CreateEmitContext (ILGenerator ig);
1748 void EmitExtraSymbolInfo (SourceMethod source);
1752 // Encapsulates most of the Method's state
1754 public class MethodData
1757 static FieldInfo methodbuilder_attrs_field;
1760 public readonly IMethodData method;
1762 public readonly GenericMethod GenericMethod;
1765 // Are we implementing an interface ?
1767 public MethodSpec implementing;
1772 protected InterfaceMemberBase member;
1773 protected Modifiers modifiers;
1774 protected MethodAttributes flags;
1775 protected TypeSpec declaring_type;
1776 protected MethodSpec parent_method;
1778 MethodBuilder builder;
1779 public MethodBuilder MethodBuilder {
1785 public TypeSpec DeclaringType {
1787 return declaring_type;
1791 public MethodData (InterfaceMemberBase member,
1792 Modifiers modifiers, MethodAttributes flags, IMethodData method)
1794 this.member = member;
1795 this.modifiers = modifiers;
1798 this.method = method;
1801 public MethodData (InterfaceMemberBase member,
1802 Modifiers modifiers, MethodAttributes flags,
1803 IMethodData method, MethodBuilder builder,
1804 GenericMethod generic, MethodSpec parent_method)
1805 : this (member, modifiers, flags, method)
1807 this.builder = builder;
1808 this.GenericMethod = generic;
1809 this.parent_method = parent_method;
1812 public bool Define (DeclSpace parent, string method_full_name, Report Report)
1814 TypeContainer container = parent.PartialContainer;
1816 PendingImplementation pending = container.PendingImplementations;
1817 MethodSpec ambig_iface_method;
1818 if (pending != null) {
1819 implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this, out ambig_iface_method);
1821 if (member.InterfaceType != null) {
1822 if (implementing == null) {
1823 if (member is PropertyBase) {
1824 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
1825 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
1826 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
1829 Report.Error (539, method.Location,
1830 "`{0}.{1}' in explicit interface declaration is not a member of interface",
1831 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
1835 if (implementing.IsAccessor && !method.IsAccessor) {
1836 Report.SymbolRelatedToPreviousError (implementing);
1837 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
1838 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1842 if (implementing != null) {
1843 if (!method.IsAccessor) {
1844 if (implementing.IsAccessor) {
1845 Report.SymbolRelatedToPreviousError (implementing);
1846 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}'",
1847 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1849 } else if (implementing.DeclaringType.IsInterface) {
1850 if (!implementing.IsAccessor) {
1851 Report.SymbolRelatedToPreviousError (implementing);
1852 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
1853 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
1855 PropertyBase.PropertyMethod pm = method as PropertyBase.PropertyMethod;
1856 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
1857 Report.SymbolRelatedToPreviousError (implementing);
1858 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
1859 method.GetSignatureForError (), implementing.GetSignatureForError ());
1866 ambig_iface_method = null;
1870 // For implicit implementations, make sure we are public, for
1871 // explicit implementations, make sure we are private.
1873 if (implementing != null){
1875 // Setting null inside this block will trigger a more
1876 // verbose error reporting for missing interface implementations
1878 // The "candidate" function has been flagged already
1879 // but it wont get cleared
1881 if (member.IsExplicitImpl){
1882 if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
1883 Report.SymbolRelatedToPreviousError (implementing);
1884 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
1885 method.GetSignatureForError ());
1888 if (ambig_iface_method != null) {
1889 Report.SymbolRelatedToPreviousError (ambig_iface_method);
1890 Report.SymbolRelatedToPreviousError (implementing);
1891 Report.Warning (473, 2, method.Location,
1892 "Explicit interface implementation `{0}' matches more than one interface member. Consider using a non-explicit implementation instead",
1893 method.GetSignatureForError ());
1897 if (implementing.DeclaringType.IsInterface) {
1899 // If this is an interface method implementation,
1900 // check for public accessibility
1902 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
1904 implementing = null;
1906 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
1907 // We may never be private.
1908 implementing = null;
1910 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
1912 // We may be protected if we're overriding something.
1914 implementing = null;
1919 // Static is not allowed
1921 if ((modifiers & Modifiers.STATIC) != 0){
1922 implementing = null;
1927 // If implementing is still valid, set flags
1929 if (implementing != null){
1931 // When implementing interface methods, set NewSlot
1932 // unless, we are overwriting a method.
1934 if (implementing.DeclaringType.IsInterface){
1935 if ((modifiers & Modifiers.OVERRIDE) == 0)
1936 flags |= MethodAttributes.NewSlot;
1939 flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;
1941 // Set Final unless we're virtual, abstract or already overriding a method.
1942 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
1943 flags |= MethodAttributes.Final;
1946 // clear the pending implementation flag (requires explicit methods to be defined first)
1948 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName,
1949 member.InterfaceType, this, member.IsExplicitImpl, out ambig_iface_method);
1952 // Update indexer accessor name to match implementing abstract accessor
1954 if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
1955 method_full_name = implementing.MemberDefinition.Name;
1958 DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
1960 if (builder == null)
1963 // if (container.CurrentType != null)
1964 // declaring_type = container.CurrentType;
1966 declaring_type = container.Definition;
1968 if (implementing != null && member.IsExplicitImpl) {
1969 container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
1977 /// Create the MethodBuilder for the method
1979 void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
1981 var return_type = method.ReturnType.GetMetaInfo ();
1982 var p_types = param.GetMetaInfo ();
1984 if (builder == null) {
1985 builder = container.TypeBuilder.DefineMethod (
1986 method_name, flags, method.CallingConventions,
1987 return_type, p_types);
1992 // Generic method has been already defined to resolve method parameters
1993 // correctly when they use type parameters
1995 builder.SetParameters (p_types);
1996 builder.SetReturnType (return_type);
1997 if (builder.Attributes != flags) {
1999 builder.__SetAttributes (flags);
2002 if (methodbuilder_attrs_field == null)
2003 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
2004 methodbuilder_attrs_field.SetValue (builder, flags);
2006 container.Compiler.Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
2015 public void Emit (DeclSpace parent)
2017 if (GenericMethod != null)
2018 GenericMethod.EmitAttributes ();
2020 var mc = (IMemberContext) method;
2022 method.ParameterInfo.ApplyAttributes (mc, MethodBuilder);
2024 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
2026 ToplevelBlock block = method.Block;
2027 if (block != null) {
2028 BlockContext bc = new BlockContext (mc, block, method.ReturnType);
2029 if (block.Resolve (null, bc, method)) {
2030 EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator ());
2031 if (!ec.HasReturnLabel && bc.HasReturnLabel) {
2032 ec.ReturnLabel = bc.ReturnLabel;
2033 ec.HasReturnLabel = true;
2040 if (source != null) {
2041 method.EmitExtraSymbolInfo (source);
2042 source.CloseMethod ();
2047 public class Destructor : MethodOrOperator
2049 const Modifiers AllowedModifiers =
2053 static readonly string[] attribute_targets = new string [] { "method" };
2055 public static readonly string MetadataName = "Finalize";
2057 public Destructor (DeclSpace parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
2058 : base (parent, null, null, mod, AllowedModifiers,
2059 new MemberName (MetadataName, l), attrs, parameters)
2061 ModFlags &= ~Modifiers.PRIVATE;
2062 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
2065 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2067 if (a.Type == pa.Conditional) {
2068 Error_ConditionalAttributeIsNotValid ();
2072 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2075 protected override bool CheckBase ()
2077 // Don't check base, destructors have special syntax
2081 public override void Emit()
2083 var base_type = Parent.PartialContainer.BaseType;
2084 if (base_type != null && Block != null) {
2085 var base_dtor = MemberCache.FindMember (base_type,
2086 new MemberFilter (MetadataName, 0, MemberKind.Destructor, null, null), BindingRestriction.InstanceOnly) as MethodSpec;
2088 if (base_dtor == null)
2089 throw new NotImplementedException ();
2091 MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
2092 method_expr.InstanceExpression = new BaseThis (base_type, Location);
2094 var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation);
2095 var finaly_block = new ExplicitBlock (block, Location, Location);
2098 // 0-size arguments to avoid CS0250 error
2099 // TODO: Should use AddScopeStatement or something else which emits correct
2102 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0))));
2104 var tf = new TryFinally (try_block, finaly_block, Location);
2105 block.WrapIntoDestructor (tf, try_block);
2111 public override string GetSignatureForError ()
2113 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
2116 protected override bool ResolveMemberType ()
2118 member_type = Compiler.BuiltinTypes.Void;
2122 public override string[] ValidAttributeTargets {
2124 return attribute_targets;
2129 // Ooouh Martin, templates are missing here.
2130 // When it will be possible move here a lot of child code and template method type.
2131 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
2132 protected MethodData method_data;
2133 protected ToplevelBlock block;
2134 protected SecurityType declarative_security;
2136 protected readonly string prefix;
2138 ReturnParameter return_attributes;
2140 public AbstractPropertyEventMethod (InterfaceMemberBase member, string prefix, Attributes attrs, Location loc)
2141 : base (member.Parent, SetupName (prefix, member, loc), attrs)
2143 this.prefix = prefix;
2146 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
2148 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
2151 public void UpdateName (InterfaceMemberBase member)
2153 SetMemberName (SetupName (prefix, member, Location));
2156 #region IMethodData Members
2158 public ToplevelBlock Block {
2168 public CallingConventions CallingConventions {
2170 return CallingConventions.Standard;
2174 public EmitContext CreateEmitContext (ILGenerator ig)
2176 return new EmitContext (this, ig, ReturnType);
2179 public bool IsAccessor {
2185 public bool IsExcluded ()
2190 GenericMethod IMethodData.GenericMethod {
2196 public MemberName MethodName {
2202 public TypeSpec[] ParameterTypes {
2204 return ParameterInfo.Types;
2208 public abstract ParametersCompiled ParameterInfo { get ; }
2209 public abstract TypeSpec ReturnType { get; }
2213 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2215 if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
2216 Report.Error (1667, a.Location,
2217 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
2218 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
2222 if (a.IsValidSecurityAttribute ()) {
2223 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
2227 if (a.Target == AttributeTargets.Method) {
2228 method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
2232 if (a.Target == AttributeTargets.ReturnValue) {
2233 if (return_attributes == null)
2234 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2236 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
2240 ApplyToExtraTarget (a, ctor, cdata, pa);
2243 protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2245 throw new NotSupportedException ("You forgot to define special attribute target handling");
2248 // It is not supported for the accessors
2249 public sealed override bool Define()
2251 throw new NotSupportedException ();
2254 public virtual void Emit (DeclSpace parent)
2256 method_data.Emit (parent);
2258 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
2259 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
2260 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
2261 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
2263 if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2264 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2265 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
2266 } else if (ReturnType.HasDynamicElement) {
2267 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2268 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
2271 if (OptAttributes != null)
2272 OptAttributes.Emit ();
2274 if (declarative_security != null) {
2275 foreach (var de in declarative_security) {
2277 method_data.MethodBuilder.__AddDeclarativeSecurity (de);
2279 method_data.MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2287 public override bool EnableOverloadChecks (MemberCore overload)
2289 if (overload is MethodCore) {
2290 caching_flags |= Flags.MethodOverloadsExist;
2294 // This can only happen with indexers and it will
2295 // be catched as indexer difference
2296 if (overload is AbstractPropertyEventMethod)
2302 public override string GetSignatureForDocumentation ()
2304 // should not be called
2305 throw new NotSupportedException ();
2308 public override bool IsClsComplianceRequired()
2313 public MethodSpec Spec { get; protected set; }
2316 // Represents header string for documentation comment.
2318 public override string DocCommentHeader {
2319 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
2322 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
2326 public class Operator : MethodOrOperator {
2328 const Modifiers AllowedModifiers =
2334 public enum OpType : byte {
2344 // Unary and Binary operators
2367 // Implicit and Explicit
2371 // Just because of enum
2375 public readonly OpType OperatorType;
2377 static readonly string [] [] names;
2381 names = new string[(int)OpType.TOP][];
2382 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
2383 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
2384 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
2385 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
2386 names [(int) OpType.True] = new string [] { "true", "op_True" };
2387 names [(int) OpType.False] = new string [] { "false", "op_False" };
2388 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
2389 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
2390 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
2391 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
2392 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
2393 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
2394 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
2395 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
2396 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
2397 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
2398 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
2399 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
2400 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
2401 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
2402 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
2403 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
2404 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
2405 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
2406 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
2407 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
2410 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
2411 Modifiers mod_flags, ParametersCompiled parameters,
2412 ToplevelBlock block, Attributes attrs, Location loc)
2413 : base (parent, null, ret_type, mod_flags, AllowedModifiers,
2414 new MemberName (GetMetadataName (type), loc), attrs, parameters)
2416 OperatorType = type;
2420 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2422 if (a.Type == pa.Conditional) {
2423 Error_ConditionalAttributeIsNotValid ();
2427 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2430 public override bool Define ()
2432 const Modifiers RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
2433 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
2434 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
2437 if (!base.Define ())
2440 if (block != null && block.IsIterator) {
2442 // Current method is turned into automatically generated
2443 // wrapper which creates an instance of iterator
2445 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
2446 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
2449 // imlicit and explicit operator of same types are not allowed
2450 if (OperatorType == OpType.Explicit)
2451 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
2452 else if (OperatorType == OpType.Implicit)
2453 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
2455 TypeSpec declaring_type = Parent.CurrentType;
2456 TypeSpec return_type = MemberType;
2457 TypeSpec first_arg_type = ParameterTypes [0];
2459 TypeSpec first_arg_type_unwrap = first_arg_type;
2460 if (first_arg_type.IsNullableType)
2461 first_arg_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (first_arg_type);
2463 TypeSpec return_type_unwrap = return_type;
2464 if (return_type.IsNullableType)
2465 return_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (return_type);
2468 // Rules for conversion operators
2470 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2471 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type) {
2472 Report.Error (555, Location,
2473 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
2478 if (declaring_type == return_type || declaring_type == return_type_unwrap) {
2479 conv_type = first_arg_type;
2480 } else if (declaring_type == first_arg_type || declaring_type == first_arg_type_unwrap) {
2481 conv_type = return_type;
2483 Report.Error (556, Location,
2484 "User-defined conversion must convert to or from the enclosing type");
2488 if (conv_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2489 Report.Error (1964, Location,
2490 "User-defined conversion `{0}' cannot convert to or from the dynamic type",
2491 GetSignatureForError ());
2496 if (conv_type.IsInterface) {
2497 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
2498 GetSignatureForError ());
2502 if (conv_type.IsClass) {
2503 if (TypeSpec.IsBaseClass (declaring_type, conv_type, true)) {
2504 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
2505 GetSignatureForError ());
2509 if (TypeSpec.IsBaseClass (conv_type, declaring_type, false)) {
2510 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
2511 GetSignatureForError ());
2515 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
2516 if (first_arg_type != declaring_type || parameters.Types[1].BuiltinType != BuiltinTypeSpec.Type.Int) {
2517 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");
2520 } else if (parameters.Count == 1) {
2521 // Checks for Unary operators
2523 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
2524 if (return_type != declaring_type && !TypeSpec.IsBaseClass (return_type, declaring_type, false)) {
2525 Report.Error (448, Location,
2526 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
2529 if (first_arg_type != declaring_type) {
2531 559, Location, "The parameter type for ++ or -- operator must be the containing type");
2536 if (first_arg_type_unwrap != declaring_type) {
2537 Report.Error (562, Location,
2538 "The parameter type of a unary operator must be the containing type");
2542 if (OperatorType == OpType.True || OperatorType == OpType.False) {
2543 if (return_type.BuiltinType != BuiltinTypeSpec.Type.Bool) {
2546 "The return type of operator True or False " +
2552 } else if (first_arg_type_unwrap != declaring_type) {
2553 // Checks for Binary operators
2555 var second_arg_type = ParameterTypes[1];
2556 if (second_arg_type.IsNullableType)
2557 second_arg_type = Nullable.NullableInfo.GetUnderlyingType (second_arg_type);
2559 if (second_arg_type != declaring_type) {
2560 Report.Error (563, Location,
2561 "One of the parameters of a binary operator must be the containing type");
2569 protected override bool ResolveMemberType ()
2571 if (!base.ResolveMemberType ())
2574 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2578 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
2580 // Operator cannot be override
2581 bestCandidate = null;
2585 public static string GetName (OpType ot)
2587 return names [(int) ot] [0];
2590 public static string GetName (string metadata_name)
2592 for (int i = 0; i < names.Length; ++i) {
2593 if (names [i] [1] == metadata_name)
2594 return names [i] [0];
2599 public static string GetMetadataName (OpType ot)
2601 return names [(int) ot] [1];
2604 public static string GetMetadataName (string name)
2606 for (int i = 0; i < names.Length; ++i) {
2607 if (names [i] [0] == name)
2608 return names [i] [1];
2613 public static OpType? GetType (string metadata_name)
2615 for (int i = 0; i < names.Length; ++i) {
2616 if (names[i][1] == metadata_name)
2623 public OpType GetMatchingOperator ()
2625 switch (OperatorType) {
2626 case OpType.Equality:
2627 return OpType.Inequality;
2628 case OpType.Inequality:
2629 return OpType.Equality;
2631 return OpType.False;
2634 case OpType.GreaterThan:
2635 return OpType.LessThan;
2636 case OpType.LessThan:
2637 return OpType.GreaterThan;
2638 case OpType.GreaterThanOrEqual:
2639 return OpType.LessThanOrEqual;
2640 case OpType.LessThanOrEqual:
2641 return OpType.GreaterThanOrEqual;
2647 public override string GetSignatureForDocumentation ()
2649 string s = base.GetSignatureForDocumentation ();
2650 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2651 s = s + "~" + ReturnType.GetSignatureForDocumentation ();
2657 public override string GetSignatureForError ()
2659 StringBuilder sb = new StringBuilder ();
2660 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2661 sb.AppendFormat ("{0}.{1} operator {2}",
2662 Parent.GetSignatureForError (), GetName (OperatorType),
2663 member_type == null ? type_expr.GetSignatureForError () : member_type.GetSignatureForError ());
2666 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
2669 sb.Append (parameters.GetSignatureForError ());
2670 return sb.ToString ();