2 // method.cs: Method based declarations
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin Inc.
16 using System.Collections.Generic;
17 using System.Security;
18 using System.Security.Permissions;
21 using Mono.CompilerServices.SymbolWriter;
22 using System.Runtime.CompilerServices;
25 using XmlElement = System.Object;
31 using MetaType = IKVM.Reflection.Type;
32 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
33 using IKVM.Reflection;
34 using IKVM.Reflection.Emit;
36 using MetaType = System.Type;
37 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
38 using System.Reflection;
39 using System.Reflection.Emit;
42 namespace Mono.CSharp {
44 public abstract class MethodCore : InterfaceMemberBase, IParametersMember
46 protected ParametersCompiled parameters;
47 protected ToplevelBlock block;
48 protected MethodSpec spec;
50 protected MethodCore (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
51 MemberName name, Attributes attrs, ParametersCompiled parameters)
52 : base (parent, 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 override void PrepareEmit ()
171 parameters.ResolveDefaultValues (this);
174 public MethodSpec Spec {
178 protected override bool VerifyClsCompliance ()
180 if (!base.VerifyClsCompliance ())
183 if (parameters.HasArglist) {
184 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
187 if (member_type != null && !member_type.IsCLSCompliant ()) {
188 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
189 GetSignatureForError ());
192 parameters.VerifyClsCompliance (this);
197 public interface IGenericMethodDefinition : IMethodDefinition
199 TypeParameterSpec[] TypeParameters { get; }
200 int TypeParametersCount { get; }
202 // MethodInfo MakeGenericMethod (TypeSpec[] targs);
205 public sealed class MethodSpec : MemberSpec, IParametersMember
207 MethodBase inflatedMetaInfo;
208 AParametersCollection parameters;
212 TypeParameterSpec[] constraints;
214 public static readonly MethodSpec Excluded = new MethodSpec (MemberKind.Method, InternalType.FakeInternalType, null, null, ParametersCompiled.EmptyReadOnlyParameters, 0);
216 public MethodSpec (MemberKind kind, TypeSpec declaringType, IMethodDefinition details, TypeSpec returnType,
217 AParametersCollection parameters, Modifiers modifiers)
218 : base (kind, declaringType, details, modifiers)
220 this.parameters = parameters;
221 this.returnType = returnType;
226 public override int Arity {
228 return IsGeneric ? GenericDefinition.TypeParametersCount : 0;
232 public TypeParameterSpec[] Constraints {
234 if (constraints == null && IsGeneric)
235 constraints = GenericDefinition.TypeParameters;
241 public bool IsConstructor {
243 return Kind == MemberKind.Constructor;
247 public new IMethodDefinition MemberDefinition {
249 return (IMethodDefinition) definition;
253 public IGenericMethodDefinition GenericDefinition {
255 return (IGenericMethodDefinition) definition;
259 public bool IsAsync {
261 return (Modifiers & Modifiers.ASYNC) != 0;
265 public bool IsExtensionMethod {
267 return IsStatic && parameters.HasExtensionMethodType;
271 public bool IsSealed {
273 return (Modifiers & Modifiers.SEALED) != 0;
277 // When is virtual or abstract
278 public bool IsVirtual {
280 return (Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) != 0;
284 public bool IsReservedMethod {
286 return Kind == MemberKind.Operator || IsAccessor;
290 TypeSpec IInterfaceMemberSpec.MemberType {
296 public AParametersCollection Parameters {
302 public TypeSpec ReturnType {
308 public TypeSpec[] TypeArguments {
316 public MethodSpec GetGenericMethodDefinition ()
318 if (!IsGeneric && !DeclaringType.IsGeneric)
321 return MemberCache.GetMember (declaringType, this);
324 public MethodBase GetMetaInfo ()
327 // inflatedMetaInfo is extra field needed for cases where we
328 // inflate method but another nested type can later inflate
329 // again (the cache would be build with inflated metaInfo) and
330 // TypeBuilder can work with method definitions only
332 if (inflatedMetaInfo == null) {
333 if ((state & StateFlags.PendingMetaInflate) != 0) {
334 var dt_meta = DeclaringType.GetMetaInfo ();
336 if (DeclaringType.IsTypeBuilder) {
338 inflatedMetaInfo = TypeBuilder.GetConstructor (dt_meta, (ConstructorInfo) MemberDefinition.Metadata);
340 inflatedMetaInfo = TypeBuilder.GetMethod (dt_meta, (MethodInfo) MemberDefinition.Metadata);
343 // it should not be reached
344 throw new NotImplementedException ();
346 inflatedMetaInfo = MethodInfo.GetMethodFromHandle (MemberDefinition.Metadata.MethodHandle, dt_meta.TypeHandle);
350 state &= ~StateFlags.PendingMetaInflate;
352 inflatedMetaInfo = MemberDefinition.Metadata;
356 if ((state & StateFlags.PendingMakeMethod) != 0) {
357 var sre_targs = new MetaType[targs.Length];
358 for (int i = 0; i < sre_targs.Length; ++i)
359 sre_targs[i] = targs[i].GetMetaInfo ();
361 inflatedMetaInfo = ((MethodInfo) inflatedMetaInfo).MakeGenericMethod (sre_targs);
362 state &= ~StateFlags.PendingMakeMethod;
365 return inflatedMetaInfo;
368 public override string GetSignatureForDocumentation ()
372 case MemberKind.Constructor:
375 case MemberKind.Method:
377 name = Name + "``" + Arity.ToString ();
387 name = DeclaringType.GetSignatureForDocumentation () + "." + name + parameters.GetSignatureForDocumentation ();
388 if (Kind == MemberKind.Operator) {
389 var op = Operator.GetType (Name).Value;
390 if (op == Operator.OpType.Explicit || op == Operator.OpType.Implicit) {
391 name += "~" + ReturnType.GetSignatureForDocumentation ();
398 public override string GetSignatureForError ()
402 name = DeclaringType.GetSignatureForError () + "." + DeclaringType.Name;
403 } else if (Kind == MemberKind.Operator) {
404 var op = Operator.GetType (Name).Value;
405 if (op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) {
406 name = DeclaringType.GetSignatureForError () + "." + Operator.GetName (op) + " operator " + returnType.GetSignatureForError ();
408 name = DeclaringType.GetSignatureForError () + ".operator " + Operator.GetName (op);
410 } else if (IsAccessor) {
411 int split = Name.IndexOf ('_');
412 name = Name.Substring (split + 1);
413 var postfix = Name.Substring (0, split);
415 var pc = parameters.Count;
416 if (pc > 0 && postfix == "get") {
417 name = "this" + parameters.GetSignatureForError ("[", "]", pc);
418 } else if (pc > 1 && postfix == "set") {
419 name = "this" + parameters.GetSignatureForError ("[", "]", pc - 1);
423 return DeclaringType.GetSignatureForError () + "." + name + "." + postfix;
425 name = base.GetSignatureForError ();
427 name += "<" + TypeManager.CSharpName (targs) + ">";
429 name += "<" + TypeManager.CSharpName (GenericDefinition.TypeParameters) + ">";
432 return name + parameters.GetSignatureForError ();
435 public override MemberSpec InflateMember (TypeParameterInflator inflator)
437 var ms = (MethodSpec) base.InflateMember (inflator);
438 ms.inflatedMetaInfo = null;
439 ms.returnType = inflator.Inflate (returnType);
440 ms.parameters = parameters.Inflate (inflator);
442 ms.constraints = TypeParameterSpec.InflateConstraints (inflator, Constraints);
448 int counter = 100000;
451 public MethodSpec MakeGenericMethod (IMemberContext context, params TypeSpec[] targs)
454 throw new ArgumentNullException ();
456 // if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
459 //if (generic_intances == null)
460 // generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
462 var inflator = new TypeParameterInflator (context, DeclaringType, GenericDefinition.TypeParameters, targs);
464 var inflated = (MethodSpec) MemberwiseClone ();
465 inflated.declaringType = inflator.TypeInstance;
466 inflated.returnType = inflator.Inflate (returnType);
467 inflated.parameters = parameters.Inflate (inflator);
468 inflated.targs = targs;
469 inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
470 inflated.state |= StateFlags.PendingMakeMethod;
473 inflated.ID += counter;
476 // if (inflated.parent == null)
477 // inflated.parent = parent;
479 //generic_intances.Add (targs, inflated);
483 public MethodSpec Mutate (TypeParameterMutator mutator)
485 var targs = TypeArguments;
487 targs = mutator.Mutate (targs);
489 var decl = DeclaringType;
490 if (DeclaringType.IsGenericOrParentIsGeneric) {
491 decl = mutator.Mutate (decl);
494 if (targs == TypeArguments && decl == DeclaringType)
497 var ms = (MethodSpec) MemberwiseClone ();
498 if (decl != DeclaringType) {
499 ms.inflatedMetaInfo = null;
500 ms.declaringType = decl;
501 ms.state |= StateFlags.PendingMetaInflate;
506 ms.state |= StateFlags.PendingMakeMethod;
512 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
514 var missing = returnType.ResolveMissingDependencies (this);
515 foreach (var pt in parameters.Types) {
516 var m = pt.GetMissingDependencies (this);
521 missing = new List<MissingTypeSpecReference> ();
523 missing.AddRange (m);
527 foreach (var tp in GenericDefinition.TypeParameters) {
528 var m = tp.GetMissingDependencies (this);
534 missing = new List<MissingTypeSpecReference> ();
536 missing.AddRange (m);
544 public abstract class MethodOrOperator : MethodCore, IMethodData, IMethodDefinition
546 ReturnParameter return_attributes;
547 SecurityType declarative_security;
548 protected MethodData MethodData;
550 static readonly string[] attribute_targets = new string [] { "method", "return" };
552 protected MethodOrOperator (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name,
553 Attributes attrs, ParametersCompiled parameters)
554 : base (parent, type, mod, allowed_mod, name, attrs, parameters)
558 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
560 if (a.Target == AttributeTargets.ReturnValue) {
561 CreateReturnBuilder ().ApplyAttributeBuilder (a, ctor, cdata, pa);
565 if (a.Type == pa.MethodImpl) {
566 if ((ModFlags & Modifiers.ASYNC) != 0 && (a.GetMethodImplOptions () & MethodImplOptions.Synchronized) != 0) {
567 Report.Error (4015, a.Location, "`{0}': Async methods cannot use `MethodImplOptions.Synchronized'",
568 GetSignatureForError ());
571 is_external_implementation = a.IsInternalCall ();
572 } else if (a.Type == pa.DllImport) {
573 const Modifiers extern_static = Modifiers.EXTERN | Modifiers.STATIC;
574 if ((ModFlags & extern_static) != extern_static) {
575 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
578 if (MemberName.IsGeneric || Parent.IsGenericOrParentIsGeneric) {
579 Report.Error (7042, a.Location,
580 "The DllImport attribute cannot be applied to a method that is generic or contained in a generic type");
583 is_external_implementation = true;
586 if (a.IsValidSecurityAttribute ()) {
587 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
591 if (MethodBuilder != null)
592 MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
595 public override AttributeTargets AttributeTargets {
597 return AttributeTargets.Method;
601 MethodBase IMethodDefinition.Metadata {
603 return MethodData.MethodBuilder;
607 // TODO: Remove and use MethodData abstraction
608 public MethodBuilder MethodBuilder {
610 return MethodData.MethodBuilder;
614 protected override bool CheckForDuplications ()
616 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
619 public virtual EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
621 return new EmitContext (this, ig, MemberType, sourceMethod);
624 ReturnParameter CreateReturnBuilder ()
626 return return_attributes ?? (return_attributes = new ReturnParameter (this, MethodBuilder, Location));
629 public override bool Define ()
638 if (this is Operator)
639 kind = MemberKind.Operator;
640 else if (this is Destructor)
641 kind = MemberKind.Destructor;
643 kind = MemberKind.Method;
645 string explicit_name;
647 if (IsPartialDefinition) {
648 caching_flags &= ~Flags.Excluded_Undetected;
649 caching_flags |= Flags.Excluded;
651 // Add to member cache only when a partial method implementation has not been found yet
652 if ((caching_flags & Flags.PartialDefinitionExists) != 0)
658 explicit_name = null;
660 MethodData = new MethodData (this, ModFlags, flags, this);
662 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
665 explicit_name = MethodData.MetadataName;
668 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, parameters, ModFlags);
669 if (MemberName.Arity > 0)
670 spec.IsGeneric = true;
672 Parent.MemberCache.AddMember (this, explicit_name, spec);
677 protected override void DoMemberTypeIndependentChecks ()
679 base.DoMemberTypeIndependentChecks ();
681 CheckAbstractAndExtern (block != null);
683 if ((ModFlags & Modifiers.PARTIAL) != 0) {
684 for (int i = 0; i < parameters.Count; ++i) {
685 IParameterData p = parameters.FixedParameters [i];
686 if ((p.ModFlags & Parameter.Modifier.OUT) != 0) {
687 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
688 GetSignatureForError ());
691 if (p.HasDefaultValue && IsPartialImplementation)
692 ((Parameter) p).Warning_UselessOptionalParameter (Report);
697 protected override void DoMemberTypeDependentChecks ()
699 base.DoMemberTypeDependentChecks ();
701 if (MemberType.IsStatic) {
702 Error_StaticReturnType ();
706 public override void Emit ()
708 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
709 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (MethodBuilder);
710 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
711 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (MethodBuilder);
712 if ((ModFlags & Modifiers.DEBUGGER_STEP_THROUGH) != 0)
713 Module.PredefinedAttributes.DebuggerStepThrough.EmitAttribute (MethodBuilder);
715 if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
716 Module.PredefinedAttributes.Dynamic.EmitAttribute (CreateReturnBuilder ().Builder);
717 } else if (ReturnType.HasDynamicElement) {
718 Module.PredefinedAttributes.Dynamic.EmitAttribute (CreateReturnBuilder ().Builder, ReturnType, Location);
721 if (ReturnType.HasNamedTupleElement) {
722 Module.PredefinedAttributes.TupleElementNames.EmitAttribute (CreateReturnBuilder ().Builder, ReturnType, Location);
725 if (OptAttributes != null)
726 OptAttributes.Emit ();
728 if (declarative_security != null) {
729 foreach (var de in declarative_security) {
731 MethodBuilder.__AddDeclarativeSecurity (de);
733 MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
739 // Optimization but it also covers cases where we cannot check
740 // constraints because method is captured into generated class
741 // and type parameters context is now different
743 if (type_expr != null && !IsCompilerGenerated)
744 ConstraintChecker.Check (this, member_type, type_expr.Location);
748 if (MethodData != null)
749 MethodData.Emit (Parent);
751 if (block != null && block.StateMachine is AsyncTaskStorey) {
752 var psm = Module.PredefinedAttributes.AsyncStateMachine;
753 psm.EmitAttribute (MethodBuilder, block.StateMachine);
756 if ((ModFlags & Modifiers.PARTIAL) == 0)
760 protected void Error_ConditionalAttributeIsNotValid ()
762 Report.Error (577, Location,
763 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
764 GetSignatureForError ());
767 public bool IsPartialDefinition {
769 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
773 public bool IsPartialImplementation {
775 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
779 public override string[] ValidAttributeTargets {
781 return attribute_targets;
785 #region IMethodData Members
787 bool IMethodData.IsAccessor {
793 public TypeSpec ReturnType {
799 public MemberName MethodName {
806 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
808 public override string[] ConditionalConditions ()
810 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
813 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
814 return new string [0];
816 caching_flags &= ~Flags.Excluded_Undetected;
819 if (base_method == null) {
820 if (OptAttributes == null)
823 Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
827 conditions = new string[attrs.Length];
828 for (int i = 0; i < conditions.Length; ++i)
829 conditions[i] = attrs[i].GetConditionalAttributeValue ();
831 conditions = base_method.MemberDefinition.ConditionalConditions();
834 if (conditions != null)
835 caching_flags |= Flags.Excluded;
842 public override void PrepareEmit ()
846 var mb = MethodData.DefineMethodBuilder (Parent);
848 if (CurrentTypeParameters != null) {
849 string[] gnames = new string[CurrentTypeParameters.Count];
850 for (int i = 0; i < gnames.Length; ++i) {
851 gnames[i] = CurrentTypeParameters[i].Name;
854 var gen_params = MethodBuilder.DefineGenericParameters (gnames);
856 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
857 var tp = CurrentTypeParameters[i];
859 tp.Define (gen_params[i]);
864 // Generic method has been already defined to resolve method parameters
865 // correctly when they use type parameters
867 mb.SetParameters (parameters.GetMetaInfo ());
868 mb.SetReturnType (ReturnType.GetMetaInfo ());
871 public override void WriteDebugSymbol (MonoSymbolFile file)
873 if (MethodData != null && !IsPartialDefinition)
874 MethodData.WriteDebugSymbol (file);
878 public class Method : MethodOrOperator, IGenericMethodDefinition
880 Method partialMethodImplementation;
882 public Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, MemberName name, ParametersCompiled parameters, Attributes attrs)
883 : base (parent, return_type, mod,
884 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
885 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct | Modifiers.ASYNC :
886 AllowedModifiersClass | Modifiers.ASYNC,
887 name, attrs, parameters)
891 protected Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
892 MemberName name, ParametersCompiled parameters, Attributes attrs)
893 : base (parent, return_type, mod, amod, name, attrs, parameters)
899 public override TypeParameters CurrentTypeParameters {
901 return MemberName.TypeParameters;
905 public TypeParameterSpec[] TypeParameters {
907 return CurrentTypeParameters.Types;
911 public int TypeParametersCount {
913 return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Count;
919 public override void Accept (StructuralVisitor visitor)
921 visitor.Visit (this);
924 public static Method Create (TypeDefinition parent, FullNamedExpression returnType, Modifiers mod,
925 MemberName name, ParametersCompiled parameters, Attributes attrs)
927 var m = new Method (parent, returnType, mod, name, parameters, attrs);
929 if ((mod & Modifiers.PARTIAL) != 0) {
930 const Modifiers invalid_partial_mod = Modifiers.AccessibilityMask | Modifiers.ABSTRACT | Modifiers.EXTERN |
931 Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.SEALED | Modifiers.VIRTUAL;
933 if ((mod & invalid_partial_mod) != 0) {
934 m.Report.Error (750, m.Location,
935 "A partial method cannot define access modifier or any of abstract, extern, new, override, sealed, or virtual modifiers");
936 mod &= ~invalid_partial_mod;
939 if ((parent.ModFlags & Modifiers.PARTIAL) == 0) {
940 m.Report.Error (751, m.Location,
941 "A partial method must be declared within a partial class or partial struct");
945 if ((mod & Modifiers.STATIC) == 0 && parameters.HasExtensionMethodType) {
946 m.Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static",
947 m.GetSignatureForError ());
954 public override string GetSignatureForError()
956 return base.GetSignatureForError () + parameters.GetSignatureForError ();
959 void Error_DuplicateEntryPoint (Method b)
961 Report.Error (17, b.Location,
962 "Program `{0}' has more than one entry point defined: `{1}'",
963 b.Module.Builder.ScopeName, b.GetSignatureForError ());
968 if (ReturnType.Kind != MemberKind.Void && ReturnType.BuiltinType != BuiltinTypeSpec.Type.Int)
971 if (parameters.IsEmpty)
974 if (parameters.Count > 1)
977 var ac = parameters.Types [0] as ArrayContainer;
978 return ac != null && ac.Rank == 1 && ac.Element.BuiltinType == BuiltinTypeSpec.Type.String &&
979 (parameters[0].ModFlags & Parameter.Modifier.RefOutMask) == 0;
982 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
985 var tp = CurrentTypeParameters;
987 TypeParameter t = tp.Find (name);
989 return new TypeParameterExpr (t, loc);
993 return base.LookupNamespaceOrType (name, arity, mode, loc);
996 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
998 if (a.Type == pa.Conditional) {
999 if (IsExplicitImpl) {
1000 Error_ConditionalAttributeIsNotValid ();
1004 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
1005 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
1009 if (ReturnType.Kind != MemberKind.Void) {
1010 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
1015 Report.Error (582, Location, "Conditional not valid on interface members");
1019 if (MethodData.implementing != null) {
1020 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
1021 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
1022 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
1026 for (int i = 0; i < parameters.Count; ++i) {
1027 if ((parameters.FixedParameters [i].ModFlags & Parameter.Modifier.OUT) != 0) {
1028 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
1034 if (a.Type == pa.Extension) {
1035 a.Error_MisusedExtensionAttribute ();
1039 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1042 void CreateTypeParameters ()
1044 var tparams = MemberName.TypeParameters;
1045 var parent_tparams = Parent.TypeParametersAll;
1047 for (int i = 0; i < MemberName.Arity; i++) {
1048 string type_argument_name = tparams[i].MemberName.Name;
1050 if (block == null) {
1051 int idx = parameters.GetParameterIndexByName (type_argument_name);
1055 b = new ToplevelBlock (Compiler, Location);
1057 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
1060 INamedBlockVariable variable = null;
1061 block.GetLocalName (type_argument_name, block, ref variable);
1062 if (variable != null)
1063 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
1066 if (parent_tparams != null) {
1067 var tp = parent_tparams.Find (type_argument_name);
1069 tparams[i].WarningParentNameConflict (tp);
1074 tparams.Create (null, 0, Parent);
1077 protected virtual void DefineTypeParameters ()
1079 var tparams = CurrentTypeParameters;
1081 TypeParameterSpec[] base_tparams = null;
1082 TypeParameterSpec[] base_decl_tparams = TypeParameterSpec.EmptyTypes;
1083 TypeSpec[] base_targs = TypeSpec.EmptyTypes;
1084 if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
1085 MethodSpec base_override = base_method ?? MethodData.implementing;
1087 if (base_override != null) {
1088 base_tparams = base_override.GenericDefinition.TypeParameters;
1090 if (base_override.DeclaringType.IsGeneric) {
1091 base_decl_tparams = base_override.DeclaringType.MemberDefinition.TypeParameters;
1093 if (base_method != null) {
1094 var base_type_parent = CurrentType;
1095 while (base_type_parent.BaseType != base_override.DeclaringType) {
1096 base_type_parent = base_type_parent.BaseType;
1099 base_targs = base_type_parent.BaseType.TypeArguments;
1101 foreach (var iface in Parent.CurrentType.Interfaces) {
1102 if (iface == base_override.DeclaringType) {
1103 base_targs = iface.TypeArguments;
1110 if (base_override.IsGeneric) {
1111 foreach (var base_tp in base_tparams) {
1112 base_tp.BaseType.CheckObsoleteness (this, Location);
1114 if (base_tp.InterfacesDefined != null) {
1115 foreach (var iface in base_tp.InterfacesDefined) {
1116 iface.CheckObsoleteness (this, Location);
1121 if (base_decl_tparams.Length != 0) {
1122 base_decl_tparams = base_decl_tparams.Concat (base_tparams).ToArray ();
1123 base_targs = base_targs.Concat (tparams.Types).ToArray ();
1125 base_decl_tparams = base_tparams;
1126 base_targs = tparams.Types;
1132 for (int i = 0; i < tparams.Count; ++i) {
1133 var tp = tparams [i];
1135 if (base_tparams == null) {
1136 tp.ResolveConstraints (this);
1141 // Copy base constraints for override/explicit methods
1143 var base_tparam = base_tparams [i];
1144 var local_tparam = tp.Type;
1145 local_tparam.SpecialConstraint = base_tparam.SpecialConstraint;
1147 var inflator = new TypeParameterInflator (this, CurrentType, base_decl_tparams, base_targs);
1148 base_tparam.InflateConstraints (inflator, local_tparam);
1151 // Check all type argument constraints for possible collision or unification
1152 // introduced by inflating inherited constraints in this context
1154 // Conflict example:
1156 // class A<T> { virtual void Foo<U> () where U : class, T {} }
1157 // class B : A<int> { override void Foo<U> {} }
1159 var local_tparam_targs = local_tparam.TypeArguments;
1160 if (local_tparam_targs != null) {
1161 for (int ii = 0; ii < local_tparam_targs.Length; ++ii) {
1162 var ta = local_tparam_targs [ii];
1163 if (!ta.IsClass && !ta.IsStruct)
1166 TypeSpec[] unique_tparams = null;
1167 for (int iii = ii + 1; iii < local_tparam_targs.Length; ++iii) {
1169 // Remove any identical or unified constraint types
1171 var tparam_checked = local_tparam_targs [iii];
1172 if (TypeSpecComparer.IsEqual (ta, tparam_checked) || TypeSpec.IsBaseClass (ta, tparam_checked, false)) {
1173 unique_tparams = new TypeSpec[local_tparam_targs.Length - 1];
1174 Array.Copy (local_tparam_targs, 0, unique_tparams, 0, iii);
1175 Array.Copy (local_tparam_targs, iii + 1, unique_tparams, iii, local_tparam_targs.Length - iii - 1);
1176 } else if (!TypeSpec.IsBaseClass (tparam_checked, ta, false)) {
1177 Constraints.Error_ConflictingConstraints (this, local_tparam, ta, tparam_checked, Location);
1181 if (unique_tparams != null) {
1182 local_tparam_targs = unique_tparams;
1183 local_tparam.TypeArguments = local_tparam_targs;
1187 Constraints.CheckConflictingInheritedConstraint (local_tparam, ta, this, Location);
1192 if (base_tparams == null && MethodData != null && MethodData.implementing != null) {
1193 CheckImplementingMethodConstraints (Parent, spec, MethodData.implementing);
1197 public static bool CheckImplementingMethodConstraints (TypeContainer container, MethodSpec method, MethodSpec baseMethod)
1199 var tparams = method.Constraints;
1200 var base_tparams = baseMethod.Constraints;
1201 for (int i = 0; i < tparams.Length; ++i) {
1202 if (!tparams[i].HasSameConstraintsImplementation (base_tparams[i])) {
1203 container.Compiler.Report.SymbolRelatedToPreviousError (method);
1204 container.Compiler.Report.SymbolRelatedToPreviousError (baseMethod);
1206 // Using container location because the interface can be implemented
1208 var tp = (tparams [i].MemberDefinition as MemberCore) ?? container;
1209 container.Compiler.Report.Error (425, tp.Location,
1210 "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",
1211 tparams[i].GetSignatureForError (), method.GetSignatureForError (),
1212 base_tparams[i].GetSignatureForError (), baseMethod.GetSignatureForError ());
1224 public override bool Define ()
1226 if (!base.Define ())
1229 if (member_type.Kind == MemberKind.Void && parameters.IsEmpty && MemberName.Arity == 0 && MemberName.Name == Destructor.MetadataName) {
1230 Report.Warning (465, 1, Location,
1231 "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
1234 if (Compiler.Settings.StdLib && ReturnType.IsSpecialRuntimeType) {
1235 Error1599 (Location, ReturnType, Report);
1239 if (CurrentTypeParameters == null) {
1240 if (base_method != null && !IsExplicitImpl) {
1241 if (parameters.Count == 1 && ParameterTypes[0].BuiltinType == BuiltinTypeSpec.Type.Object && MemberName.Name == "Equals")
1242 Parent.PartialContainer.Mark_HasEquals ();
1243 else if (parameters.IsEmpty && MemberName.Name == "GetHashCode")
1244 Parent.PartialContainer.Mark_HasGetHashCode ();
1248 DefineTypeParameters ();
1251 if (block != null) {
1252 if (block.IsIterator) {
1254 // Current method is turned into automatically generated
1255 // wrapper which creates an instance of iterator
1257 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1258 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
1261 if ((ModFlags & Modifiers.ASYNC) != 0) {
1262 if (ReturnType.Kind != MemberKind.Void &&
1263 ReturnType != Module.PredefinedTypes.Task.TypeSpec &&
1264 !ReturnType.IsGenericTask) {
1265 Report.Error (1983, Location, "The return type of an async method must be void, Task, or Task<T>");
1268 block = (ToplevelBlock) block.ConvertToAsyncTask (this, Parent.PartialContainer, parameters, ReturnType, null, Location);
1269 ModFlags |= Modifiers.DEBUGGER_STEP_THROUGH;
1272 if (Compiler.Settings.WriteMetadataOnly)
1276 if ((ModFlags & Modifiers.STATIC) == 0)
1279 if (parameters.HasExtensionMethodType) {
1280 if (Parent.PartialContainer.IsStatic && !Parent.IsGenericOrParentIsGeneric) {
1281 if (!Parent.IsTopLevel)
1282 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
1283 GetSignatureForError ());
1285 PredefinedAttribute pa = Module.PredefinedAttributes.Extension;
1286 if (!pa.IsDefined) {
1287 Report.Error (1110, Location,
1288 "`{0}': Extension methods require `System.Runtime.CompilerServices.ExtensionAttribute' type to be available. Are you missing an assembly reference?",
1289 GetSignatureForError ());
1292 ModFlags |= Modifiers.METHOD_EXTENSION;
1293 Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
1294 Spec.DeclaringType.SetExtensionMethodContainer ();
1295 Parent.Module.HasExtensionMethod = true;
1297 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
1298 GetSignatureForError ());
1303 // This is used to track the Entry Point,
1305 var settings = Compiler.Settings;
1306 if (settings.NeedsEntryPoint && MemberName.Name == "Main" && !IsPartialDefinition && (settings.MainClass == null || settings.MainClass == Parent.TypeBuilder.FullName)) {
1307 if (IsEntryPoint ()) {
1308 if (Parent.DeclaringAssembly.EntryPoint == null) {
1309 if (Parent.IsGenericOrParentIsGeneric || MemberName.IsGeneric) {
1310 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
1311 GetSignatureForError ());
1312 } else if ((ModFlags & Modifiers.ASYNC) != 0) {
1313 Report.Error (4009, Location, "`{0}': an entry point cannot be async method",
1314 GetSignatureForError ());
1317 Parent.DeclaringAssembly.EntryPoint = this;
1320 Error_DuplicateEntryPoint (Parent.DeclaringAssembly.EntryPoint);
1321 Error_DuplicateEntryPoint (this);
1324 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
1325 GetSignatureForError ());
1332 public override void PrepareEmit ()
1334 if (IsPartialDefinition) {
1336 // Use partial method implementation builder for partial method declaration attributes
1338 if (partialMethodImplementation != null) {
1339 MethodData = partialMethodImplementation.MethodData;
1345 base.PrepareEmit ();
1351 public override void Emit ()
1354 if (IsPartialDefinition) {
1355 if (partialMethodImplementation != null && CurrentTypeParameters != null) {
1356 CurrentTypeParameters.CheckPartialConstraints (partialMethodImplementation);
1358 var otp = partialMethodImplementation.CurrentTypeParameters;
1359 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1360 var tp = CurrentTypeParameters [i];
1368 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
1369 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
1370 GetSignatureForError ());
1373 if (CurrentTypeParameters != null) {
1374 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1375 var tp = CurrentTypeParameters [i];
1377 tp.CheckGenericConstraints (false);
1382 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
1383 Module.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
1386 } catch (Exception e) {
1387 throw new InternalErrorException (this, e);
1391 public override bool EnableOverloadChecks (MemberCore overload)
1393 if (overload is Indexer)
1396 return base.EnableOverloadChecks (overload);
1399 public static void Error1599 (Location loc, TypeSpec t, Report Report)
1401 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", t.GetSignatureForError ());
1404 protected override bool ResolveMemberType ()
1406 if (CurrentTypeParameters != null) {
1407 CreateTypeParameters ();
1410 return base.ResolveMemberType ();
1413 public void SetPartialDefinition (Method methodDefinition)
1415 caching_flags |= Flags.PartialDefinitionExists;
1416 methodDefinition.partialMethodImplementation = this;
1418 // Ensure we are always using method declaration parameters
1419 for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
1420 var md_p = methodDefinition.parameters [i];
1421 var p = parameters [i];
1423 p.DefaultValue = md_p.DefaultValue;
1424 if (md_p.OptAttributes != null) {
1425 Attributes.AttachFromPartial (p, md_p);
1429 if (methodDefinition.attributes != null) {
1430 if (attributes == null) {
1431 attributes = methodDefinition.attributes;
1433 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
1437 if (CurrentTypeParameters != null) {
1438 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1439 var tp_other = methodDefinition.CurrentTypeParameters [i];
1440 if (tp_other.OptAttributes == null)
1443 var tp = CurrentTypeParameters [i];
1444 if (tp.OptAttributes == null) {
1445 tp.OptAttributes = tp_other.OptAttributes;
1447 tp.OptAttributes.Attrs.AddRange (tp.OptAttributes.Attrs);
1454 public abstract class ConstructorInitializer : ExpressionStatement
1456 Arguments argument_list;
1457 MethodSpec base_ctor;
1459 protected ConstructorInitializer (Arguments argument_list, Location loc)
1461 this.argument_list = argument_list;
1465 public Arguments Arguments {
1467 return argument_list;
1471 public override bool ContainsEmitWithAwait ()
1473 throw new NotSupportedException ();
1476 public override Expression CreateExpressionTree (ResolveContext ec)
1478 throw new NotSupportedException ("ET");
1481 protected override Expression DoResolve (ResolveContext ec)
1483 eclass = ExprClass.Value;
1486 var caller_builder = (Constructor) ec.MemberContext;
1489 // Spec mandates that constructor initializer will not have `this' access
1491 using (ec.Set (ResolveContext.Options.BaseInitializer)) {
1492 if (argument_list != null) {
1494 argument_list.Resolve (ec, out dynamic);
1497 ec.Report.Error (1975, loc,
1498 "The constructor call cannot be dynamically dispatched within constructor initializer");
1504 type = ec.CurrentType;
1505 if (this is ConstructorBaseInitializer) {
1506 if (ec.CurrentType.BaseType == null)
1509 type = ec.CurrentType.BaseType;
1510 if (ec.CurrentType.IsStruct) {
1511 ec.Report.Error (522, loc,
1512 "`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
1517 base_ctor = ConstructorLookup (ec, type, ref argument_list, loc);
1520 if (base_ctor != null && base_ctor.MemberDefinition == caller_builder.Spec.MemberDefinition) {
1521 ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
1522 caller_builder.GetSignatureForError ());
1528 public override void Emit (EmitContext ec)
1531 // It can be null for struct initializers or System.Object
1533 if (base_ctor == null) {
1534 if (type == ec.BuiltinTypes.Object)
1537 ec.Emit (OpCodes.Ldarg_0);
1538 ec.Emit (OpCodes.Initobj, type);
1542 var call = new CallEmitter ();
1543 call.InstanceExpression = new CompilerGeneratedThis (type, loc);
1544 call.EmitPredefined (ec, base_ctor, argument_list, false);
1547 public override void EmitStatement (EmitContext ec)
1552 public override void FlowAnalysis (FlowAnalysisContext fc)
1554 if (argument_list != null)
1555 argument_list.FlowAnalysis (fc);
1559 public class ConstructorBaseInitializer : ConstructorInitializer {
1560 public ConstructorBaseInitializer (Arguments argument_list, Location l) :
1561 base (argument_list, l)
1566 class GeneratedBaseInitializer: ConstructorBaseInitializer {
1567 public GeneratedBaseInitializer (Location loc, Arguments arguments)
1568 : base (arguments, loc)
1573 public class ConstructorThisInitializer : ConstructorInitializer {
1574 public ConstructorThisInitializer (Arguments argument_list, Location l) :
1575 base (argument_list, l)
1580 public class Constructor : MethodCore, IMethodData, IMethodDefinition
1582 public ConstructorBuilder ConstructorBuilder;
1583 public ConstructorInitializer Initializer;
1584 SecurityType declarative_security;
1585 bool has_compliant_args;
1586 SourceMethodBuilder debug_builder;
1589 // Modifiers allowed for a constructor.
1591 public const Modifiers AllowedModifiers =
1593 Modifiers.PROTECTED |
1594 Modifiers.INTERNAL |
1600 static readonly string[] attribute_targets = new string [] { "method" };
1602 public static readonly string ConstructorName = ".ctor";
1603 public static readonly string TypeConstructorName = ".cctor";
1605 public Constructor (TypeDefinition parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args, Location loc)
1606 : base (parent, null, mod, AllowedModifiers, new MemberName (name, loc), attrs, args)
1610 public bool HasCompliantArgs {
1612 return has_compliant_args;
1616 public override AttributeTargets AttributeTargets {
1618 return AttributeTargets.Constructor;
1622 bool IMethodData.IsAccessor {
1628 public bool IsPrimaryConstructor { get; set; }
1630 MethodBase IMethodDefinition.Metadata {
1632 return ConstructorBuilder;
1637 // Returns true if this is a default constructor
1639 public bool IsDefault ()
1641 if ((ModFlags & Modifiers.STATIC) != 0)
1642 return parameters.IsEmpty;
1644 return parameters.IsEmpty &&
1645 (Initializer is ConstructorBaseInitializer) &&
1646 (Initializer.Arguments == null);
1649 public override void Accept (StructuralVisitor visitor)
1651 visitor.Visit (this);
1654 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1656 if (a.IsValidSecurityAttribute ()) {
1657 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
1661 if (a.Type == pa.MethodImpl) {
1662 is_external_implementation = a.IsInternalCall ();
1665 ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1668 protected override bool CheckBase ()
1670 if ((ModFlags & Modifiers.STATIC) != 0) {
1671 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1672 Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1674 // the rest can be ignored
1678 // Check whether arguments were correct.
1679 if (!DefineParameters (parameters))
1682 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1683 Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1685 CheckProtectedModifier ();
1691 // Creates the ConstructorBuilder
1693 public override bool Define ()
1695 if (ConstructorBuilder != null)
1698 if (!CheckAbstractAndExtern (block != null))
1701 // Check if arguments were correct.
1705 if (Parent.PrimaryConstructorParameters != null && !IsPrimaryConstructor && !IsStatic) {
1706 if (Parent.Kind == MemberKind.Struct && Initializer is ConstructorThisInitializer && Initializer.Arguments == null) {
1707 Report.Error (8043, Location, "`{0}': Structs with primary constructor cannot specify default constructor initializer",
1708 GetSignatureForError ());
1709 } else if (Initializer == null || Initializer is ConstructorBaseInitializer) {
1710 Report.Error (8037, Location, "`{0}': Instance constructor of type with primary constructor must specify `this' constructor initializer",
1711 GetSignatureForError ());
1715 if ((ModFlags & Modifiers.EXTERN) != 0 && Initializer != null) {
1716 Report.Error (8091, Location, "`{0}': Contructors cannot be extern and have a constructor initializer",
1717 GetSignatureForError ());
1720 var ca = ModifiersExtensions.MethodAttr (ModFlags) | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
1722 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
1723 ca, CallingConventions,
1724 parameters.GetMetaInfo ());
1726 spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, Compiler.BuiltinTypes.Void, parameters, ModFlags);
1728 Parent.MemberCache.AddMember (spec);
1730 if (block != null) {
1731 // It's here only to report an error
1732 if (block.IsIterator) {
1733 member_type = Compiler.BuiltinTypes.Void;
1734 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1737 if (Compiler.Settings.WriteMetadataOnly)
1747 public override void Emit ()
1749 if (Parent.PartialContainer.IsComImport) {
1750 if (!IsDefault ()) {
1751 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
1752 Parent.GetSignatureForError ());
1755 // Set as internal implementation and reset block data
1756 // to ensure no IL is generated
1757 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
1761 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
1762 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (ConstructorBuilder);
1764 if (OptAttributes != null)
1765 OptAttributes.Emit ();
1768 parameters.ApplyAttributes (this, ConstructorBuilder);
1771 BlockContext bc = new BlockContext (this, block, Compiler.BuiltinTypes.Void);
1772 bc.Set (ResolveContext.Options.ConstructorScope);
1774 if (block != null) {
1775 if (!IsStatic && Initializer == null && Parent.PartialContainer.Kind == MemberKind.Struct) {
1777 // If this is a non-static `struct' constructor and doesn't have any
1778 // initializer, it must initialize all of the struct's fields.
1780 block.AddThisVariable (bc);
1784 // If we use a "this (...)" constructor initializer, then
1785 // do not emit field initializers, they are initialized in the other constructor
1787 if (!(Initializer is ConstructorThisInitializer)) {
1788 var errors = Compiler.Report.Errors;
1789 Parent.PartialContainer.ResolveFieldInitializers (bc);
1790 if (errors != Compiler.Report.Errors)
1795 if (Initializer == null && Parent.PartialContainer.Kind == MemberKind.Class) {
1796 Initializer = new GeneratedBaseInitializer (Location, null);
1799 if (Initializer != null) {
1801 // mdb format does not support reqions. Try to workaround this by emitting the
1802 // sequence point at initializer. Any breakpoint at constructor header should
1803 // be adjusted to this sequence point as it's the next one which follows.
1805 block.AddScopeStatement (new StatementExpression (Initializer));
1809 if (block.Resolve (bc, this)) {
1810 debug_builder = Parent.CreateMethodSymbolEntry ();
1811 EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType, debug_builder);
1812 ec.With (EmitContext.Options.ConstructorScope, true);
1818 if (declarative_security != null) {
1819 foreach (var de in declarative_security) {
1821 ConstructorBuilder.__AddDeclarativeSecurity (de);
1823 ConstructorBuilder.AddDeclarativeSecurity (de.Key, de.Value);
1831 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
1833 // Is never override
1834 bestCandidate = null;
1838 public override string GetCallerMemberName ()
1840 return IsStatic ? TypeConstructorName : ConstructorName;
1843 public override string GetSignatureForDocumentation ()
1845 return Parent.GetSignatureForDocumentation () + ".#ctor" + parameters.GetSignatureForDocumentation ();
1848 public override string GetSignatureForError()
1850 return base.GetSignatureForError () + parameters.GetSignatureForError ();
1853 public override string[] ValidAttributeTargets {
1855 return attribute_targets;
1859 protected override bool VerifyClsCompliance ()
1861 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
1865 if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
1866 foreach (TypeSpec param in parameters.Types) {
1867 if (param.IsArray) {
1873 has_compliant_args = true;
1877 public override void WriteDebugSymbol (MonoSymbolFile file)
1879 if (debug_builder == null)
1882 #if !FULL_AOT_RUNTIME
1883 var token = ConstructorBuilder.GetToken ();
1884 int t = token.Token;
1886 if (ModuleBuilder.IsPseudoToken (t))
1887 t = Module.Builder.ResolvePseudoToken (t);
1890 debug_builder.DefineMethod (file, t);
1894 #region IMethodData Members
1896 public MemberName MethodName {
1902 public TypeSpec ReturnType {
1908 EmitContext IMethodData.CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
1910 throw new NotImplementedException ();
1917 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
1919 public interface IMethodData : IMemberContext
1921 CallingConventions CallingConventions { get; }
1922 Location Location { get; }
1923 MemberName MethodName { get; }
1924 TypeSpec ReturnType { get; }
1925 ParametersCompiled ParameterInfo { get; }
1926 MethodSpec Spec { get; }
1927 bool IsAccessor { get; }
1929 Attributes OptAttributes { get; }
1930 ToplevelBlock Block { get; set; }
1932 EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod);
1936 // Encapsulates most of the Method's state
1938 public class MethodData
1940 public readonly IMethodData method;
1943 // Are we implementing an interface ?
1945 public MethodSpec implementing;
1950 protected InterfaceMemberBase member;
1951 protected Modifiers modifiers;
1952 protected MethodAttributes flags;
1953 protected TypeSpec declaring_type;
1954 SourceMethodBuilder debug_builder;
1957 MethodBuilder builder;
1958 public MethodBuilder MethodBuilder {
1964 public TypeSpec DeclaringType {
1966 return declaring_type;
1970 public string MetadataName {
1976 public MethodData (InterfaceMemberBase member,
1977 Modifiers modifiers, MethodAttributes flags, IMethodData method)
1979 this.member = member;
1980 this.modifiers = modifiers;
1983 this.method = method;
1986 public bool Define (TypeDefinition container, string method_full_name)
1988 PendingImplementation pending = container.PendingImplementations;
1989 MethodSpec ambig_iface_method;
1990 bool optional = false;
1992 if (pending != null) {
1993 implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this, out ambig_iface_method, ref optional);
1995 if (member.InterfaceType != null) {
1996 if (implementing == null) {
1997 if (member is PropertyBase) {
1998 container.Compiler.Report.Error (550, method.Location,
1999 "`{0}' is an accessor not found in interface member `{1}{2}'",
2000 method.GetSignatureForError (), member.InterfaceType.GetSignatureForError (),
2001 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
2004 container.Compiler.Report.Error (539, method.Location,
2005 "`{0}.{1}' in explicit interface declaration is not a member of interface",
2006 member.InterfaceType.GetSignatureForError (), member.ShortName);
2010 if (implementing.IsAccessor && !method.IsAccessor) {
2011 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2012 container.Compiler.Report.Error (683, method.Location,
2013 "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
2014 member.GetSignatureForError (), implementing.GetSignatureForError ());
2018 if (implementing != null && !optional) {
2019 if (!method.IsAccessor) {
2020 if (implementing.IsAccessor) {
2021 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2022 container.Compiler.Report.Error (470, method.Location,
2023 "Method `{0}' cannot implement interface accessor `{1}'",
2024 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
2026 } else if (implementing.DeclaringType.IsInterface) {
2027 if (!implementing.IsAccessor) {
2028 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2029 container.Compiler.Report.Error (686, method.Location,
2030 "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
2031 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
2033 PropertyBase.PropertyMethod pm = method as PropertyBase.PropertyMethod;
2034 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
2035 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2036 container.Compiler.Report.Error (277, method.Location,
2037 "Accessor `{0}' must be declared public to implement interface member `{1}'",
2038 method.GetSignatureForError (), implementing.GetSignatureForError ());
2043 if (!NamedTupleSpec.CheckOverrideName (member.MemberType, implementing.ReturnType)) {
2044 container.Compiler.Report.Error (8141, method.Location,
2045 "The tuple element names in the signature type of member `{0}' must match the tuple element names of interface member `{1}''",
2046 member.GetSignatureForError (), implementing.GetSignatureForError ());
2049 var p_member = method as IParametersMember;
2050 var p_implementing = implementing as IParametersMember;
2051 if (p_member != null && p_implementing != null && !NamedTupleSpec.CheckOverrideName (p_member, p_implementing)) {
2052 container.Compiler.Report.Error (8141, method.Location,
2053 "The tuple element names in the signature type of member `{0}' must match the tuple element names of interface member `{1}''",
2054 member.GetSignatureForError (), implementing.GetSignatureForError ());
2059 ambig_iface_method = null;
2063 // For implicit implementations, make sure we are public, for
2064 // explicit implementations, make sure we are private.
2066 if (implementing != null){
2067 if (member.IsExplicitImpl) {
2068 if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
2069 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2070 container.Compiler.Report.Error (466, method.Location,
2071 "`{0}': the explicit interface implementation cannot introduce the params modifier",
2072 method.GetSignatureForError ());
2075 if (ambig_iface_method != null) {
2076 container.Compiler.Report.SymbolRelatedToPreviousError (ambig_iface_method);
2077 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2078 container.Compiler.Report.Warning (473, 2, method.Location,
2079 "Explicit interface implementation `{0}' matches more than one interface member. Consider using a non-explicit implementation instead",
2080 method.GetSignatureForError ());
2084 // Setting implementing to null inside this block will trigger a more
2085 // verbose error reporting for missing interface implementations
2087 if (implementing.DeclaringType.IsInterface) {
2089 // If this is an interface method implementation,
2090 // check for public accessibility
2092 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) {
2093 implementing = null;
2094 } else if (optional && (container.Interfaces == null || !container.Definition.Interfaces.Contains (implementing.DeclaringType))) {
2096 // We are not implementing interface when base class already implemented it
2098 implementing = null;
2100 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2101 // We may never be private.
2102 implementing = null;
2104 } else if ((modifiers & Modifiers.OVERRIDE) == 0) {
2106 // We may be protected if we're overriding something.
2108 implementing = null;
2113 // Static is not allowed
2115 if ((modifiers & Modifiers.STATIC) != 0){
2116 implementing = null;
2121 // If implementing is still valid, set flags
2123 if (implementing != null){
2125 // When implementing interface methods, set NewSlot
2126 // unless, we are overwriting a method.
2128 if ((modifiers & Modifiers.OVERRIDE) == 0 && implementing.DeclaringType.IsInterface) {
2129 flags |= MethodAttributes.NewSlot;
2132 flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;
2134 // Set Final unless we're virtual, abstract or already overriding a method.
2135 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
2136 flags |= MethodAttributes.Final;
2139 // clear the pending implementation flag (requires explicit methods to be defined first)
2141 pending.ImplementMethod (method.MethodName,
2142 member.InterfaceType, this, member.IsExplicitImpl, out ambig_iface_method, ref optional);
2145 // Update indexer accessor name to match implementing abstract accessor
2147 if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
2148 method_full_name = implementing.MemberDefinition.Name;
2151 full_name = method_full_name;
2152 declaring_type = container.Definition;
2157 void DefineOverride (TypeDefinition container)
2159 if (implementing == null)
2162 if (!member.IsExplicitImpl)
2165 container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
2169 // Creates partial MethodBuilder for the method when has generic parameters used
2170 // as arguments or return type
2172 public MethodBuilder DefineMethodBuilder (TypeDefinition container)
2174 if (builder != null)
2175 throw new InternalErrorException ();
2177 builder = container.TypeBuilder.DefineMethod (full_name, flags, method.CallingConventions);
2182 // Creates full MethodBuilder for the method
2184 public MethodBuilder DefineMethodBuilder (TypeDefinition container, ParametersCompiled param)
2186 DefineMethodBuilder (container);
2187 builder.SetReturnType (method.ReturnType.GetMetaInfo ());
2188 builder.SetParameters (param.GetMetaInfo ());
2195 public void Emit (TypeDefinition parent)
2197 DefineOverride (parent);
2199 method.ParameterInfo.ApplyAttributes (method, MethodBuilder);
2201 ToplevelBlock block = method.Block;
2202 if (block != null) {
2203 BlockContext bc = new BlockContext (method, block, method.ReturnType);
2204 if (block.Resolve (bc, method)) {
2205 debug_builder = member.Parent.CreateMethodSymbolEntry ();
2206 EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator (), debug_builder);
2213 public void WriteDebugSymbol (MonoSymbolFile file)
2215 if (debug_builder == null)
2218 #if !FULL_AOT_RUNTIME
2219 var token = builder.GetToken ();
2220 int t = token.Token;
2222 if (ModuleBuilder.IsPseudoToken (t))
2223 t = member.Module.Builder.ResolvePseudoToken (t);
2226 debug_builder.DefineMethod (file, t);
2231 public class Destructor : MethodOrOperator
2233 const Modifiers AllowedModifiers =
2237 static readonly string[] attribute_targets = new string [] { "method" };
2239 public static readonly string MetadataName = "Finalize";
2241 public Destructor (TypeDefinition parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
2242 : base (parent, null, mod, AllowedModifiers, new MemberName (MetadataName, l), attrs, parameters)
2244 ModFlags &= ~Modifiers.PRIVATE;
2245 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
2248 public override void Accept (StructuralVisitor visitor)
2250 visitor.Visit (this);
2253 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2255 if (a.Type == pa.Conditional) {
2256 Error_ConditionalAttributeIsNotValid ();
2260 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2263 protected override bool CheckBase ()
2265 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2266 CheckForDuplications ();
2268 // Don't check base, destructors have special syntax
2272 public override bool Define ()
2276 if (Compiler.Settings.WriteMetadataOnly)
2282 public override void Emit()
2284 var base_type = Parent.PartialContainer.BaseType;
2285 if (base_type != null && Block != null) {
2286 var base_dtor = MemberCache.FindMember (base_type,
2287 new MemberFilter (MetadataName, 0, MemberKind.Destructor, null, null), BindingRestriction.InstanceOnly) as MethodSpec;
2289 if (base_dtor == null)
2290 throw new NotImplementedException ();
2292 MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
2293 method_expr.InstanceExpression = new BaseThis (base_type, Location);
2295 var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation) {
2296 IsCompilerGenerated = true
2298 var finaly_block = new ExplicitBlock (block, Location, Location) {
2299 IsCompilerGenerated = true
2303 // 0-size arguments to avoid CS0250 error
2304 // TODO: Should use AddScopeStatement or something else which emits correct
2307 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0)), Location.Null));
2309 var tf = new TryFinally (try_block, finaly_block, Location);
2310 block.WrapIntoDestructor (tf, try_block);
2316 public override string GetSignatureForError ()
2318 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
2321 protected override bool ResolveMemberType ()
2323 member_type = Compiler.BuiltinTypes.Void;
2327 public override string[] ValidAttributeTargets {
2329 return attribute_targets;
2334 // Ooouh Martin, templates are missing here.
2335 // When it will be possible move here a lot of child code and template method type.
2336 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData, IMethodDefinition {
2337 protected MethodData method_data;
2338 protected ToplevelBlock block;
2339 protected SecurityType declarative_security;
2341 protected readonly string prefix;
2343 ReturnParameter return_attributes;
2345 protected AbstractPropertyEventMethod (InterfaceMemberBase member, string prefix, Attributes attrs, Location loc)
2346 : base (member.Parent, SetupName (prefix, member, loc), attrs)
2348 this.prefix = prefix;
2351 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
2353 return new MemberName (member.MemberName.Left, prefix + member.ShortName, member.MemberName.ExplicitInterface, loc);
2356 public void UpdateName (InterfaceMemberBase member)
2358 SetMemberName (SetupName (prefix, member, Location));
2361 #region IMethodData Members
2363 public ToplevelBlock Block {
2373 public CallingConventions CallingConventions {
2375 return CallingConventions.Standard;
2379 public EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
2381 return new EmitContext (this, ig, ReturnType, sourceMethod);
2384 public bool IsAccessor {
2390 public MemberName MethodName {
2396 public TypeSpec[] ParameterTypes {
2398 return ParameterInfo.Types;
2402 MethodBase IMethodDefinition.Metadata {
2404 return method_data.MethodBuilder;
2408 public abstract ParametersCompiled ParameterInfo { get ; }
2409 public abstract TypeSpec ReturnType { get; }
2413 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2415 if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
2416 Report.Error (1667, a.Location,
2417 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
2418 a.Type.GetSignatureForError (), a.GetValidTargets ());
2422 if (a.IsValidSecurityAttribute ()) {
2423 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
2427 if (a.Target == AttributeTargets.Method) {
2428 method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
2432 if (a.Target == AttributeTargets.ReturnValue) {
2433 CreateReturnBuilder ();
2434 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
2438 ApplyToExtraTarget (a, ctor, cdata, pa);
2441 protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2443 throw new NotSupportedException ("You forgot to define special attribute target handling");
2446 // It is not supported for the accessors
2447 public sealed override bool Define()
2449 throw new NotSupportedException ();
2452 ReturnParameter CreateReturnBuilder ()
2454 return return_attributes ?? (return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location));
2457 public virtual void Emit (TypeDefinition parent)
2459 method_data.Emit (parent);
2461 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
2462 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
2463 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
2464 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
2466 if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2467 Module.PredefinedAttributes.Dynamic.EmitAttribute (CreateReturnBuilder ().Builder);
2468 } else if (ReturnType.HasDynamicElement) {
2469 Module.PredefinedAttributes.Dynamic.EmitAttribute (CreateReturnBuilder ().Builder, ReturnType, Location);
2472 if (ReturnType.HasNamedTupleElement) {
2473 Module.PredefinedAttributes.TupleElementNames.EmitAttribute (CreateReturnBuilder ().Builder, ReturnType, Location);
2476 if (OptAttributes != null)
2477 OptAttributes.Emit ();
2479 if (declarative_security != null) {
2480 foreach (var de in declarative_security) {
2482 method_data.MethodBuilder.__AddDeclarativeSecurity (de);
2484 method_data.MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2492 public override bool EnableOverloadChecks (MemberCore overload)
2494 if (overload is MethodCore) {
2495 caching_flags |= Flags.MethodOverloadsExist;
2499 // This can only happen with indexers and it will
2500 // be catched as indexer difference
2501 if (overload is AbstractPropertyEventMethod)
2507 public override string GetCallerMemberName ()
2509 return base.GetCallerMemberName ().Substring (prefix.Length);
2512 public override string GetSignatureForDocumentation ()
2514 // should not be called
2515 throw new NotSupportedException ();
2518 public override bool IsClsComplianceRequired()
2523 public void PrepareEmit ()
2525 method_data.DefineMethodBuilder (Parent.PartialContainer, ParameterInfo);
2528 public override void WriteDebugSymbol (MonoSymbolFile file)
2530 if (method_data != null)
2531 method_data.WriteDebugSymbol (file);
2534 public MethodSpec Spec { get; protected set; }
2537 // Represents header string for documentation comment.
2539 public override string DocCommentHeader {
2540 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
2544 public class Operator : MethodOrOperator {
2546 const Modifiers AllowedModifiers =
2552 public enum OpType : byte {
2562 // Unary and Binary operators
2585 // Implicit and Explicit
2592 // Just because of enum
2596 public readonly OpType OperatorType;
2598 static readonly string [] [] names;
2602 names = new string[(int)OpType.TOP][];
2603 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
2604 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
2605 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
2606 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
2607 names [(int) OpType.True] = new string [] { "true", "op_True" };
2608 names [(int) OpType.False] = new string [] { "false", "op_False" };
2609 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
2610 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
2611 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
2612 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
2613 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
2614 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
2615 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
2616 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
2617 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
2618 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
2619 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
2620 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
2621 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
2622 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
2623 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
2624 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
2625 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
2626 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
2627 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
2628 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
2629 names [(int) OpType.Is] = new string[] { "is", "op_Is" };
2632 public Operator (TypeDefinition parent, OpType type, FullNamedExpression ret_type, Modifiers mod_flags, ParametersCompiled parameters,
2633 ToplevelBlock block, Attributes attrs, Location loc)
2634 : base (parent, ret_type, mod_flags, AllowedModifiers, new MemberName (GetMetadataName (type), loc), attrs, parameters)
2636 OperatorType = type;
2640 public override void Accept (StructuralVisitor visitor)
2642 visitor.Visit (this);
2645 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2647 if (a.Type == pa.Conditional) {
2648 Error_ConditionalAttributeIsNotValid ();
2652 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2655 public override bool Define ()
2657 const Modifiers RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
2658 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
2659 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
2662 if (!base.Define ())
2665 if (block != null) {
2666 if (block.IsIterator) {
2668 // Current method is turned into automatically generated
2669 // wrapper which creates an instance of iterator
2671 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
2672 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
2675 if (Compiler.Settings.WriteMetadataOnly)
2679 // imlicit and explicit operator of same types are not allowed
2680 if (OperatorType == OpType.Explicit)
2681 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
2682 else if (OperatorType == OpType.Implicit)
2683 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
2685 TypeSpec declaring_type = Parent.PartialContainer.CurrentType;
2686 TypeSpec return_type = MemberType;
2687 TypeSpec first_arg_type = ParameterTypes [0];
2689 TypeSpec first_arg_type_unwrap = first_arg_type;
2690 if (first_arg_type.IsNullableType)
2691 first_arg_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (first_arg_type);
2693 TypeSpec return_type_unwrap = return_type;
2694 if (return_type.IsNullableType)
2695 return_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (return_type);
2698 // Rules for conversion operators
2700 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2701 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type) {
2702 Report.Error (555, Location,
2703 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
2708 if (declaring_type == return_type || declaring_type == return_type_unwrap) {
2709 conv_type = first_arg_type;
2710 } else if (declaring_type == first_arg_type || declaring_type == first_arg_type_unwrap) {
2711 conv_type = return_type;
2713 Report.Error (556, Location,
2714 "User-defined conversion must convert to or from the enclosing type");
2718 if (conv_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2719 Report.Error (1964, Location,
2720 "User-defined conversion `{0}' cannot convert to or from the dynamic type",
2721 GetSignatureForError ());
2726 if (conv_type.IsInterface) {
2727 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
2728 GetSignatureForError ());
2732 if (conv_type.IsClass) {
2733 if (TypeSpec.IsBaseClass (declaring_type, conv_type, true)) {
2734 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
2735 GetSignatureForError ());
2739 if (TypeSpec.IsBaseClass (conv_type, declaring_type, false)) {
2740 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
2741 GetSignatureForError ());
2745 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
2746 if (first_arg_type != declaring_type || parameters.Types[1].BuiltinType != BuiltinTypeSpec.Type.Int) {
2747 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");
2750 } else if (parameters.Count == 1) {
2751 // Checks for Unary operators
2753 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
2754 if (return_type != declaring_type && !TypeSpec.IsBaseClass (return_type, declaring_type, false)) {
2755 Report.Error (448, Location,
2756 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
2759 if (first_arg_type != declaring_type) {
2761 559, Location, "The parameter type for ++ or -- operator must be the containing type");
2766 if (first_arg_type_unwrap != declaring_type) {
2767 Report.Error (562, Location,
2768 "The parameter type of a unary operator must be the containing type");
2772 if (OperatorType == OpType.True || OperatorType == OpType.False) {
2773 if (return_type.BuiltinType != BuiltinTypeSpec.Type.Bool) {
2776 "The return type of operator True or False " +
2782 } else if (first_arg_type_unwrap != declaring_type) {
2783 // Checks for Binary operators
2785 var second_arg_type = ParameterTypes[1];
2786 if (second_arg_type.IsNullableType)
2787 second_arg_type = Nullable.NullableInfo.GetUnderlyingType (second_arg_type);
2789 if (second_arg_type != declaring_type) {
2790 Report.Error (563, Location,
2791 "One of the parameters of a binary operator must be the containing type");
2799 protected override bool ResolveMemberType ()
2801 if (!base.ResolveMemberType ())
2804 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2808 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
2810 // Operator cannot be override
2811 bestCandidate = null;
2815 public static string GetName (OpType ot)
2817 return names [(int) ot] [0];
2820 public static string GetName (string metadata_name)
2822 for (int i = 0; i < names.Length; ++i) {
2823 if (names [i] [1] == metadata_name)
2824 return names [i] [0];
2829 public static string GetMetadataName (OpType ot)
2831 return names [(int) ot] [1];
2834 public static string GetMetadataName (string name)
2836 for (int i = 0; i < names.Length; ++i) {
2837 if (names [i] [0] == name)
2838 return names [i] [1];
2843 public static OpType? GetType (string metadata_name)
2845 for (int i = 0; i < names.Length; ++i) {
2846 if (names[i][1] == metadata_name)
2853 public OpType GetMatchingOperator ()
2855 switch (OperatorType) {
2856 case OpType.Equality:
2857 return OpType.Inequality;
2858 case OpType.Inequality:
2859 return OpType.Equality;
2861 return OpType.False;
2864 case OpType.GreaterThan:
2865 return OpType.LessThan;
2866 case OpType.LessThan:
2867 return OpType.GreaterThan;
2868 case OpType.GreaterThanOrEqual:
2869 return OpType.LessThanOrEqual;
2870 case OpType.LessThanOrEqual:
2871 return OpType.GreaterThanOrEqual;
2877 public override string GetSignatureForDocumentation ()
2879 string s = base.GetSignatureForDocumentation ();
2880 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2881 s = s + "~" + ReturnType.GetSignatureForDocumentation ();
2887 public override string GetSignatureForError ()
2889 StringBuilder sb = new StringBuilder ();
2890 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2891 sb.AppendFormat ("{0}.{1} operator {2}",
2892 Parent.GetSignatureForError (), GetName (OperatorType),
2893 member_type == null ? type_expr.GetSignatureForError () : member_type.GetSignatureForError ());
2896 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
2899 sb.Append (parameters.GetSignatureForError ());
2900 return sb.ToString ();