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);
447 public MethodSpec MakeGenericMethod (IMemberContext context, params TypeSpec[] targs)
450 throw new ArgumentNullException ();
452 // if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
455 //if (generic_intances == null)
456 // generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
458 var inflator = new TypeParameterInflator (context, DeclaringType, GenericDefinition.TypeParameters, targs);
460 var inflated = (MethodSpec) MemberwiseClone ();
461 inflated.declaringType = inflator.TypeInstance;
462 inflated.returnType = inflator.Inflate (returnType);
463 inflated.parameters = parameters.Inflate (inflator);
464 inflated.targs = targs;
465 inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
466 inflated.state |= StateFlags.PendingMakeMethod;
468 // if (inflated.parent == null)
469 // inflated.parent = parent;
471 //generic_intances.Add (targs, inflated);
475 public MethodSpec Mutate (TypeParameterMutator mutator)
477 var targs = TypeArguments;
479 targs = mutator.Mutate (targs);
481 var decl = DeclaringType;
482 if (DeclaringType.IsGenericOrParentIsGeneric) {
483 decl = mutator.Mutate (decl);
486 if (targs == TypeArguments && decl == DeclaringType)
489 var ms = (MethodSpec) MemberwiseClone ();
490 if (decl != DeclaringType) {
491 ms.inflatedMetaInfo = null;
492 ms.declaringType = decl;
493 ms.state |= StateFlags.PendingMetaInflate;
498 ms.state |= StateFlags.PendingMakeMethod;
504 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
506 var missing = returnType.ResolveMissingDependencies (this);
507 foreach (var pt in parameters.Types) {
508 var m = pt.GetMissingDependencies (this);
513 missing = new List<MissingTypeSpecReference> ();
515 missing.AddRange (m);
519 foreach (var tp in GenericDefinition.TypeParameters) {
520 var m = tp.GetMissingDependencies (this);
526 missing = new List<MissingTypeSpecReference> ();
528 missing.AddRange (m);
536 public abstract class MethodOrOperator : MethodCore, IMethodData, IMethodDefinition
538 ReturnParameter return_attributes;
539 SecurityType declarative_security;
540 protected MethodData MethodData;
542 static readonly string[] attribute_targets = new string [] { "method", "return" };
544 protected MethodOrOperator (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name,
545 Attributes attrs, ParametersCompiled parameters)
546 : base (parent, type, mod, allowed_mod, name, attrs, parameters)
550 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
552 if (a.Target == AttributeTargets.ReturnValue) {
553 if (return_attributes == null)
554 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
556 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
560 if (a.Type == pa.MethodImpl) {
561 if ((ModFlags & Modifiers.ASYNC) != 0 && (a.GetMethodImplOptions () & MethodImplOptions.Synchronized) != 0) {
562 Report.Error (4015, a.Location, "`{0}': Async methods cannot use `MethodImplOptions.Synchronized'",
563 GetSignatureForError ());
566 is_external_implementation = a.IsInternalCall ();
567 } else if (a.Type == pa.DllImport) {
568 const Modifiers extern_static = Modifiers.EXTERN | Modifiers.STATIC;
569 if ((ModFlags & extern_static) != extern_static) {
570 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
573 if (MemberName.IsGeneric || Parent.IsGenericOrParentIsGeneric) {
574 Report.Error (7042, a.Location,
575 "The DllImport attribute cannot be applied to a method that is generic or contained in a generic type");
578 is_external_implementation = true;
581 if (a.IsValidSecurityAttribute ()) {
582 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
586 if (MethodBuilder != null)
587 MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
590 public override AttributeTargets AttributeTargets {
592 return AttributeTargets.Method;
596 MethodBase IMethodDefinition.Metadata {
598 return MethodData.MethodBuilder;
602 // TODO: Remove and use MethodData abstraction
603 public MethodBuilder MethodBuilder {
605 return MethodData.MethodBuilder;
609 protected override bool CheckForDuplications ()
611 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
614 public virtual EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
616 return new EmitContext (this, ig, MemberType, sourceMethod);
619 public override bool Define ()
628 if (this is Operator)
629 kind = MemberKind.Operator;
630 else if (this is Destructor)
631 kind = MemberKind.Destructor;
633 kind = MemberKind.Method;
635 string explicit_name;
637 if (IsPartialDefinition) {
638 caching_flags &= ~Flags.Excluded_Undetected;
639 caching_flags |= Flags.Excluded;
641 // Add to member cache only when a partial method implementation has not been found yet
642 if ((caching_flags & Flags.PartialDefinitionExists) != 0)
648 explicit_name = null;
650 MethodData = new MethodData (this, ModFlags, flags, this, base_method);
652 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
655 explicit_name = MethodData.MetadataName;
658 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, parameters, ModFlags);
659 if (MemberName.Arity > 0)
660 spec.IsGeneric = true;
662 Parent.MemberCache.AddMember (this, explicit_name, spec);
667 protected override void DoMemberTypeIndependentChecks ()
669 base.DoMemberTypeIndependentChecks ();
671 CheckAbstractAndExtern (block != null);
673 if ((ModFlags & Modifiers.PARTIAL) != 0) {
674 for (int i = 0; i < parameters.Count; ++i) {
675 IParameterData p = parameters.FixedParameters [i];
676 if ((p.ModFlags & Parameter.Modifier.OUT) != 0) {
677 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
678 GetSignatureForError ());
681 if (p.HasDefaultValue && IsPartialImplementation)
682 ((Parameter) p).Warning_UselessOptionalParameter (Report);
687 protected override void DoMemberTypeDependentChecks ()
689 base.DoMemberTypeDependentChecks ();
691 if (MemberType.IsStatic) {
692 Error_StaticReturnType ();
696 public override void Emit ()
698 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
699 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (MethodBuilder);
700 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
701 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (MethodBuilder);
702 if ((ModFlags & Modifiers.DEBUGGER_STEP_THROUGH) != 0)
703 Module.PredefinedAttributes.DebuggerStepThrough.EmitAttribute (MethodBuilder);
705 if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
706 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
707 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
708 } else if (ReturnType.HasDynamicElement) {
709 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
710 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
713 if (OptAttributes != null)
714 OptAttributes.Emit ();
716 if (declarative_security != null) {
717 foreach (var de in declarative_security) {
719 MethodBuilder.__AddDeclarativeSecurity (de);
721 MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
727 // Optimization but it also covers cases where we cannot check
728 // constraints because method is captured into generated class
729 // and type parameters context is now different
731 if (type_expr != null && !IsCompilerGenerated)
732 ConstraintChecker.Check (this, member_type, type_expr.Location);
736 if (MethodData != null)
737 MethodData.Emit (Parent);
739 if (block != null && block.StateMachine is AsyncTaskStorey) {
740 var psm = Module.PredefinedAttributes.AsyncStateMachine;
741 psm.EmitAttribute (MethodBuilder, block.StateMachine);
744 if ((ModFlags & Modifiers.PARTIAL) == 0)
748 protected void Error_ConditionalAttributeIsNotValid ()
750 Report.Error (577, Location,
751 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
752 GetSignatureForError ());
755 public bool IsPartialDefinition {
757 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
761 public bool IsPartialImplementation {
763 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
767 public override string[] ValidAttributeTargets {
769 return attribute_targets;
773 #region IMethodData Members
775 bool IMethodData.IsAccessor {
781 public TypeSpec ReturnType {
787 public MemberName MethodName {
794 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
796 public override string[] ConditionalConditions ()
798 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
801 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
802 return new string [0];
804 caching_flags &= ~Flags.Excluded_Undetected;
807 if (base_method == null) {
808 if (OptAttributes == null)
811 Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
815 conditions = new string[attrs.Length];
816 for (int i = 0; i < conditions.Length; ++i)
817 conditions[i] = attrs[i].GetConditionalAttributeValue ();
819 conditions = base_method.MemberDefinition.ConditionalConditions();
822 if (conditions != null)
823 caching_flags |= Flags.Excluded;
830 public override void PrepareEmit ()
834 var mb = MethodData.DefineMethodBuilder (Parent);
836 if (CurrentTypeParameters != null) {
837 string[] gnames = new string[CurrentTypeParameters.Count];
838 for (int i = 0; i < gnames.Length; ++i) {
839 gnames[i] = CurrentTypeParameters[i].Name;
842 var gen_params = MethodBuilder.DefineGenericParameters (gnames);
844 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
845 var tp = CurrentTypeParameters[i];
847 tp.Define (gen_params[i]);
852 // Generic method has been already defined to resolve method parameters
853 // correctly when they use type parameters
855 mb.SetParameters (parameters.GetMetaInfo ());
856 mb.SetReturnType (ReturnType.GetMetaInfo ());
859 public override void WriteDebugSymbol (MonoSymbolFile file)
861 if (MethodData != null && !IsPartialDefinition)
862 MethodData.WriteDebugSymbol (file);
866 public class Method : MethodOrOperator, IGenericMethodDefinition
868 Method partialMethodImplementation;
870 public Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, MemberName name, ParametersCompiled parameters, Attributes attrs)
871 : base (parent, return_type, mod,
872 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
873 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct | Modifiers.ASYNC :
874 AllowedModifiersClass | Modifiers.ASYNC,
875 name, attrs, parameters)
879 protected Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
880 MemberName name, ParametersCompiled parameters, Attributes attrs)
881 : base (parent, return_type, mod, amod, name, attrs, parameters)
887 public override TypeParameters CurrentTypeParameters {
889 return MemberName.TypeParameters;
893 public TypeParameterSpec[] TypeParameters {
895 return CurrentTypeParameters.Types;
899 public int TypeParametersCount {
901 return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Count;
907 public override void Accept (StructuralVisitor visitor)
909 visitor.Visit (this);
912 public static Method Create (TypeDefinition parent, FullNamedExpression returnType, Modifiers mod,
913 MemberName name, ParametersCompiled parameters, Attributes attrs)
915 var m = new Method (parent, returnType, mod, name, parameters, attrs);
917 if ((mod & Modifiers.PARTIAL) != 0) {
918 const Modifiers invalid_partial_mod = Modifiers.AccessibilityMask | Modifiers.ABSTRACT | Modifiers.EXTERN |
919 Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.SEALED | Modifiers.VIRTUAL;
921 if ((mod & invalid_partial_mod) != 0) {
922 m.Report.Error (750, m.Location,
923 "A partial method cannot define access modifier or any of abstract, extern, new, override, sealed, or virtual modifiers");
924 mod &= ~invalid_partial_mod;
927 if ((parent.ModFlags & Modifiers.PARTIAL) == 0) {
928 m.Report.Error (751, m.Location,
929 "A partial method must be declared within a partial class or partial struct");
933 if ((mod & Modifiers.STATIC) == 0 && parameters.HasExtensionMethodType) {
934 m.Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static",
935 m.GetSignatureForError ());
942 public override string GetSignatureForError()
944 return base.GetSignatureForError () + parameters.GetSignatureForError ();
947 void Error_DuplicateEntryPoint (Method b)
949 Report.Error (17, b.Location,
950 "Program `{0}' has more than one entry point defined: `{1}'",
951 b.Module.Builder.ScopeName, b.GetSignatureForError ());
956 if (ReturnType.Kind != MemberKind.Void && ReturnType.BuiltinType != BuiltinTypeSpec.Type.Int)
959 if (parameters.IsEmpty)
962 if (parameters.Count > 1)
965 var ac = parameters.Types [0] as ArrayContainer;
966 return ac != null && ac.Rank == 1 && ac.Element.BuiltinType == BuiltinTypeSpec.Type.String &&
967 (parameters[0].ModFlags & Parameter.Modifier.RefOutMask) == 0;
970 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
973 var tp = CurrentTypeParameters;
975 TypeParameter t = tp.Find (name);
977 return new TypeParameterExpr (t, loc);
981 return base.LookupNamespaceOrType (name, arity, mode, loc);
984 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
986 if (a.Type == pa.Conditional) {
987 if (IsExplicitImpl) {
988 Error_ConditionalAttributeIsNotValid ();
992 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
993 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
997 if (ReturnType.Kind != MemberKind.Void) {
998 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
1003 Report.Error (582, Location, "Conditional not valid on interface members");
1007 if (MethodData.implementing != null) {
1008 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
1009 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
1010 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
1014 for (int i = 0; i < parameters.Count; ++i) {
1015 if ((parameters.FixedParameters [i].ModFlags & Parameter.Modifier.OUT) != 0) {
1016 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
1022 if (a.Type == pa.Extension) {
1023 a.Error_MisusedExtensionAttribute ();
1027 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1030 void CreateTypeParameters ()
1032 var tparams = MemberName.TypeParameters;
1033 var parent_tparams = Parent.TypeParametersAll;
1035 for (int i = 0; i < MemberName.Arity; i++) {
1036 string type_argument_name = tparams[i].MemberName.Name;
1038 if (block == null) {
1039 int idx = parameters.GetParameterIndexByName (type_argument_name);
1043 b = new ToplevelBlock (Compiler, Location);
1045 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
1048 INamedBlockVariable variable = null;
1049 block.GetLocalName (type_argument_name, block, ref variable);
1050 if (variable != null)
1051 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
1054 if (parent_tparams != null) {
1055 var tp = parent_tparams.Find (type_argument_name);
1057 tparams[i].WarningParentNameConflict (tp);
1062 tparams.Create (null, 0, Parent);
1065 protected virtual void DefineTypeParameters ()
1067 var tparams = CurrentTypeParameters;
1069 TypeParameterSpec[] base_tparams = null;
1070 TypeParameterSpec[] base_decl_tparams = TypeParameterSpec.EmptyTypes;
1071 TypeSpec[] base_targs = TypeSpec.EmptyTypes;
1072 if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
1073 MethodSpec base_override = base_method ?? MethodData.implementing;
1075 if (base_override != null) {
1076 base_tparams = base_override.GenericDefinition.TypeParameters;
1078 if (base_override.DeclaringType.IsGeneric) {
1079 base_decl_tparams = base_override.DeclaringType.MemberDefinition.TypeParameters;
1081 if (base_method != null) {
1082 var base_type_parent = CurrentType;
1083 while (base_type_parent.BaseType != base_override.DeclaringType) {
1084 base_type_parent = base_type_parent.BaseType;
1087 base_targs = base_type_parent.BaseType.TypeArguments;
1089 foreach (var iface in Parent.CurrentType.Interfaces) {
1090 if (iface == base_override.DeclaringType) {
1091 base_targs = iface.TypeArguments;
1098 if (base_override.IsGeneric) {
1099 foreach (var base_tp in base_tparams) {
1100 base_tp.BaseType.CheckObsoleteness (this, Location);
1102 if (base_tp.InterfacesDefined != null) {
1103 foreach (var iface in base_tp.InterfacesDefined) {
1104 iface.CheckObsoleteness (this, Location);
1109 if (base_decl_tparams.Length != 0) {
1110 base_decl_tparams = base_decl_tparams.Concat (base_tparams).ToArray ();
1111 base_targs = base_targs.Concat (tparams.Types).ToArray ();
1113 base_decl_tparams = base_tparams;
1114 base_targs = tparams.Types;
1120 for (int i = 0; i < tparams.Count; ++i) {
1121 var tp = tparams [i];
1123 if (base_tparams == null) {
1124 tp.ResolveConstraints (this);
1129 // Copy base constraints for override/explicit methods
1131 var base_tparam = base_tparams [i];
1132 var local_tparam = tp.Type;
1133 local_tparam.SpecialConstraint = base_tparam.SpecialConstraint;
1135 var inflator = new TypeParameterInflator (this, CurrentType, base_decl_tparams, base_targs);
1136 base_tparam.InflateConstraints (inflator, local_tparam);
1139 // Check all type argument constraints for possible collision or unification
1140 // introduced by inflating inherited constraints in this context
1142 // Conflict example:
1144 // class A<T> { virtual void Foo<U> () where U : class, T {} }
1145 // class B : A<int> { override void Foo<U> {} }
1147 var local_tparam_targs = local_tparam.TypeArguments;
1148 if (local_tparam_targs != null) {
1149 for (int ii = 0; ii < local_tparam_targs.Length; ++ii) {
1150 var ta = local_tparam_targs [ii];
1151 if (!ta.IsClass && !ta.IsStruct)
1154 TypeSpec[] unique_tparams = null;
1155 for (int iii = ii + 1; iii < local_tparam_targs.Length; ++iii) {
1157 // Remove any identical or unified constraint types
1159 var tparam_checked = local_tparam_targs [iii];
1160 if (TypeSpecComparer.IsEqual (ta, tparam_checked) || TypeSpec.IsBaseClass (ta, tparam_checked, false)) {
1161 unique_tparams = new TypeSpec[local_tparam_targs.Length - 1];
1162 Array.Copy (local_tparam_targs, 0, unique_tparams, 0, iii);
1163 Array.Copy (local_tparam_targs, iii + 1, unique_tparams, iii, local_tparam_targs.Length - iii - 1);
1164 } else if (!TypeSpec.IsBaseClass (tparam_checked, ta, false)) {
1165 Constraints.Error_ConflictingConstraints (this, local_tparam, ta, tparam_checked, Location);
1169 if (unique_tparams != null) {
1170 local_tparam_targs = unique_tparams;
1171 local_tparam.TypeArguments = local_tparam_targs;
1175 Constraints.CheckConflictingInheritedConstraint (local_tparam, ta, this, Location);
1180 if (base_tparams == null && MethodData != null && MethodData.implementing != null) {
1181 CheckImplementingMethodConstraints (Parent, spec, MethodData.implementing);
1185 public static bool CheckImplementingMethodConstraints (TypeContainer container, MethodSpec method, MethodSpec baseMethod)
1187 var tparams = method.Constraints;
1188 var base_tparams = baseMethod.Constraints;
1189 for (int i = 0; i < tparams.Length; ++i) {
1190 if (!tparams[i].HasSameConstraintsImplementation (base_tparams[i])) {
1191 container.Compiler.Report.SymbolRelatedToPreviousError (method);
1192 container.Compiler.Report.SymbolRelatedToPreviousError (baseMethod);
1194 // Using container location because the interface can be implemented
1196 var tp = (tparams [i].MemberDefinition as MemberCore) ?? container;
1197 container.Compiler.Report.Error (425, tp.Location,
1198 "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",
1199 tparams[i].GetSignatureForError (), method.GetSignatureForError (),
1200 base_tparams[i].GetSignatureForError (), baseMethod.GetSignatureForError ());
1212 public override bool Define ()
1214 if (!base.Define ())
1217 if (member_type.Kind == MemberKind.Void && parameters.IsEmpty && MemberName.Arity == 0 && MemberName.Name == Destructor.MetadataName) {
1218 Report.Warning (465, 1, Location,
1219 "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
1222 if (Compiler.Settings.StdLib && ReturnType.IsSpecialRuntimeType) {
1223 Error1599 (Location, ReturnType, Report);
1227 if (CurrentTypeParameters == null) {
1228 if (base_method != null && !IsExplicitImpl) {
1229 if (parameters.Count == 1 && ParameterTypes[0].BuiltinType == BuiltinTypeSpec.Type.Object && MemberName.Name == "Equals")
1230 Parent.PartialContainer.Mark_HasEquals ();
1231 else if (parameters.IsEmpty && MemberName.Name == "GetHashCode")
1232 Parent.PartialContainer.Mark_HasGetHashCode ();
1236 DefineTypeParameters ();
1239 if (block != null) {
1240 if (block.IsIterator) {
1242 // Current method is turned into automatically generated
1243 // wrapper which creates an instance of iterator
1245 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1246 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
1249 if ((ModFlags & Modifiers.ASYNC) != 0) {
1250 if (ReturnType.Kind != MemberKind.Void &&
1251 ReturnType != Module.PredefinedTypes.Task.TypeSpec &&
1252 !ReturnType.IsGenericTask) {
1253 Report.Error (1983, Location, "The return type of an async method must be void, Task, or Task<T>");
1256 block = (ToplevelBlock) block.ConvertToAsyncTask (this, Parent.PartialContainer, parameters, ReturnType, null, Location);
1257 ModFlags |= Modifiers.DEBUGGER_STEP_THROUGH;
1260 if (Compiler.Settings.WriteMetadataOnly)
1264 if ((ModFlags & Modifiers.STATIC) == 0)
1267 if (parameters.HasExtensionMethodType) {
1268 if (Parent.PartialContainer.IsStatic && !Parent.IsGenericOrParentIsGeneric) {
1269 if (!Parent.IsTopLevel)
1270 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
1271 GetSignatureForError ());
1273 PredefinedAttribute pa = Module.PredefinedAttributes.Extension;
1274 if (!pa.IsDefined) {
1275 Report.Error (1110, Location,
1276 "`{0}': Extension methods require `System.Runtime.CompilerServices.ExtensionAttribute' type to be available. Are you missing an assembly reference?",
1277 GetSignatureForError ());
1280 ModFlags |= Modifiers.METHOD_EXTENSION;
1281 Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
1282 Spec.DeclaringType.SetExtensionMethodContainer ();
1283 Parent.Module.HasExtensionMethod = true;
1285 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
1286 GetSignatureForError ());
1291 // This is used to track the Entry Point,
1293 var settings = Compiler.Settings;
1294 if (settings.NeedsEntryPoint && MemberName.Name == "Main" && !IsPartialDefinition && (settings.MainClass == null || settings.MainClass == Parent.TypeBuilder.FullName)) {
1295 if (IsEntryPoint ()) {
1296 if (Parent.DeclaringAssembly.EntryPoint == null) {
1297 if (Parent.IsGenericOrParentIsGeneric || MemberName.IsGeneric) {
1298 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
1299 GetSignatureForError ());
1300 } else if ((ModFlags & Modifiers.ASYNC) != 0) {
1301 Report.Error (4009, Location, "`{0}': an entry point cannot be async method",
1302 GetSignatureForError ());
1305 Parent.DeclaringAssembly.EntryPoint = this;
1308 Error_DuplicateEntryPoint (Parent.DeclaringAssembly.EntryPoint);
1309 Error_DuplicateEntryPoint (this);
1312 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
1313 GetSignatureForError ());
1320 public override void PrepareEmit ()
1322 if (IsPartialDefinition) {
1324 // Use partial method implementation builder for partial method declaration attributes
1326 if (partialMethodImplementation != null) {
1327 MethodData = partialMethodImplementation.MethodData;
1333 base.PrepareEmit ();
1339 public override void Emit ()
1342 if (IsPartialDefinition) {
1343 if (partialMethodImplementation != null && CurrentTypeParameters != null) {
1344 CurrentTypeParameters.CheckPartialConstraints (partialMethodImplementation);
1346 var otp = partialMethodImplementation.CurrentTypeParameters;
1347 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1348 var tp = CurrentTypeParameters [i];
1356 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
1357 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
1358 GetSignatureForError ());
1361 if (CurrentTypeParameters != null) {
1362 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1363 var tp = CurrentTypeParameters [i];
1365 tp.CheckGenericConstraints (false);
1370 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
1371 Module.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
1374 } catch (Exception e) {
1375 throw new InternalErrorException (this, e);
1379 public override bool EnableOverloadChecks (MemberCore overload)
1381 if (overload is Indexer)
1384 return base.EnableOverloadChecks (overload);
1387 public static void Error1599 (Location loc, TypeSpec t, Report Report)
1389 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", t.GetSignatureForError ());
1392 protected override bool ResolveMemberType ()
1394 if (CurrentTypeParameters != null) {
1395 CreateTypeParameters ();
1398 return base.ResolveMemberType ();
1401 public void SetPartialDefinition (Method methodDefinition)
1403 caching_flags |= Flags.PartialDefinitionExists;
1404 methodDefinition.partialMethodImplementation = this;
1406 // Ensure we are always using method declaration parameters
1407 for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
1408 var md_p = methodDefinition.parameters [i];
1409 var p = parameters [i];
1411 p.DefaultValue = md_p.DefaultValue;
1412 if (md_p.OptAttributes != null) {
1413 Attributes.AttachFromPartial (p, md_p);
1417 if (methodDefinition.attributes != null) {
1418 if (attributes == null) {
1419 attributes = methodDefinition.attributes;
1421 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
1425 if (CurrentTypeParameters != null) {
1426 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1427 var tp_other = methodDefinition.CurrentTypeParameters [i];
1428 if (tp_other.OptAttributes == null)
1431 var tp = CurrentTypeParameters [i];
1432 if (tp.OptAttributes == null) {
1433 tp.OptAttributes = tp_other.OptAttributes;
1435 tp.OptAttributes.Attrs.AddRange (tp.OptAttributes.Attrs);
1442 public abstract class ConstructorInitializer : ExpressionStatement
1444 Arguments argument_list;
1445 MethodSpec base_ctor;
1447 protected ConstructorInitializer (Arguments argument_list, Location loc)
1449 this.argument_list = argument_list;
1453 public Arguments Arguments {
1455 return argument_list;
1459 public override bool ContainsEmitWithAwait ()
1461 throw new NotSupportedException ();
1464 public override Expression CreateExpressionTree (ResolveContext ec)
1466 throw new NotSupportedException ("ET");
1469 protected override Expression DoResolve (ResolveContext ec)
1471 eclass = ExprClass.Value;
1474 var caller_builder = (Constructor) ec.MemberContext;
1477 // Spec mandates that constructor initializer will not have `this' access
1479 using (ec.Set (ResolveContext.Options.BaseInitializer)) {
1480 if (argument_list != null) {
1482 argument_list.Resolve (ec, out dynamic);
1485 ec.Report.Error (1975, loc,
1486 "The constructor call cannot be dynamically dispatched within constructor initializer");
1492 type = ec.CurrentType;
1493 if (this is ConstructorBaseInitializer) {
1494 if (ec.CurrentType.BaseType == null)
1497 type = ec.CurrentType.BaseType;
1498 if (ec.CurrentType.IsStruct) {
1499 ec.Report.Error (522, loc,
1500 "`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
1505 base_ctor = ConstructorLookup (ec, type, ref argument_list, loc);
1508 if (base_ctor != null && base_ctor.MemberDefinition == caller_builder.Spec.MemberDefinition) {
1509 ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
1510 caller_builder.GetSignatureForError ());
1516 public override void Emit (EmitContext ec)
1519 // It can be null for struct initializers or System.Object
1521 if (base_ctor == null) {
1522 if (type == ec.BuiltinTypes.Object)
1525 ec.Emit (OpCodes.Ldarg_0);
1526 ec.Emit (OpCodes.Initobj, type);
1530 var call = new CallEmitter ();
1531 call.InstanceExpression = new CompilerGeneratedThis (type, loc);
1532 call.EmitPredefined (ec, base_ctor, argument_list, false);
1535 public override void EmitStatement (EmitContext ec)
1540 public override void FlowAnalysis (FlowAnalysisContext fc)
1542 if (argument_list != null)
1543 argument_list.FlowAnalysis (fc);
1547 public class ConstructorBaseInitializer : ConstructorInitializer {
1548 public ConstructorBaseInitializer (Arguments argument_list, Location l) :
1549 base (argument_list, l)
1554 class GeneratedBaseInitializer: ConstructorBaseInitializer {
1555 public GeneratedBaseInitializer (Location loc, Arguments arguments)
1556 : base (arguments, loc)
1561 public class ConstructorThisInitializer : ConstructorInitializer {
1562 public ConstructorThisInitializer (Arguments argument_list, Location l) :
1563 base (argument_list, l)
1568 public class Constructor : MethodCore, IMethodData, IMethodDefinition
1570 public ConstructorBuilder ConstructorBuilder;
1571 public ConstructorInitializer Initializer;
1572 SecurityType declarative_security;
1573 bool has_compliant_args;
1574 SourceMethodBuilder debug_builder;
1577 // Modifiers allowed for a constructor.
1579 public const Modifiers AllowedModifiers =
1581 Modifiers.PROTECTED |
1582 Modifiers.INTERNAL |
1588 static readonly string[] attribute_targets = new string [] { "method" };
1590 public static readonly string ConstructorName = ".ctor";
1591 public static readonly string TypeConstructorName = ".cctor";
1593 public Constructor (TypeDefinition parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args, Location loc)
1594 : base (parent, null, mod, AllowedModifiers, new MemberName (name, loc), attrs, args)
1598 public bool HasCompliantArgs {
1600 return has_compliant_args;
1604 public override AttributeTargets AttributeTargets {
1606 return AttributeTargets.Constructor;
1610 bool IMethodData.IsAccessor {
1616 public bool IsPrimaryConstructor { get; set; }
1618 MethodBase IMethodDefinition.Metadata {
1620 return ConstructorBuilder;
1625 // Returns true if this is a default constructor
1627 public bool IsDefault ()
1629 if ((ModFlags & Modifiers.STATIC) != 0)
1630 return parameters.IsEmpty;
1632 return parameters.IsEmpty &&
1633 (Initializer is ConstructorBaseInitializer) &&
1634 (Initializer.Arguments == null);
1637 public override void Accept (StructuralVisitor visitor)
1639 visitor.Visit (this);
1642 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1644 if (a.IsValidSecurityAttribute ()) {
1645 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
1649 if (a.Type == pa.MethodImpl) {
1650 is_external_implementation = a.IsInternalCall ();
1653 ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1656 protected override bool CheckBase ()
1658 if ((ModFlags & Modifiers.STATIC) != 0) {
1659 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1660 Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1662 // the rest can be ignored
1666 // Check whether arguments were correct.
1667 if (!DefineParameters (parameters))
1670 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1671 Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1673 CheckProtectedModifier ();
1679 // Creates the ConstructorBuilder
1681 public override bool Define ()
1683 if (ConstructorBuilder != null)
1686 if (!CheckAbstractAndExtern (block != null))
1689 // Check if arguments were correct.
1693 if (Parent.PrimaryConstructorParameters != null && !IsPrimaryConstructor && !IsStatic) {
1694 if (Parent.Kind == MemberKind.Struct && Initializer is ConstructorThisInitializer && Initializer.Arguments == null) {
1695 Report.Error (8043, Location, "`{0}': Structs with primary constructor cannot specify default constructor initializer",
1696 GetSignatureForError ());
1697 } else if (Initializer == null || Initializer is ConstructorBaseInitializer) {
1698 Report.Error (8037, Location, "`{0}': Instance constructor of type with primary constructor must specify `this' constructor initializer",
1699 GetSignatureForError ());
1703 if ((ModFlags & Modifiers.EXTERN) != 0 && Initializer != null) {
1704 Report.Error (8091, Location, "`{0}': Contructors cannot be extern and have a constructor initializer",
1705 GetSignatureForError ());
1708 var ca = ModifiersExtensions.MethodAttr (ModFlags) | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
1710 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
1711 ca, CallingConventions,
1712 parameters.GetMetaInfo ());
1714 spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, Compiler.BuiltinTypes.Void, parameters, ModFlags);
1716 Parent.MemberCache.AddMember (spec);
1718 if (block != null) {
1719 // It's here only to report an error
1720 if (block.IsIterator) {
1721 member_type = Compiler.BuiltinTypes.Void;
1722 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1725 if (Compiler.Settings.WriteMetadataOnly)
1735 public override void Emit ()
1737 if (Parent.PartialContainer.IsComImport) {
1738 if (!IsDefault ()) {
1739 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
1740 Parent.GetSignatureForError ());
1743 // Set as internal implementation and reset block data
1744 // to ensure no IL is generated
1745 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
1749 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
1750 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (ConstructorBuilder);
1752 if (OptAttributes != null)
1753 OptAttributes.Emit ();
1756 parameters.ApplyAttributes (this, ConstructorBuilder);
1759 BlockContext bc = new BlockContext (this, block, Compiler.BuiltinTypes.Void);
1760 bc.Set (ResolveContext.Options.ConstructorScope);
1762 if (block != null) {
1763 if (!IsStatic && Initializer == null && Parent.PartialContainer.Kind == MemberKind.Struct) {
1765 // If this is a non-static `struct' constructor and doesn't have any
1766 // initializer, it must initialize all of the struct's fields.
1768 block.AddThisVariable (bc);
1772 // If we use a "this (...)" constructor initializer, then
1773 // do not emit field initializers, they are initialized in the other constructor
1775 if (!(Initializer is ConstructorThisInitializer)) {
1776 var errors = Compiler.Report.Errors;
1777 Parent.PartialContainer.ResolveFieldInitializers (bc);
1778 if (errors != Compiler.Report.Errors)
1783 if (Initializer == null && Parent.PartialContainer.Kind == MemberKind.Class) {
1784 Initializer = new GeneratedBaseInitializer (Location, null);
1787 if (Initializer != null) {
1789 // mdb format does not support reqions. Try to workaround this by emitting the
1790 // sequence point at initializer. Any breakpoint at constructor header should
1791 // be adjusted to this sequence point as it's the next one which follows.
1793 block.AddScopeStatement (new StatementExpression (Initializer));
1797 if (block.Resolve (bc, this)) {
1798 debug_builder = Parent.CreateMethodSymbolEntry ();
1799 EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType, debug_builder);
1800 ec.With (EmitContext.Options.ConstructorScope, true);
1806 if (declarative_security != null) {
1807 foreach (var de in declarative_security) {
1809 ConstructorBuilder.__AddDeclarativeSecurity (de);
1811 ConstructorBuilder.AddDeclarativeSecurity (de.Key, de.Value);
1819 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
1821 // Is never override
1822 bestCandidate = null;
1826 public override string GetCallerMemberName ()
1828 return IsStatic ? TypeConstructorName : ConstructorName;
1831 public override string GetSignatureForDocumentation ()
1833 return Parent.GetSignatureForDocumentation () + ".#ctor" + parameters.GetSignatureForDocumentation ();
1836 public override string GetSignatureForError()
1838 return base.GetSignatureForError () + parameters.GetSignatureForError ();
1841 public override string[] ValidAttributeTargets {
1843 return attribute_targets;
1847 protected override bool VerifyClsCompliance ()
1849 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
1853 if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
1854 foreach (TypeSpec param in parameters.Types) {
1855 if (param.IsArray) {
1861 has_compliant_args = true;
1865 public override void WriteDebugSymbol (MonoSymbolFile file)
1867 if (debug_builder == null)
1870 var token = ConstructorBuilder.GetToken ();
1871 int t = token.Token;
1873 if (ModuleBuilder.IsPseudoToken (t))
1874 t = Module.Builder.ResolvePseudoToken (t);
1877 debug_builder.DefineMethod (file, t);
1880 #region IMethodData Members
1882 public MemberName MethodName {
1888 public TypeSpec ReturnType {
1894 EmitContext IMethodData.CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
1896 throw new NotImplementedException ();
1903 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
1905 public interface IMethodData : IMemberContext
1907 CallingConventions CallingConventions { get; }
1908 Location Location { get; }
1909 MemberName MethodName { get; }
1910 TypeSpec ReturnType { get; }
1911 ParametersCompiled ParameterInfo { get; }
1912 MethodSpec Spec { get; }
1913 bool IsAccessor { get; }
1915 Attributes OptAttributes { get; }
1916 ToplevelBlock Block { get; set; }
1918 EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod);
1922 // Encapsulates most of the Method's state
1924 public class MethodData
1926 public readonly IMethodData method;
1929 // Are we implementing an interface ?
1931 public MethodSpec implementing;
1936 protected InterfaceMemberBase member;
1937 protected Modifiers modifiers;
1938 protected MethodAttributes flags;
1939 protected TypeSpec declaring_type;
1940 protected MethodSpec parent_method;
1941 SourceMethodBuilder debug_builder;
1944 MethodBuilder builder;
1945 public MethodBuilder MethodBuilder {
1951 public TypeSpec DeclaringType {
1953 return declaring_type;
1957 public string MetadataName {
1963 public MethodData (InterfaceMemberBase member,
1964 Modifiers modifiers, MethodAttributes flags, IMethodData method)
1966 this.member = member;
1967 this.modifiers = modifiers;
1970 this.method = method;
1973 public MethodData (InterfaceMemberBase member,
1974 Modifiers modifiers, MethodAttributes flags,
1976 MethodSpec parent_method)
1977 : this (member, modifiers, flags, method)
1979 this.parent_method = parent_method;
1982 public bool Define (TypeDefinition container, string method_full_name)
1984 PendingImplementation pending = container.PendingImplementations;
1985 MethodSpec ambig_iface_method;
1986 bool optional = false;
1988 if (pending != null) {
1989 implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this, out ambig_iface_method, ref optional);
1991 if (member.InterfaceType != null) {
1992 if (implementing == null) {
1993 if (member is PropertyBase) {
1994 container.Compiler.Report.Error (550, method.Location,
1995 "`{0}' is an accessor not found in interface member `{1}{2}'",
1996 method.GetSignatureForError (), member.InterfaceType.GetSignatureForError (),
1997 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
2000 container.Compiler.Report.Error (539, method.Location,
2001 "`{0}.{1}' in explicit interface declaration is not a member of interface",
2002 member.InterfaceType.GetSignatureForError (), member.ShortName);
2006 if (implementing.IsAccessor && !method.IsAccessor) {
2007 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2008 container.Compiler.Report.Error (683, method.Location,
2009 "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
2010 member.GetSignatureForError (), implementing.GetSignatureForError ());
2014 if (implementing != null && !optional) {
2015 if (!method.IsAccessor) {
2016 if (implementing.IsAccessor) {
2017 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2018 container.Compiler.Report.Error (470, method.Location,
2019 "Method `{0}' cannot implement interface accessor `{1}'",
2020 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
2022 } else if (implementing.DeclaringType.IsInterface) {
2023 if (!implementing.IsAccessor) {
2024 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2025 container.Compiler.Report.Error (686, method.Location,
2026 "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
2027 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
2029 PropertyBase.PropertyMethod pm = method as PropertyBase.PropertyMethod;
2030 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
2031 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2032 container.Compiler.Report.Error (277, method.Location,
2033 "Accessor `{0}' must be declared public to implement interface member `{1}'",
2034 method.GetSignatureForError (), implementing.GetSignatureForError ());
2041 ambig_iface_method = null;
2045 // For implicit implementations, make sure we are public, for
2046 // explicit implementations, make sure we are private.
2048 if (implementing != null){
2049 if (member.IsExplicitImpl) {
2050 if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
2051 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2052 container.Compiler.Report.Error (466, method.Location,
2053 "`{0}': the explicit interface implementation cannot introduce the params modifier",
2054 method.GetSignatureForError ());
2057 if (ambig_iface_method != null) {
2058 container.Compiler.Report.SymbolRelatedToPreviousError (ambig_iface_method);
2059 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2060 container.Compiler.Report.Warning (473, 2, method.Location,
2061 "Explicit interface implementation `{0}' matches more than one interface member. Consider using a non-explicit implementation instead",
2062 method.GetSignatureForError ());
2066 // Setting implementin to null inside this block will trigger a more
2067 // verbose error reporting for missing interface implementations
2069 if (implementing.DeclaringType.IsInterface) {
2071 // If this is an interface method implementation,
2072 // check for public accessibility
2074 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) {
2075 implementing = null;
2076 } else if (optional && (container.Interfaces == null || !container.Definition.Interfaces.Contains (implementing.DeclaringType))) {
2078 // We are not implementing interface when base class already implemented it
2080 implementing = null;
2082 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2083 // We may never be private.
2084 implementing = null;
2086 } else if ((modifiers & Modifiers.OVERRIDE) == 0) {
2088 // We may be protected if we're overriding something.
2090 implementing = null;
2095 // Static is not allowed
2097 if ((modifiers & Modifiers.STATIC) != 0){
2098 implementing = null;
2103 // If implementing is still valid, set flags
2105 if (implementing != null){
2107 // When implementing interface methods, set NewSlot
2108 // unless, we are overwriting a method.
2110 if ((modifiers & Modifiers.OVERRIDE) == 0 && implementing.DeclaringType.IsInterface) {
2111 flags |= MethodAttributes.NewSlot;
2114 flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;
2116 // Set Final unless we're virtual, abstract or already overriding a method.
2117 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
2118 flags |= MethodAttributes.Final;
2121 // clear the pending implementation flag (requires explicit methods to be defined first)
2123 pending.ImplementMethod (method.MethodName,
2124 member.InterfaceType, this, member.IsExplicitImpl, out ambig_iface_method, ref optional);
2127 // Update indexer accessor name to match implementing abstract accessor
2129 if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
2130 method_full_name = implementing.MemberDefinition.Name;
2133 full_name = method_full_name;
2134 declaring_type = container.Definition;
2139 void DefineOverride (TypeDefinition container)
2141 if (implementing == null)
2144 if (!member.IsExplicitImpl)
2147 container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
2151 // Creates partial MethodBuilder for the method when has generic parameters used
2152 // as arguments or return type
2154 public MethodBuilder DefineMethodBuilder (TypeDefinition container)
2156 if (builder != null)
2157 throw new InternalErrorException ();
2159 builder = container.TypeBuilder.DefineMethod (full_name, flags, method.CallingConventions);
2164 // Creates full MethodBuilder for the method
2166 public MethodBuilder DefineMethodBuilder (TypeDefinition container, ParametersCompiled param)
2168 DefineMethodBuilder (container);
2169 builder.SetReturnType (method.ReturnType.GetMetaInfo ());
2170 builder.SetParameters (param.GetMetaInfo ());
2177 public void Emit (TypeDefinition parent)
2179 DefineOverride (parent);
2181 method.ParameterInfo.ApplyAttributes (method, MethodBuilder);
2183 ToplevelBlock block = method.Block;
2184 if (block != null) {
2185 BlockContext bc = new BlockContext (method, block, method.ReturnType);
2186 if (block.Resolve (bc, method)) {
2187 debug_builder = member.Parent.CreateMethodSymbolEntry ();
2188 EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator (), debug_builder);
2195 public void WriteDebugSymbol (MonoSymbolFile file)
2197 if (debug_builder == null)
2200 var token = builder.GetToken ();
2201 int t = token.Token;
2203 if (ModuleBuilder.IsPseudoToken (t))
2204 t = member.Module.Builder.ResolvePseudoToken (t);
2207 debug_builder.DefineMethod (file, t);
2211 public class Destructor : MethodOrOperator
2213 const Modifiers AllowedModifiers =
2217 static readonly string[] attribute_targets = new string [] { "method" };
2219 public static readonly string MetadataName = "Finalize";
2221 public Destructor (TypeDefinition parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
2222 : base (parent, null, mod, AllowedModifiers, new MemberName (MetadataName, l), attrs, parameters)
2224 ModFlags &= ~Modifiers.PRIVATE;
2225 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
2228 public override void Accept (StructuralVisitor visitor)
2230 visitor.Visit (this);
2233 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2235 if (a.Type == pa.Conditional) {
2236 Error_ConditionalAttributeIsNotValid ();
2240 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2243 protected override bool CheckBase ()
2245 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2246 CheckForDuplications ();
2248 // Don't check base, destructors have special syntax
2252 public override bool Define ()
2256 if (Compiler.Settings.WriteMetadataOnly)
2262 public override void Emit()
2264 var base_type = Parent.PartialContainer.BaseType;
2265 if (base_type != null && Block != null) {
2266 var base_dtor = MemberCache.FindMember (base_type,
2267 new MemberFilter (MetadataName, 0, MemberKind.Destructor, null, null), BindingRestriction.InstanceOnly) as MethodSpec;
2269 if (base_dtor == null)
2270 throw new NotImplementedException ();
2272 MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
2273 method_expr.InstanceExpression = new BaseThis (base_type, Location);
2275 var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation) {
2276 IsCompilerGenerated = true
2278 var finaly_block = new ExplicitBlock (block, Location, Location) {
2279 IsCompilerGenerated = true
2283 // 0-size arguments to avoid CS0250 error
2284 // TODO: Should use AddScopeStatement or something else which emits correct
2287 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0)), Location.Null));
2289 var tf = new TryFinally (try_block, finaly_block, Location);
2290 block.WrapIntoDestructor (tf, try_block);
2296 public override string GetSignatureForError ()
2298 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
2301 protected override bool ResolveMemberType ()
2303 member_type = Compiler.BuiltinTypes.Void;
2307 public override string[] ValidAttributeTargets {
2309 return attribute_targets;
2314 // Ooouh Martin, templates are missing here.
2315 // When it will be possible move here a lot of child code and template method type.
2316 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData, IMethodDefinition {
2317 protected MethodData method_data;
2318 protected ToplevelBlock block;
2319 protected SecurityType declarative_security;
2321 protected readonly string prefix;
2323 ReturnParameter return_attributes;
2325 protected AbstractPropertyEventMethod (InterfaceMemberBase member, string prefix, Attributes attrs, Location loc)
2326 : base (member.Parent, SetupName (prefix, member, loc), attrs)
2328 this.prefix = prefix;
2331 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
2333 return new MemberName (member.MemberName.Left, prefix + member.ShortName, member.MemberName.ExplicitInterface, loc);
2336 public void UpdateName (InterfaceMemberBase member)
2338 SetMemberName (SetupName (prefix, member, Location));
2341 #region IMethodData Members
2343 public ToplevelBlock Block {
2353 public CallingConventions CallingConventions {
2355 return CallingConventions.Standard;
2359 public EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
2361 return new EmitContext (this, ig, ReturnType, sourceMethod);
2364 public bool IsAccessor {
2370 public MemberName MethodName {
2376 public TypeSpec[] ParameterTypes {
2378 return ParameterInfo.Types;
2382 MethodBase IMethodDefinition.Metadata {
2384 return method_data.MethodBuilder;
2388 public abstract ParametersCompiled ParameterInfo { get ; }
2389 public abstract TypeSpec ReturnType { get; }
2393 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2395 if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
2396 Report.Error (1667, a.Location,
2397 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
2398 a.Type.GetSignatureForError (), a.GetValidTargets ());
2402 if (a.IsValidSecurityAttribute ()) {
2403 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
2407 if (a.Target == AttributeTargets.Method) {
2408 method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
2412 if (a.Target == AttributeTargets.ReturnValue) {
2413 if (return_attributes == null)
2414 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2416 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
2420 ApplyToExtraTarget (a, ctor, cdata, pa);
2423 protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2425 throw new NotSupportedException ("You forgot to define special attribute target handling");
2428 // It is not supported for the accessors
2429 public sealed override bool Define()
2431 throw new NotSupportedException ();
2434 public virtual void Emit (TypeDefinition parent)
2436 method_data.Emit (parent);
2438 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
2439 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
2440 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
2441 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
2443 if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2444 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2445 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
2446 } else if (ReturnType.HasDynamicElement) {
2447 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2448 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
2451 if (OptAttributes != null)
2452 OptAttributes.Emit ();
2454 if (declarative_security != null) {
2455 foreach (var de in declarative_security) {
2457 method_data.MethodBuilder.__AddDeclarativeSecurity (de);
2459 method_data.MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2467 public override bool EnableOverloadChecks (MemberCore overload)
2469 if (overload is MethodCore) {
2470 caching_flags |= Flags.MethodOverloadsExist;
2474 // This can only happen with indexers and it will
2475 // be catched as indexer difference
2476 if (overload is AbstractPropertyEventMethod)
2482 public override string GetCallerMemberName ()
2484 return base.GetCallerMemberName ().Substring (prefix.Length);
2487 public override string GetSignatureForDocumentation ()
2489 // should not be called
2490 throw new NotSupportedException ();
2493 public override bool IsClsComplianceRequired()
2498 public void PrepareEmit ()
2500 method_data.DefineMethodBuilder (Parent.PartialContainer, ParameterInfo);
2503 public override void WriteDebugSymbol (MonoSymbolFile file)
2505 if (method_data != null)
2506 method_data.WriteDebugSymbol (file);
2509 public MethodSpec Spec { get; protected set; }
2512 // Represents header string for documentation comment.
2514 public override string DocCommentHeader {
2515 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
2519 public class Operator : MethodOrOperator {
2521 const Modifiers AllowedModifiers =
2527 public enum OpType : byte {
2537 // Unary and Binary operators
2560 // Implicit and Explicit
2567 // Just because of enum
2571 public readonly OpType OperatorType;
2573 static readonly string [] [] names;
2577 names = new string[(int)OpType.TOP][];
2578 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
2579 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
2580 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
2581 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
2582 names [(int) OpType.True] = new string [] { "true", "op_True" };
2583 names [(int) OpType.False] = new string [] { "false", "op_False" };
2584 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
2585 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
2586 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
2587 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
2588 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
2589 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
2590 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
2591 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
2592 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
2593 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
2594 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
2595 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
2596 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
2597 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
2598 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
2599 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
2600 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
2601 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
2602 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
2603 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
2604 names [(int) OpType.Is] = new string[] { "is", "op_Is" };
2607 public Operator (TypeDefinition parent, OpType type, FullNamedExpression ret_type, Modifiers mod_flags, ParametersCompiled parameters,
2608 ToplevelBlock block, Attributes attrs, Location loc)
2609 : base (parent, ret_type, mod_flags, AllowedModifiers, new MemberName (GetMetadataName (type), loc), attrs, parameters)
2611 OperatorType = type;
2615 public override void Accept (StructuralVisitor visitor)
2617 visitor.Visit (this);
2620 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2622 if (a.Type == pa.Conditional) {
2623 Error_ConditionalAttributeIsNotValid ();
2627 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2630 public override bool Define ()
2632 const Modifiers RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
2633 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
2634 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
2637 if (!base.Define ())
2640 if (block != null) {
2641 if (block.IsIterator) {
2643 // Current method is turned into automatically generated
2644 // wrapper which creates an instance of iterator
2646 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
2647 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
2650 if (Compiler.Settings.WriteMetadataOnly)
2654 // imlicit and explicit operator of same types are not allowed
2655 if (OperatorType == OpType.Explicit)
2656 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
2657 else if (OperatorType == OpType.Implicit)
2658 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
2660 TypeSpec declaring_type = Parent.PartialContainer.CurrentType;
2661 TypeSpec return_type = MemberType;
2662 TypeSpec first_arg_type = ParameterTypes [0];
2664 TypeSpec first_arg_type_unwrap = first_arg_type;
2665 if (first_arg_type.IsNullableType)
2666 first_arg_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (first_arg_type);
2668 TypeSpec return_type_unwrap = return_type;
2669 if (return_type.IsNullableType)
2670 return_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (return_type);
2673 // Rules for conversion operators
2675 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2676 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type) {
2677 Report.Error (555, Location,
2678 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
2683 if (declaring_type == return_type || declaring_type == return_type_unwrap) {
2684 conv_type = first_arg_type;
2685 } else if (declaring_type == first_arg_type || declaring_type == first_arg_type_unwrap) {
2686 conv_type = return_type;
2688 Report.Error (556, Location,
2689 "User-defined conversion must convert to or from the enclosing type");
2693 if (conv_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2694 Report.Error (1964, Location,
2695 "User-defined conversion `{0}' cannot convert to or from the dynamic type",
2696 GetSignatureForError ());
2701 if (conv_type.IsInterface) {
2702 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
2703 GetSignatureForError ());
2707 if (conv_type.IsClass) {
2708 if (TypeSpec.IsBaseClass (declaring_type, conv_type, true)) {
2709 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
2710 GetSignatureForError ());
2714 if (TypeSpec.IsBaseClass (conv_type, declaring_type, false)) {
2715 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
2716 GetSignatureForError ());
2720 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
2721 if (first_arg_type != declaring_type || parameters.Types[1].BuiltinType != BuiltinTypeSpec.Type.Int) {
2722 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");
2725 } else if (parameters.Count == 1) {
2726 // Checks for Unary operators
2728 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
2729 if (return_type != declaring_type && !TypeSpec.IsBaseClass (return_type, declaring_type, false)) {
2730 Report.Error (448, Location,
2731 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
2734 if (first_arg_type != declaring_type) {
2736 559, Location, "The parameter type for ++ or -- operator must be the containing type");
2741 if (first_arg_type_unwrap != declaring_type) {
2742 Report.Error (562, Location,
2743 "The parameter type of a unary operator must be the containing type");
2747 if (OperatorType == OpType.True || OperatorType == OpType.False) {
2748 if (return_type.BuiltinType != BuiltinTypeSpec.Type.Bool) {
2751 "The return type of operator True or False " +
2757 } else if (first_arg_type_unwrap != declaring_type) {
2758 // Checks for Binary operators
2760 var second_arg_type = ParameterTypes[1];
2761 if (second_arg_type.IsNullableType)
2762 second_arg_type = Nullable.NullableInfo.GetUnderlyingType (second_arg_type);
2764 if (second_arg_type != declaring_type) {
2765 Report.Error (563, Location,
2766 "One of the parameters of a binary operator must be the containing type");
2774 protected override bool ResolveMemberType ()
2776 if (!base.ResolveMemberType ())
2779 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2783 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
2785 // Operator cannot be override
2786 bestCandidate = null;
2790 public static string GetName (OpType ot)
2792 return names [(int) ot] [0];
2795 public static string GetName (string metadata_name)
2797 for (int i = 0; i < names.Length; ++i) {
2798 if (names [i] [1] == metadata_name)
2799 return names [i] [0];
2804 public static string GetMetadataName (OpType ot)
2806 return names [(int) ot] [1];
2809 public static string GetMetadataName (string name)
2811 for (int i = 0; i < names.Length; ++i) {
2812 if (names [i] [0] == name)
2813 return names [i] [1];
2818 public static OpType? GetType (string metadata_name)
2820 for (int i = 0; i < names.Length; ++i) {
2821 if (names[i][1] == metadata_name)
2828 public OpType GetMatchingOperator ()
2830 switch (OperatorType) {
2831 case OpType.Equality:
2832 return OpType.Inequality;
2833 case OpType.Inequality:
2834 return OpType.Equality;
2836 return OpType.False;
2839 case OpType.GreaterThan:
2840 return OpType.LessThan;
2841 case OpType.LessThan:
2842 return OpType.GreaterThan;
2843 case OpType.GreaterThanOrEqual:
2844 return OpType.LessThanOrEqual;
2845 case OpType.LessThanOrEqual:
2846 return OpType.GreaterThanOrEqual;
2852 public override string GetSignatureForDocumentation ()
2854 string s = base.GetSignatureForDocumentation ();
2855 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2856 s = s + "~" + ReturnType.GetSignatureForDocumentation ();
2862 public override string GetSignatureForError ()
2864 StringBuilder sb = new StringBuilder ();
2865 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2866 sb.AppendFormat ("{0}.{1} operator {2}",
2867 Parent.GetSignatureForError (), GetName (OperatorType),
2868 member_type == null ? type_expr.GetSignatureForError () : member_type.GetSignatureForError ());
2871 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
2874 sb.Append (parameters.GetSignatureForError ());
2875 return sb.ToString ();