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 virtual void PrepareEmit ()
170 parameters.ResolveDefaultValues (this);
173 public MethodSpec Spec {
177 protected override bool VerifyClsCompliance ()
179 if (!base.VerifyClsCompliance ())
182 if (parameters.HasArglist) {
183 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
186 if (member_type != null && !member_type.IsCLSCompliant ()) {
187 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
188 GetSignatureForError ());
191 parameters.VerifyClsCompliance (this);
196 public interface IGenericMethodDefinition : IMethodDefinition
198 TypeParameterSpec[] TypeParameters { get; }
199 int TypeParametersCount { get; }
201 // MethodInfo MakeGenericMethod (TypeSpec[] targs);
204 public sealed class MethodSpec : MemberSpec, IParametersMember
206 MethodBase inflatedMetaInfo;
207 AParametersCollection parameters;
211 TypeParameterSpec[] constraints;
213 public static readonly MethodSpec Excluded = new MethodSpec (MemberKind.Method, InternalType.FakeInternalType, null, null, ParametersCompiled.EmptyReadOnlyParameters, 0);
215 public MethodSpec (MemberKind kind, TypeSpec declaringType, IMethodDefinition details, TypeSpec returnType,
216 AParametersCollection parameters, Modifiers modifiers)
217 : base (kind, declaringType, details, modifiers)
219 this.parameters = parameters;
220 this.returnType = returnType;
225 public override int Arity {
227 return IsGeneric ? GenericDefinition.TypeParametersCount : 0;
231 public TypeParameterSpec[] Constraints {
233 if (constraints == null && IsGeneric)
234 constraints = GenericDefinition.TypeParameters;
240 public bool IsConstructor {
242 return Kind == MemberKind.Constructor;
246 public new IMethodDefinition MemberDefinition {
248 return (IMethodDefinition) definition;
252 public IGenericMethodDefinition GenericDefinition {
254 return (IGenericMethodDefinition) definition;
258 public bool IsAsync {
260 return (Modifiers & Modifiers.ASYNC) != 0;
264 public bool IsExtensionMethod {
266 return IsStatic && parameters.HasExtensionMethodType;
270 public bool IsSealed {
272 return (Modifiers & Modifiers.SEALED) != 0;
276 // When is virtual or abstract
277 public bool IsVirtual {
279 return (Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) != 0;
283 public bool IsReservedMethod {
285 return Kind == MemberKind.Operator || IsAccessor;
289 TypeSpec IInterfaceMemberSpec.MemberType {
295 public AParametersCollection Parameters {
301 public TypeSpec ReturnType {
307 public TypeSpec[] TypeArguments {
315 public MethodSpec GetGenericMethodDefinition ()
317 if (!IsGeneric && !DeclaringType.IsGeneric)
320 return MemberCache.GetMember (declaringType, this);
323 public MethodBase GetMetaInfo ()
326 // inflatedMetaInfo is extra field needed for cases where we
327 // inflate method but another nested type can later inflate
328 // again (the cache would be build with inflated metaInfo) and
329 // TypeBuilder can work with method definitions only
331 if (inflatedMetaInfo == null) {
332 if ((state & StateFlags.PendingMetaInflate) != 0) {
333 var dt_meta = DeclaringType.GetMetaInfo ();
335 if (DeclaringType.IsTypeBuilder) {
337 inflatedMetaInfo = TypeBuilder.GetConstructor (dt_meta, (ConstructorInfo) MemberDefinition.Metadata);
339 inflatedMetaInfo = TypeBuilder.GetMethod (dt_meta, (MethodInfo) MemberDefinition.Metadata);
342 // it should not be reached
343 throw new NotImplementedException ();
345 inflatedMetaInfo = MethodInfo.GetMethodFromHandle (MemberDefinition.Metadata.MethodHandle, dt_meta.TypeHandle);
349 state &= ~StateFlags.PendingMetaInflate;
351 inflatedMetaInfo = MemberDefinition.Metadata;
355 if ((state & StateFlags.PendingMakeMethod) != 0) {
356 var sre_targs = new MetaType[targs.Length];
357 for (int i = 0; i < sre_targs.Length; ++i)
358 sre_targs[i] = targs[i].GetMetaInfo ();
360 inflatedMetaInfo = ((MethodInfo) inflatedMetaInfo).MakeGenericMethod (sre_targs);
361 state &= ~StateFlags.PendingMakeMethod;
364 return inflatedMetaInfo;
367 public override string GetSignatureForDocumentation ()
371 case MemberKind.Constructor:
374 case MemberKind.Method:
376 name = Name + "``" + Arity.ToString ();
386 name = DeclaringType.GetSignatureForDocumentation () + "." + name + parameters.GetSignatureForDocumentation ();
387 if (Kind == MemberKind.Operator) {
388 var op = Operator.GetType (Name).Value;
389 if (op == Operator.OpType.Explicit || op == Operator.OpType.Implicit) {
390 name += "~" + ReturnType.GetSignatureForDocumentation ();
397 public override string GetSignatureForError ()
401 name = DeclaringType.GetSignatureForError () + "." + DeclaringType.Name;
402 } else if (Kind == MemberKind.Operator) {
403 var op = Operator.GetType (Name).Value;
404 if (op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) {
405 name = DeclaringType.GetSignatureForError () + "." + Operator.GetName (op) + " operator " + returnType.GetSignatureForError ();
407 name = DeclaringType.GetSignatureForError () + ".operator " + Operator.GetName (op);
409 } else if (IsAccessor) {
410 int split = Name.IndexOf ('_');
411 name = Name.Substring (split + 1);
412 var postfix = Name.Substring (0, split);
414 var pc = parameters.Count;
415 if (pc > 0 && postfix == "get") {
416 name = "this" + parameters.GetSignatureForError ("[", "]", pc);
417 } else if (pc > 1 && postfix == "set") {
418 name = "this" + parameters.GetSignatureForError ("[", "]", pc - 1);
422 return DeclaringType.GetSignatureForError () + "." + name + "." + postfix;
424 name = base.GetSignatureForError ();
426 name += "<" + TypeManager.CSharpName (targs) + ">";
428 name += "<" + TypeManager.CSharpName (GenericDefinition.TypeParameters) + ">";
431 return name + parameters.GetSignatureForError ();
434 public override MemberSpec InflateMember (TypeParameterInflator inflator)
436 var ms = (MethodSpec) base.InflateMember (inflator);
437 ms.inflatedMetaInfo = null;
438 ms.returnType = inflator.Inflate (returnType);
439 ms.parameters = parameters.Inflate (inflator);
441 ms.constraints = TypeParameterSpec.InflateConstraints (inflator, Constraints);
446 public MethodSpec MakeGenericMethod (IMemberContext context, params TypeSpec[] targs)
449 throw new ArgumentNullException ();
451 // if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
454 //if (generic_intances == null)
455 // generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
457 var inflator = new TypeParameterInflator (context, DeclaringType, GenericDefinition.TypeParameters, targs);
459 var inflated = (MethodSpec) MemberwiseClone ();
460 inflated.declaringType = inflator.TypeInstance;
461 inflated.returnType = inflator.Inflate (returnType);
462 inflated.parameters = parameters.Inflate (inflator);
463 inflated.targs = targs;
464 inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
465 inflated.state |= StateFlags.PendingMakeMethod;
467 // if (inflated.parent == null)
468 // inflated.parent = parent;
470 //generic_intances.Add (targs, inflated);
474 public MethodSpec Mutate (TypeParameterMutator mutator)
476 var targs = TypeArguments;
478 targs = mutator.Mutate (targs);
480 var decl = DeclaringType;
481 if (DeclaringType.IsGenericOrParentIsGeneric) {
482 decl = mutator.Mutate (decl);
485 if (targs == TypeArguments && decl == DeclaringType)
488 var ms = (MethodSpec) MemberwiseClone ();
489 if (decl != DeclaringType) {
490 ms.inflatedMetaInfo = null;
491 ms.declaringType = decl;
492 ms.state |= StateFlags.PendingMetaInflate;
497 ms.state |= StateFlags.PendingMakeMethod;
503 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
505 var missing = returnType.ResolveMissingDependencies (this);
506 foreach (var pt in parameters.Types) {
507 var m = pt.GetMissingDependencies (this);
512 missing = new List<MissingTypeSpecReference> ();
514 missing.AddRange (m);
518 foreach (var tp in GenericDefinition.TypeParameters) {
519 var m = tp.GetMissingDependencies (this);
525 missing = new List<MissingTypeSpecReference> ();
527 missing.AddRange (m);
535 public abstract class MethodOrOperator : MethodCore, IMethodData, IMethodDefinition
537 ReturnParameter return_attributes;
538 SecurityType declarative_security;
539 protected MethodData MethodData;
541 static readonly string[] attribute_targets = new string [] { "method", "return" };
543 protected MethodOrOperator (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name,
544 Attributes attrs, ParametersCompiled parameters)
545 : base (parent, type, mod, allowed_mod, name, attrs, parameters)
549 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
551 if (a.Target == AttributeTargets.ReturnValue) {
552 if (return_attributes == null)
553 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
555 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
559 if (a.Type == pa.MethodImpl) {
560 if ((ModFlags & Modifiers.ASYNC) != 0 && (a.GetMethodImplOptions () & MethodImplOptions.Synchronized) != 0) {
561 Report.Error (4015, a.Location, "`{0}': Async methods cannot use `MethodImplOptions.Synchronized'",
562 GetSignatureForError ());
565 is_external_implementation = a.IsInternalCall ();
566 } else if (a.Type == pa.DllImport) {
567 const Modifiers extern_static = Modifiers.EXTERN | Modifiers.STATIC;
568 if ((ModFlags & extern_static) != extern_static) {
569 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
572 if (MemberName.IsGeneric || Parent.IsGenericOrParentIsGeneric) {
573 Report.Error (7042, a.Location,
574 "The DllImport attribute cannot be applied to a method that is generic or contained in a generic type");
577 is_external_implementation = true;
580 if (a.IsValidSecurityAttribute ()) {
581 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
585 if (MethodBuilder != null)
586 MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
589 public override AttributeTargets AttributeTargets {
591 return AttributeTargets.Method;
595 MethodBase IMethodDefinition.Metadata {
597 return MethodData.MethodBuilder;
601 // TODO: Remove and use MethodData abstraction
602 public MethodBuilder MethodBuilder {
604 return MethodData.MethodBuilder;
608 protected override bool CheckForDuplications ()
610 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
613 public virtual EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
615 return new EmitContext (this, ig, MemberType, sourceMethod);
618 public override bool Define ()
627 if (this is Operator)
628 kind = MemberKind.Operator;
629 else if (this is Destructor)
630 kind = MemberKind.Destructor;
632 kind = MemberKind.Method;
634 string explicit_name;
636 if (IsPartialDefinition) {
637 caching_flags &= ~Flags.Excluded_Undetected;
638 caching_flags |= Flags.Excluded;
640 // Add to member cache only when a partial method implementation has not been found yet
641 if ((caching_flags & Flags.PartialDefinitionExists) != 0)
647 explicit_name = null;
649 MethodData = new MethodData (this, ModFlags, flags, this, base_method);
651 if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
654 explicit_name = MethodData.MetadataName;
657 spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, parameters, ModFlags);
658 if (MemberName.Arity > 0)
659 spec.IsGeneric = true;
661 Parent.MemberCache.AddMember (this, explicit_name, spec);
666 protected override void DoMemberTypeIndependentChecks ()
668 base.DoMemberTypeIndependentChecks ();
670 CheckAbstractAndExtern (block != null);
672 if ((ModFlags & Modifiers.PARTIAL) != 0) {
673 for (int i = 0; i < parameters.Count; ++i) {
674 IParameterData p = parameters.FixedParameters [i];
675 if ((p.ModFlags & Parameter.Modifier.OUT) != 0) {
676 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
677 GetSignatureForError ());
680 if (p.HasDefaultValue && IsPartialImplementation)
681 ((Parameter) p).Warning_UselessOptionalParameter (Report);
686 protected override void DoMemberTypeDependentChecks ()
688 base.DoMemberTypeDependentChecks ();
690 if (MemberType.IsStatic) {
691 Error_StaticReturnType ();
695 public override void Emit ()
697 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
698 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (MethodBuilder);
699 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
700 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (MethodBuilder);
701 if ((ModFlags & Modifiers.DEBUGGER_STEP_THROUGH) != 0)
702 Module.PredefinedAttributes.DebuggerStepThrough.EmitAttribute (MethodBuilder);
704 if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
705 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
706 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
707 } else if (ReturnType.HasDynamicElement) {
708 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
709 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
712 if (OptAttributes != null)
713 OptAttributes.Emit ();
715 if (declarative_security != null) {
716 foreach (var de in declarative_security) {
718 MethodBuilder.__AddDeclarativeSecurity (de);
720 MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
725 if (type_expr != null)
726 ConstraintChecker.Check (this, member_type, type_expr.Location);
730 if (MethodData != null)
731 MethodData.Emit (Parent);
733 if (block != null && block.StateMachine is AsyncTaskStorey) {
734 var psm = Module.PredefinedAttributes.AsyncStateMachine;
735 psm.EmitAttribute (MethodBuilder, block.StateMachine);
738 if ((ModFlags & Modifiers.PARTIAL) == 0)
742 protected void Error_ConditionalAttributeIsNotValid ()
744 Report.Error (577, Location,
745 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
746 GetSignatureForError ());
749 public bool IsPartialDefinition {
751 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
755 public bool IsPartialImplementation {
757 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
761 public override string[] ValidAttributeTargets {
763 return attribute_targets;
767 #region IMethodData Members
769 bool IMethodData.IsAccessor {
775 public TypeSpec ReturnType {
781 public MemberName MethodName {
788 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
790 public override string[] ConditionalConditions ()
792 if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
795 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
796 return new string [0];
798 caching_flags &= ~Flags.Excluded_Undetected;
801 if (base_method == null) {
802 if (OptAttributes == null)
805 Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
809 conditions = new string[attrs.Length];
810 for (int i = 0; i < conditions.Length; ++i)
811 conditions[i] = attrs[i].GetConditionalAttributeValue ();
813 conditions = base_method.MemberDefinition.ConditionalConditions();
816 if (conditions != null)
817 caching_flags |= Flags.Excluded;
824 public override void PrepareEmit ()
828 var mb = MethodData.DefineMethodBuilder (Parent);
830 if (CurrentTypeParameters != null) {
831 string[] gnames = new string[CurrentTypeParameters.Count];
832 for (int i = 0; i < gnames.Length; ++i) {
833 gnames[i] = CurrentTypeParameters[i].Name;
836 var gen_params = MethodBuilder.DefineGenericParameters (gnames);
838 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
839 var tp = CurrentTypeParameters[i];
841 tp.Define (gen_params[i]);
846 // Generic method has been already defined to resolve method parameters
847 // correctly when they use type parameters
849 mb.SetParameters (parameters.GetMetaInfo ());
850 mb.SetReturnType (ReturnType.GetMetaInfo ());
853 public override void WriteDebugSymbol (MonoSymbolFile file)
855 if (MethodData != null && !IsPartialDefinition)
856 MethodData.WriteDebugSymbol (file);
860 public class Method : MethodOrOperator, IGenericMethodDefinition
862 Method partialMethodImplementation;
864 public Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, MemberName name, ParametersCompiled parameters, Attributes attrs)
865 : base (parent, return_type, mod,
866 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
867 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct | Modifiers.ASYNC :
868 AllowedModifiersClass | Modifiers.ASYNC,
869 name, attrs, parameters)
873 protected Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
874 MemberName name, ParametersCompiled parameters, Attributes attrs)
875 : base (parent, return_type, mod, amod, name, attrs, parameters)
881 public override TypeParameters CurrentTypeParameters {
883 return MemberName.TypeParameters;
887 public TypeParameterSpec[] TypeParameters {
889 return CurrentTypeParameters.Types;
893 public int TypeParametersCount {
895 return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Count;
901 public override void Accept (StructuralVisitor visitor)
903 visitor.Visit (this);
906 public static Method Create (TypeDefinition parent, FullNamedExpression returnType, Modifiers mod,
907 MemberName name, ParametersCompiled parameters, Attributes attrs)
909 var m = new Method (parent, returnType, mod, name, parameters, attrs);
911 if ((mod & Modifiers.PARTIAL) != 0) {
912 const Modifiers invalid_partial_mod = Modifiers.AccessibilityMask | Modifiers.ABSTRACT | Modifiers.EXTERN |
913 Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.SEALED | Modifiers.VIRTUAL;
915 if ((mod & invalid_partial_mod) != 0) {
916 m.Report.Error (750, m.Location,
917 "A partial method cannot define access modifier or any of abstract, extern, new, override, sealed, or virtual modifiers");
918 mod &= ~invalid_partial_mod;
921 if ((parent.ModFlags & Modifiers.PARTIAL) == 0) {
922 m.Report.Error (751, m.Location,
923 "A partial method must be declared within a partial class or partial struct");
927 if ((mod & Modifiers.STATIC) == 0 && parameters.HasExtensionMethodType) {
928 m.Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static",
929 m.GetSignatureForError ());
936 public override string GetSignatureForError()
938 return base.GetSignatureForError () + parameters.GetSignatureForError ();
941 void Error_DuplicateEntryPoint (Method b)
943 Report.Error (17, b.Location,
944 "Program `{0}' has more than one entry point defined: `{1}'",
945 b.Module.Builder.ScopeName, b.GetSignatureForError ());
950 if (ReturnType.Kind != MemberKind.Void && ReturnType.BuiltinType != BuiltinTypeSpec.Type.Int)
953 if (parameters.IsEmpty)
956 if (parameters.Count > 1)
959 var ac = parameters.Types [0] as ArrayContainer;
960 return ac != null && ac.Rank == 1 && ac.Element.BuiltinType == BuiltinTypeSpec.Type.String &&
961 (parameters[0].ModFlags & Parameter.Modifier.RefOutMask) == 0;
964 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
967 var tp = CurrentTypeParameters;
969 TypeParameter t = tp.Find (name);
971 return new TypeParameterExpr (t, loc);
975 return base.LookupNamespaceOrType (name, arity, mode, loc);
978 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
980 if (a.Type == pa.Conditional) {
981 if (IsExplicitImpl) {
982 Error_ConditionalAttributeIsNotValid ();
986 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
987 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
991 if (ReturnType.Kind != MemberKind.Void) {
992 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
997 Report.Error (582, Location, "Conditional not valid on interface members");
1001 if (MethodData.implementing != null) {
1002 Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
1003 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
1004 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
1008 for (int i = 0; i < parameters.Count; ++i) {
1009 if ((parameters.FixedParameters [i].ModFlags & Parameter.Modifier.OUT) != 0) {
1010 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
1016 if (a.Type == pa.Extension) {
1017 a.Error_MisusedExtensionAttribute ();
1021 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1024 void CreateTypeParameters ()
1026 var tparams = MemberName.TypeParameters;
1027 var parent_tparams = Parent.TypeParametersAll;
1029 for (int i = 0; i < MemberName.Arity; i++) {
1030 string type_argument_name = tparams[i].MemberName.Name;
1032 if (block == null) {
1033 int idx = parameters.GetParameterIndexByName (type_argument_name);
1037 b = new ToplevelBlock (Compiler, Location);
1039 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
1042 INamedBlockVariable variable = null;
1043 block.GetLocalName (type_argument_name, block, ref variable);
1044 if (variable != null)
1045 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
1048 if (parent_tparams != null) {
1049 var tp = parent_tparams.Find (type_argument_name);
1051 tparams[i].WarningParentNameConflict (tp);
1056 tparams.Create (null, 0, Parent);
1059 protected virtual void DefineTypeParameters ()
1061 var tparams = CurrentTypeParameters;
1063 TypeParameterSpec[] base_tparams = null;
1064 TypeParameterSpec[] base_decl_tparams = TypeParameterSpec.EmptyTypes;
1065 TypeSpec[] base_targs = TypeSpec.EmptyTypes;
1066 if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
1067 MethodSpec base_override = base_method ?? MethodData.implementing;
1069 if (base_override != null) {
1070 base_tparams = base_override.GenericDefinition.TypeParameters;
1072 if (base_override.DeclaringType.IsGeneric) {
1073 base_decl_tparams = base_override.DeclaringType.MemberDefinition.TypeParameters;
1075 if (base_method != null) {
1076 var base_type_parent = CurrentType;
1077 while (base_type_parent.BaseType != base_override.DeclaringType) {
1078 base_type_parent = base_type_parent.BaseType;
1081 base_targs = base_type_parent.BaseType.TypeArguments;
1083 foreach (var iface in Parent.CurrentType.Interfaces) {
1084 if (iface == base_override.DeclaringType) {
1085 base_targs = iface.TypeArguments;
1092 if (base_override.IsGeneric) {
1093 ObsoleteAttribute oa;
1094 foreach (var base_tp in base_tparams) {
1095 oa = base_tp.BaseType.GetAttributeObsolete ();
1097 AttributeTester.Report_ObsoleteMessage (oa, base_tp.BaseType.GetSignatureForError (), Location, Report);
1100 if (base_tp.InterfacesDefined != null) {
1101 foreach (var iface in base_tp.InterfacesDefined) {
1102 oa = iface.GetAttributeObsolete ();
1104 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1110 if (base_decl_tparams.Length != 0) {
1111 base_decl_tparams = base_decl_tparams.Concat (base_tparams).ToArray ();
1112 base_targs = base_targs.Concat (tparams.Types).ToArray ();
1114 base_decl_tparams = base_tparams;
1115 base_targs = tparams.Types;
1121 for (int i = 0; i < tparams.Count; ++i) {
1122 var tp = tparams [i];
1124 if (base_tparams == null) {
1125 tp.ResolveConstraints (this);
1130 // Copy base constraints for override/explicit methods
1132 var base_tparam = base_tparams [i];
1133 var local_tparam = tp.Type;
1134 local_tparam.SpecialConstraint = base_tparam.SpecialConstraint;
1136 var inflator = new TypeParameterInflator (this, CurrentType, base_decl_tparams, base_targs);
1137 base_tparam.InflateConstraints (inflator, local_tparam);
1140 // Check all type argument constraints for possible collision or unification
1141 // introduced by inflating inherited constraints in this context
1143 // Conflict example:
1145 // class A<T> { virtual void Foo<U> () where U : class, T {} }
1146 // class B : A<int> { override void Foo<U> {} }
1148 var local_tparam_targs = local_tparam.TypeArguments;
1149 if (local_tparam_targs != null) {
1150 for (int ii = 0; ii < local_tparam_targs.Length; ++ii) {
1151 var ta = local_tparam_targs [ii];
1152 if (!ta.IsClass && !ta.IsStruct)
1155 TypeSpec[] unique_tparams = null;
1156 for (int iii = ii + 1; iii < local_tparam_targs.Length; ++iii) {
1158 // Remove any identical or unified constraint types
1160 var tparam_checked = local_tparam_targs [iii];
1161 if (TypeSpecComparer.IsEqual (ta, tparam_checked) || TypeSpec.IsBaseClass (ta, tparam_checked, false)) {
1162 unique_tparams = new TypeSpec[local_tparam_targs.Length - 1];
1163 Array.Copy (local_tparam_targs, 0, unique_tparams, 0, iii);
1164 Array.Copy (local_tparam_targs, iii + 1, unique_tparams, iii, local_tparam_targs.Length - iii - 1);
1165 } else if (!TypeSpec.IsBaseClass (tparam_checked, ta, false)) {
1166 Constraints.Error_ConflictingConstraints (this, local_tparam, ta, tparam_checked, Location);
1170 if (unique_tparams != null) {
1171 local_tparam_targs = unique_tparams;
1172 local_tparam.TypeArguments = local_tparam_targs;
1176 Constraints.CheckConflictingInheritedConstraint (local_tparam, ta, this, Location);
1181 if (base_tparams == null && MethodData != null && MethodData.implementing != null) {
1182 CheckImplementingMethodConstraints (Parent, spec, MethodData.implementing);
1186 public static bool CheckImplementingMethodConstraints (TypeContainer container, MethodSpec method, MethodSpec baseMethod)
1188 var tparams = method.Constraints;
1189 var base_tparams = baseMethod.Constraints;
1190 for (int i = 0; i < tparams.Length; ++i) {
1191 if (!tparams[i].HasSameConstraintsImplementation (base_tparams[i])) {
1192 container.Compiler.Report.SymbolRelatedToPreviousError (method);
1193 container.Compiler.Report.SymbolRelatedToPreviousError (baseMethod);
1195 // Using container location because the interface can be implemented
1197 var tp = (tparams [i].MemberDefinition as MemberCore) ?? container;
1198 container.Compiler.Report.Error (425, tp.Location,
1199 "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",
1200 tparams[i].GetSignatureForError (), method.GetSignatureForError (),
1201 base_tparams[i].GetSignatureForError (), baseMethod.GetSignatureForError ());
1213 public override bool Define ()
1215 if (!base.Define ())
1218 if (member_type.Kind == MemberKind.Void && parameters.IsEmpty && MemberName.Arity == 0 && MemberName.Name == Destructor.MetadataName) {
1219 Report.Warning (465, 1, Location,
1220 "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
1223 if (Compiler.Settings.StdLib && ReturnType.IsSpecialRuntimeType) {
1224 Error1599 (Location, ReturnType, Report);
1228 if (CurrentTypeParameters == null) {
1229 if (base_method != null && !IsExplicitImpl) {
1230 if (parameters.Count == 1 && ParameterTypes[0].BuiltinType == BuiltinTypeSpec.Type.Object && MemberName.Name == "Equals")
1231 Parent.PartialContainer.Mark_HasEquals ();
1232 else if (parameters.IsEmpty && MemberName.Name == "GetHashCode")
1233 Parent.PartialContainer.Mark_HasGetHashCode ();
1237 DefineTypeParameters ();
1240 if (block != null) {
1241 if (block.IsIterator) {
1243 // Current method is turned into automatically generated
1244 // wrapper which creates an instance of iterator
1246 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1247 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
1250 if ((ModFlags & Modifiers.ASYNC) != 0) {
1251 if (ReturnType.Kind != MemberKind.Void &&
1252 ReturnType != Module.PredefinedTypes.Task.TypeSpec &&
1253 !ReturnType.IsGenericTask) {
1254 Report.Error (1983, Location, "The return type of an async method must be void, Task, or Task<T>");
1257 block = (ToplevelBlock) block.ConvertToAsyncTask (this, Parent.PartialContainer, parameters, ReturnType, null, Location);
1258 ModFlags |= Modifiers.DEBUGGER_STEP_THROUGH;
1261 if (Compiler.Settings.WriteMetadataOnly)
1265 if ((ModFlags & Modifiers.STATIC) == 0)
1268 if (parameters.HasExtensionMethodType) {
1269 if (Parent.PartialContainer.IsStatic && !Parent.IsGenericOrParentIsGeneric) {
1270 if (!Parent.IsTopLevel)
1271 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
1272 GetSignatureForError ());
1274 PredefinedAttribute pa = Module.PredefinedAttributes.Extension;
1275 if (!pa.IsDefined) {
1276 Report.Error (1110, Location,
1277 "`{0}': Extension methods require `System.Runtime.CompilerServices.ExtensionAttribute' type to be available. Are you missing an assembly reference?",
1278 GetSignatureForError ());
1281 ModFlags |= Modifiers.METHOD_EXTENSION;
1282 Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
1283 Spec.DeclaringType.SetExtensionMethodContainer ();
1284 Parent.Module.HasExtensionMethod = true;
1286 Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
1287 GetSignatureForError ());
1292 // This is used to track the Entry Point,
1294 var settings = Compiler.Settings;
1295 if (settings.NeedsEntryPoint && MemberName.Name == "Main" && !IsPartialDefinition && (settings.MainClass == null || settings.MainClass == Parent.TypeBuilder.FullName)) {
1296 if (IsEntryPoint ()) {
1297 if (Parent.DeclaringAssembly.EntryPoint == null) {
1298 if (Parent.IsGenericOrParentIsGeneric || MemberName.IsGeneric) {
1299 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
1300 GetSignatureForError ());
1301 } else if ((ModFlags & Modifiers.ASYNC) != 0) {
1302 Report.Error (4009, Location, "`{0}': an entry point cannot be async method",
1303 GetSignatureForError ());
1306 Parent.DeclaringAssembly.EntryPoint = this;
1309 Error_DuplicateEntryPoint (Parent.DeclaringAssembly.EntryPoint);
1310 Error_DuplicateEntryPoint (this);
1313 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
1314 GetSignatureForError ());
1321 public override void PrepareEmit ()
1323 if (IsPartialDefinition) {
1325 // Use partial method implementation builder for partial method declaration attributes
1327 if (partialMethodImplementation != null) {
1328 MethodData = partialMethodImplementation.MethodData;
1334 base.PrepareEmit ();
1340 public override void Emit ()
1343 if (IsPartialDefinition) {
1344 if (partialMethodImplementation != null && CurrentTypeParameters != null) {
1345 CurrentTypeParameters.CheckPartialConstraints (partialMethodImplementation);
1347 var otp = partialMethodImplementation.CurrentTypeParameters;
1348 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1349 var tp = CurrentTypeParameters [i];
1357 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
1358 Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
1359 GetSignatureForError ());
1362 if (CurrentTypeParameters != null) {
1363 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1364 var tp = CurrentTypeParameters [i];
1366 tp.CheckGenericConstraints (false);
1371 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
1372 Module.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
1375 } catch (Exception e) {
1376 throw new InternalErrorException (this, e);
1380 public override bool EnableOverloadChecks (MemberCore overload)
1382 if (overload is Indexer)
1385 return base.EnableOverloadChecks (overload);
1388 public static void Error1599 (Location loc, TypeSpec t, Report Report)
1390 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", t.GetSignatureForError ());
1393 protected override bool ResolveMemberType ()
1395 if (CurrentTypeParameters != null) {
1396 CreateTypeParameters ();
1399 return base.ResolveMemberType ();
1402 public void SetPartialDefinition (Method methodDefinition)
1404 caching_flags |= Flags.PartialDefinitionExists;
1405 methodDefinition.partialMethodImplementation = this;
1407 // Ensure we are always using method declaration parameters
1408 for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
1409 var md_p = methodDefinition.parameters [i];
1410 var p = parameters [i];
1412 p.DefaultValue = md_p.DefaultValue;
1413 if (md_p.OptAttributes != null) {
1414 if (p.OptAttributes == null) {
1415 p.OptAttributes = md_p.OptAttributes;
1417 p.OptAttributes.Attrs.AddRange (md_p.OptAttributes.Attrs);
1422 if (methodDefinition.attributes != null) {
1423 if (attributes == null) {
1424 attributes = methodDefinition.attributes;
1426 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
1430 if (CurrentTypeParameters != null) {
1431 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1432 var tp_other = methodDefinition.CurrentTypeParameters [i];
1433 if (tp_other.OptAttributes == null)
1436 var tp = CurrentTypeParameters [i];
1437 if (tp.OptAttributes == null) {
1438 tp.OptAttributes = tp_other.OptAttributes;
1440 tp.OptAttributes.Attrs.AddRange (tp.OptAttributes.Attrs);
1447 public abstract class ConstructorInitializer : ExpressionStatement
1449 Arguments argument_list;
1450 MethodSpec base_ctor;
1452 protected ConstructorInitializer (Arguments argument_list, Location loc)
1454 this.argument_list = argument_list;
1458 public Arguments Arguments {
1460 return argument_list;
1464 public override bool ContainsEmitWithAwait ()
1466 throw new NotSupportedException ();
1469 public override Expression CreateExpressionTree (ResolveContext ec)
1471 throw new NotSupportedException ("ET");
1474 protected override Expression DoResolve (ResolveContext ec)
1476 eclass = ExprClass.Value;
1479 var caller_builder = (Constructor) ec.MemberContext;
1482 // Spec mandates that constructor initializer will not have `this' access
1484 using (ec.Set (ResolveContext.Options.BaseInitializer)) {
1485 if (argument_list != null) {
1487 argument_list.Resolve (ec, out dynamic);
1490 ec.Report.Error (1975, loc,
1491 "The constructor call cannot be dynamically dispatched within constructor initializer");
1497 type = ec.CurrentType;
1498 if (this is ConstructorBaseInitializer) {
1499 if (ec.CurrentType.BaseType == null)
1502 type = ec.CurrentType.BaseType;
1503 if (ec.CurrentType.IsStruct) {
1504 ec.Report.Error (522, loc,
1505 "`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
1510 base_ctor = ConstructorLookup (ec, type, ref argument_list, loc);
1513 if (base_ctor != null && base_ctor.MemberDefinition == caller_builder.Spec.MemberDefinition) {
1514 ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
1515 caller_builder.GetSignatureForError ());
1521 public override void Emit (EmitContext ec)
1524 // It can be null for struct initializers or System.Object
1526 if (base_ctor == null) {
1527 if (type == ec.BuiltinTypes.Object)
1530 ec.Emit (OpCodes.Ldarg_0);
1531 ec.Emit (OpCodes.Initobj, type);
1535 var call = new CallEmitter ();
1536 call.InstanceExpression = new CompilerGeneratedThis (type, loc);
1537 call.EmitPredefined (ec, base_ctor, argument_list, false);
1540 public override void EmitStatement (EmitContext ec)
1545 public override void FlowAnalysis (FlowAnalysisContext fc)
1547 if (argument_list != null)
1548 argument_list.FlowAnalysis (fc);
1552 public class ConstructorBaseInitializer : ConstructorInitializer {
1553 public ConstructorBaseInitializer (Arguments argument_list, Location l) :
1554 base (argument_list, l)
1559 class GeneratedBaseInitializer: ConstructorBaseInitializer {
1560 public GeneratedBaseInitializer (Location loc, Arguments arguments)
1561 : base (arguments, loc)
1566 public class ConstructorThisInitializer : ConstructorInitializer {
1567 public ConstructorThisInitializer (Arguments argument_list, Location l) :
1568 base (argument_list, l)
1573 public class Constructor : MethodCore, IMethodData, IMethodDefinition
1575 public ConstructorBuilder ConstructorBuilder;
1576 public ConstructorInitializer Initializer;
1577 SecurityType declarative_security;
1578 bool has_compliant_args;
1579 SourceMethodBuilder debug_builder;
1582 // Modifiers allowed for a constructor.
1584 public const Modifiers AllowedModifiers =
1586 Modifiers.PROTECTED |
1587 Modifiers.INTERNAL |
1593 static readonly string[] attribute_targets = new string [] { "method" };
1595 public static readonly string ConstructorName = ".ctor";
1596 public static readonly string TypeConstructorName = ".cctor";
1598 public Constructor (TypeDefinition parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args, Location loc)
1599 : base (parent, null, mod, AllowedModifiers, new MemberName (name, loc), attrs, args)
1603 public bool HasCompliantArgs {
1605 return has_compliant_args;
1609 public override AttributeTargets AttributeTargets {
1611 return AttributeTargets.Constructor;
1615 bool IMethodData.IsAccessor {
1621 public bool IsPrimaryConstructor { get; set; }
1623 MethodBase IMethodDefinition.Metadata {
1625 return ConstructorBuilder;
1630 // Returns true if this is a default constructor
1632 public bool IsDefault ()
1634 if ((ModFlags & Modifiers.STATIC) != 0)
1635 return parameters.IsEmpty;
1637 return parameters.IsEmpty &&
1638 (Initializer is ConstructorBaseInitializer) &&
1639 (Initializer.Arguments == null);
1642 public override void Accept (StructuralVisitor visitor)
1644 visitor.Visit (this);
1647 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1649 if (a.IsValidSecurityAttribute ()) {
1650 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
1654 if (a.Type == pa.MethodImpl) {
1655 is_external_implementation = a.IsInternalCall ();
1658 ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1661 protected override bool CheckBase ()
1663 if ((ModFlags & Modifiers.STATIC) != 0) {
1664 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1665 Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1667 // the rest can be ignored
1671 // Check whether arguments were correct.
1672 if (!DefineParameters (parameters))
1675 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1676 Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1678 CheckProtectedModifier ();
1684 // Creates the ConstructorBuilder
1686 public override bool Define ()
1688 if (ConstructorBuilder != null)
1691 if (!CheckAbstractAndExtern (block != null))
1694 // Check if arguments were correct.
1698 if (Parent.PrimaryConstructorParameters != null && !IsPrimaryConstructor && !IsStatic) {
1699 if (Parent.Kind == MemberKind.Struct && Initializer is ConstructorThisInitializer && Initializer.Arguments == null) {
1700 Report.Error (8043, Location, "`{0}': Structs with primary constructor cannot specify default constructor initializer",
1701 GetSignatureForError ());
1702 } else if (Initializer == null || Initializer is ConstructorBaseInitializer) {
1703 Report.Error (8037, Location, "`{0}': Instance constructor of type with primary constructor must specify `this' constructor initializer",
1704 GetSignatureForError ());
1708 if ((ModFlags & Modifiers.EXTERN) != 0 && Initializer != null) {
1709 Report.Error (8091, Location, "`{0}': Contructors cannot be extern and have a constructor initializer",
1710 GetSignatureForError ());
1713 var ca = ModifiersExtensions.MethodAttr (ModFlags) | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
1715 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
1716 ca, CallingConventions,
1717 parameters.GetMetaInfo ());
1719 spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, Compiler.BuiltinTypes.Void, parameters, ModFlags);
1721 Parent.MemberCache.AddMember (spec);
1723 if (block != null) {
1724 // It's here only to report an error
1725 if (block.IsIterator) {
1726 member_type = Compiler.BuiltinTypes.Void;
1727 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
1730 if (Compiler.Settings.WriteMetadataOnly)
1740 public override void Emit ()
1742 if (Parent.PartialContainer.IsComImport) {
1743 if (!IsDefault ()) {
1744 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
1745 Parent.GetSignatureForError ());
1748 // Set as internal implementation and reset block data
1749 // to ensure no IL is generated
1750 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
1754 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
1755 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (ConstructorBuilder);
1757 if (OptAttributes != null)
1758 OptAttributes.Emit ();
1761 parameters.ApplyAttributes (this, ConstructorBuilder);
1764 BlockContext bc = new BlockContext (this, block, Compiler.BuiltinTypes.Void);
1765 bc.Set (ResolveContext.Options.ConstructorScope);
1767 if (block != null) {
1768 if (!IsStatic && Initializer == null && Parent.PartialContainer.Kind == MemberKind.Struct) {
1770 // If this is a non-static `struct' constructor and doesn't have any
1771 // initializer, it must initialize all of the struct's fields.
1773 block.AddThisVariable (bc);
1777 // If we use a "this (...)" constructor initializer, then
1778 // do not emit field initializers, they are initialized in the other constructor
1780 if (!(Initializer is ConstructorThisInitializer))
1781 Parent.PartialContainer.ResolveFieldInitializers (bc);
1784 if (Initializer == null && Parent.PartialContainer.Kind == MemberKind.Class) {
1785 Initializer = new GeneratedBaseInitializer (Location, null);
1788 if (Initializer != null) {
1790 // mdb format does not support reqions. Try to workaround this by emitting the
1791 // sequence point at initializer. Any breakpoint at constructor header should
1792 // be adjusted to this sequence point as it's the next one which follows.
1794 block.AddScopeStatement (new StatementExpression (Initializer));
1798 if (block.Resolve (bc, this)) {
1799 debug_builder = Parent.CreateMethodSymbolEntry ();
1800 EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType, debug_builder);
1801 ec.With (EmitContext.Options.ConstructorScope, true);
1807 if (declarative_security != null) {
1808 foreach (var de in declarative_security) {
1810 ConstructorBuilder.__AddDeclarativeSecurity (de);
1812 ConstructorBuilder.AddDeclarativeSecurity (de.Key, de.Value);
1820 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
1822 // Is never override
1823 bestCandidate = null;
1827 public override string GetCallerMemberName ()
1829 return IsStatic ? TypeConstructorName : ConstructorName;
1832 public override string GetSignatureForDocumentation ()
1834 return Parent.GetSignatureForDocumentation () + ".#ctor" + parameters.GetSignatureForDocumentation ();
1837 public override string GetSignatureForError()
1839 return base.GetSignatureForError () + parameters.GetSignatureForError ();
1842 public override string[] ValidAttributeTargets {
1844 return attribute_targets;
1848 protected override bool VerifyClsCompliance ()
1850 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
1854 if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
1855 foreach (TypeSpec param in parameters.Types) {
1856 if (param.IsArray) {
1862 has_compliant_args = true;
1866 public override void WriteDebugSymbol (MonoSymbolFile file)
1868 if (debug_builder == null)
1871 var token = ConstructorBuilder.GetToken ();
1872 int t = token.Token;
1874 if (ModuleBuilder.IsPseudoToken (t))
1875 t = Module.Builder.ResolvePseudoToken (t);
1878 debug_builder.DefineMethod (file, t);
1881 #region IMethodData Members
1883 public MemberName MethodName {
1889 public TypeSpec ReturnType {
1895 EmitContext IMethodData.CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
1897 throw new NotImplementedException ();
1904 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
1906 public interface IMethodData : IMemberContext
1908 CallingConventions CallingConventions { get; }
1909 Location Location { get; }
1910 MemberName MethodName { get; }
1911 TypeSpec ReturnType { get; }
1912 ParametersCompiled ParameterInfo { get; }
1913 MethodSpec Spec { get; }
1914 bool IsAccessor { get; }
1916 Attributes OptAttributes { get; }
1917 ToplevelBlock Block { get; set; }
1919 EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod);
1923 // Encapsulates most of the Method's state
1925 public class MethodData
1927 public readonly IMethodData method;
1930 // Are we implementing an interface ?
1932 public MethodSpec implementing;
1937 protected InterfaceMemberBase member;
1938 protected Modifiers modifiers;
1939 protected MethodAttributes flags;
1940 protected TypeSpec declaring_type;
1941 protected MethodSpec parent_method;
1942 SourceMethodBuilder debug_builder;
1945 MethodBuilder builder;
1946 public MethodBuilder MethodBuilder {
1952 public TypeSpec DeclaringType {
1954 return declaring_type;
1958 public string MetadataName {
1964 public MethodData (InterfaceMemberBase member,
1965 Modifiers modifiers, MethodAttributes flags, IMethodData method)
1967 this.member = member;
1968 this.modifiers = modifiers;
1971 this.method = method;
1974 public MethodData (InterfaceMemberBase member,
1975 Modifiers modifiers, MethodAttributes flags,
1977 MethodSpec parent_method)
1978 : this (member, modifiers, flags, method)
1980 this.parent_method = parent_method;
1983 public bool Define (TypeDefinition container, string method_full_name)
1985 PendingImplementation pending = container.PendingImplementations;
1986 MethodSpec ambig_iface_method;
1987 bool optional = false;
1989 if (pending != null) {
1990 implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this, out ambig_iface_method, ref optional);
1992 if (member.InterfaceType != null) {
1993 if (implementing == null) {
1994 if (member is PropertyBase) {
1995 container.Compiler.Report.Error (550, method.Location,
1996 "`{0}' is an accessor not found in interface member `{1}{2}'",
1997 method.GetSignatureForError (), member.InterfaceType.GetSignatureForError (),
1998 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
2001 container.Compiler.Report.Error (539, method.Location,
2002 "`{0}.{1}' in explicit interface declaration is not a member of interface",
2003 member.InterfaceType.GetSignatureForError (), member.ShortName);
2007 if (implementing.IsAccessor && !method.IsAccessor) {
2008 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2009 container.Compiler.Report.Error (683, method.Location,
2010 "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
2011 member.GetSignatureForError (), implementing.GetSignatureForError ());
2015 if (implementing != null && !optional) {
2016 if (!method.IsAccessor) {
2017 if (implementing.IsAccessor) {
2018 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2019 container.Compiler.Report.Error (470, method.Location,
2020 "Method `{0}' cannot implement interface accessor `{1}'",
2021 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
2023 } else if (implementing.DeclaringType.IsInterface) {
2024 if (!implementing.IsAccessor) {
2025 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2026 container.Compiler.Report.Error (686, method.Location,
2027 "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
2028 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
2030 PropertyBase.PropertyMethod pm = method as PropertyBase.PropertyMethod;
2031 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
2032 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2033 container.Compiler.Report.Error (277, method.Location,
2034 "Accessor `{0}' must be declared public to implement interface member `{1}'",
2035 method.GetSignatureForError (), implementing.GetSignatureForError ());
2042 ambig_iface_method = null;
2046 // For implicit implementations, make sure we are public, for
2047 // explicit implementations, make sure we are private.
2049 if (implementing != null){
2050 if (member.IsExplicitImpl) {
2051 if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
2052 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2053 container.Compiler.Report.Error (466, method.Location,
2054 "`{0}': the explicit interface implementation cannot introduce the params modifier",
2055 method.GetSignatureForError ());
2058 if (ambig_iface_method != null) {
2059 container.Compiler.Report.SymbolRelatedToPreviousError (ambig_iface_method);
2060 container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
2061 container.Compiler.Report.Warning (473, 2, method.Location,
2062 "Explicit interface implementation `{0}' matches more than one interface member. Consider using a non-explicit implementation instead",
2063 method.GetSignatureForError ());
2067 // Setting implementin to null inside this block will trigger a more
2068 // verbose error reporting for missing interface implementations
2070 if (implementing.DeclaringType.IsInterface) {
2072 // If this is an interface method implementation,
2073 // check for public accessibility
2075 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) {
2076 implementing = null;
2077 } else if (optional && (container.Interfaces == null || !container.Definition.Interfaces.Contains (implementing.DeclaringType))) {
2079 // We are not implementing interface when base class already implemented it
2081 implementing = null;
2083 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2084 // We may never be private.
2085 implementing = null;
2087 } else if ((modifiers & Modifiers.OVERRIDE) == 0) {
2089 // We may be protected if we're overriding something.
2091 implementing = null;
2096 // Static is not allowed
2098 if ((modifiers & Modifiers.STATIC) != 0){
2099 implementing = null;
2104 // If implementing is still valid, set flags
2106 if (implementing != null){
2108 // When implementing interface methods, set NewSlot
2109 // unless, we are overwriting a method.
2111 if ((modifiers & Modifiers.OVERRIDE) == 0 && implementing.DeclaringType.IsInterface) {
2112 flags |= MethodAttributes.NewSlot;
2115 flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;
2117 // Set Final unless we're virtual, abstract or already overriding a method.
2118 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
2119 flags |= MethodAttributes.Final;
2122 // clear the pending implementation flag (requires explicit methods to be defined first)
2124 pending.ImplementMethod (method.MethodName,
2125 member.InterfaceType, this, member.IsExplicitImpl, out ambig_iface_method, ref optional);
2128 // Update indexer accessor name to match implementing abstract accessor
2130 if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
2131 method_full_name = implementing.MemberDefinition.Name;
2134 full_name = method_full_name;
2135 declaring_type = container.Definition;
2140 void DefineOverride (TypeDefinition container)
2142 if (implementing == null)
2145 if (!member.IsExplicitImpl)
2148 container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
2152 // Creates partial MethodBuilder for the method when has generic parameters used
2153 // as arguments or return type
2155 public MethodBuilder DefineMethodBuilder (TypeDefinition container)
2157 if (builder != null)
2158 throw new InternalErrorException ();
2160 builder = container.TypeBuilder.DefineMethod (full_name, flags, method.CallingConventions);
2165 // Creates full MethodBuilder for the method
2167 public MethodBuilder DefineMethodBuilder (TypeDefinition container, ParametersCompiled param)
2169 DefineMethodBuilder (container);
2170 builder.SetReturnType (method.ReturnType.GetMetaInfo ());
2171 builder.SetParameters (param.GetMetaInfo ());
2178 public void Emit (TypeDefinition parent)
2180 DefineOverride (parent);
2182 method.ParameterInfo.ApplyAttributes (method, MethodBuilder);
2184 ToplevelBlock block = method.Block;
2185 if (block != null) {
2186 BlockContext bc = new BlockContext (method, block, method.ReturnType);
2187 if (block.Resolve (bc, method)) {
2188 debug_builder = member.Parent.CreateMethodSymbolEntry ();
2189 EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator (), debug_builder);
2196 public void WriteDebugSymbol (MonoSymbolFile file)
2198 if (debug_builder == null)
2201 var token = builder.GetToken ();
2202 int t = token.Token;
2204 if (ModuleBuilder.IsPseudoToken (t))
2205 t = member.Module.Builder.ResolvePseudoToken (t);
2208 debug_builder.DefineMethod (file, t);
2212 public class Destructor : MethodOrOperator
2214 const Modifiers AllowedModifiers =
2218 static readonly string[] attribute_targets = new string [] { "method" };
2220 public static readonly string MetadataName = "Finalize";
2222 public Destructor (TypeDefinition parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
2223 : base (parent, null, mod, AllowedModifiers, new MemberName (MetadataName, l), attrs, parameters)
2225 ModFlags &= ~Modifiers.PRIVATE;
2226 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
2229 public override void Accept (StructuralVisitor visitor)
2231 visitor.Visit (this);
2234 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2236 if (a.Type == pa.Conditional) {
2237 Error_ConditionalAttributeIsNotValid ();
2241 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2244 protected override bool CheckBase ()
2246 if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2247 CheckForDuplications ();
2249 // Don't check base, destructors have special syntax
2253 public override bool Define ()
2257 if (Compiler.Settings.WriteMetadataOnly)
2263 public override void Emit()
2265 var base_type = Parent.PartialContainer.BaseType;
2266 if (base_type != null && Block != null) {
2267 var base_dtor = MemberCache.FindMember (base_type,
2268 new MemberFilter (MetadataName, 0, MemberKind.Destructor, null, null), BindingRestriction.InstanceOnly) as MethodSpec;
2270 if (base_dtor == null)
2271 throw new NotImplementedException ();
2273 MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
2274 method_expr.InstanceExpression = new BaseThis (base_type, Location);
2276 var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation) {
2277 IsCompilerGenerated = true
2279 var finaly_block = new ExplicitBlock (block, Location, Location) {
2280 IsCompilerGenerated = true
2284 // 0-size arguments to avoid CS0250 error
2285 // TODO: Should use AddScopeStatement or something else which emits correct
2288 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0)), Location.Null));
2290 var tf = new TryFinally (try_block, finaly_block, Location);
2291 block.WrapIntoDestructor (tf, try_block);
2297 public override string GetSignatureForError ()
2299 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
2302 protected override bool ResolveMemberType ()
2304 member_type = Compiler.BuiltinTypes.Void;
2308 public override string[] ValidAttributeTargets {
2310 return attribute_targets;
2315 // Ooouh Martin, templates are missing here.
2316 // When it will be possible move here a lot of child code and template method type.
2317 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData, IMethodDefinition {
2318 protected MethodData method_data;
2319 protected ToplevelBlock block;
2320 protected SecurityType declarative_security;
2322 protected readonly string prefix;
2324 ReturnParameter return_attributes;
2326 protected AbstractPropertyEventMethod (InterfaceMemberBase member, string prefix, Attributes attrs, Location loc)
2327 : base (member.Parent, SetupName (prefix, member, loc), attrs)
2329 this.prefix = prefix;
2332 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
2334 return new MemberName (member.MemberName.Left, prefix + member.ShortName, member.MemberName.ExplicitInterface, loc);
2337 public void UpdateName (InterfaceMemberBase member)
2339 SetMemberName (SetupName (prefix, member, Location));
2342 #region IMethodData Members
2344 public ToplevelBlock Block {
2354 public CallingConventions CallingConventions {
2356 return CallingConventions.Standard;
2360 public EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
2362 return new EmitContext (this, ig, ReturnType, sourceMethod);
2365 public bool IsAccessor {
2371 public MemberName MethodName {
2377 public TypeSpec[] ParameterTypes {
2379 return ParameterInfo.Types;
2383 MethodBase IMethodDefinition.Metadata {
2385 return method_data.MethodBuilder;
2389 public abstract ParametersCompiled ParameterInfo { get ; }
2390 public abstract TypeSpec ReturnType { get; }
2394 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2396 if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
2397 Report.Error (1667, a.Location,
2398 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
2399 a.Type.GetSignatureForError (), a.GetValidTargets ());
2403 if (a.IsValidSecurityAttribute ()) {
2404 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
2408 if (a.Target == AttributeTargets.Method) {
2409 method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
2413 if (a.Target == AttributeTargets.ReturnValue) {
2414 if (return_attributes == null)
2415 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2417 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
2421 ApplyToExtraTarget (a, ctor, cdata, pa);
2424 protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2426 throw new NotSupportedException ("You forgot to define special attribute target handling");
2429 // It is not supported for the accessors
2430 public sealed override bool Define()
2432 throw new NotSupportedException ();
2435 public virtual void Emit (TypeDefinition parent)
2437 method_data.Emit (parent);
2439 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
2440 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
2441 if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
2442 Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
2444 if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2445 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2446 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
2447 } else if (ReturnType.HasDynamicElement) {
2448 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2449 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
2452 if (OptAttributes != null)
2453 OptAttributes.Emit ();
2455 if (declarative_security != null) {
2456 foreach (var de in declarative_security) {
2458 method_data.MethodBuilder.__AddDeclarativeSecurity (de);
2460 method_data.MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2468 public override bool EnableOverloadChecks (MemberCore overload)
2470 if (overload is MethodCore) {
2471 caching_flags |= Flags.MethodOverloadsExist;
2475 // This can only happen with indexers and it will
2476 // be catched as indexer difference
2477 if (overload is AbstractPropertyEventMethod)
2483 public override string GetCallerMemberName ()
2485 return base.GetCallerMemberName ().Substring (prefix.Length);
2488 public override string GetSignatureForDocumentation ()
2490 // should not be called
2491 throw new NotSupportedException ();
2494 public override bool IsClsComplianceRequired()
2499 public void PrepareEmit ()
2501 method_data.DefineMethodBuilder (Parent.PartialContainer, ParameterInfo);
2504 public override void WriteDebugSymbol (MonoSymbolFile file)
2506 if (method_data != null)
2507 method_data.WriteDebugSymbol (file);
2510 public MethodSpec Spec { get; protected set; }
2513 // Represents header string for documentation comment.
2515 public override string DocCommentHeader {
2516 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
2520 public class Operator : MethodOrOperator {
2522 const Modifiers AllowedModifiers =
2528 public enum OpType : byte {
2538 // Unary and Binary operators
2561 // Implicit and Explicit
2568 // Just because of enum
2572 public readonly OpType OperatorType;
2574 static readonly string [] [] names;
2578 names = new string[(int)OpType.TOP][];
2579 names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
2580 names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
2581 names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
2582 names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
2583 names [(int) OpType.True] = new string [] { "true", "op_True" };
2584 names [(int) OpType.False] = new string [] { "false", "op_False" };
2585 names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
2586 names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
2587 names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
2588 names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
2589 names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
2590 names [(int) OpType.Division] = new string [] { "/", "op_Division" };
2591 names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
2592 names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
2593 names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
2594 names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
2595 names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
2596 names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
2597 names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
2598 names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
2599 names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
2600 names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
2601 names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
2602 names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
2603 names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
2604 names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
2605 names [(int) OpType.Is] = new string[] { "is", "op_Is" };
2608 public Operator (TypeDefinition parent, OpType type, FullNamedExpression ret_type, Modifiers mod_flags, ParametersCompiled parameters,
2609 ToplevelBlock block, Attributes attrs, Location loc)
2610 : base (parent, ret_type, mod_flags, AllowedModifiers, new MemberName (GetMetadataName (type), loc), attrs, parameters)
2612 OperatorType = type;
2616 public override void Accept (StructuralVisitor visitor)
2618 visitor.Visit (this);
2621 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2623 if (a.Type == pa.Conditional) {
2624 Error_ConditionalAttributeIsNotValid ();
2628 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2631 public override bool Define ()
2633 const Modifiers RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
2634 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
2635 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
2638 if (!base.Define ())
2641 if (block != null) {
2642 if (block.IsIterator) {
2644 // Current method is turned into automatically generated
2645 // wrapper which creates an instance of iterator
2647 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
2648 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
2651 if (Compiler.Settings.WriteMetadataOnly)
2655 // imlicit and explicit operator of same types are not allowed
2656 if (OperatorType == OpType.Explicit)
2657 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
2658 else if (OperatorType == OpType.Implicit)
2659 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
2661 TypeSpec declaring_type = Parent.PartialContainer.CurrentType;
2662 TypeSpec return_type = MemberType;
2663 TypeSpec first_arg_type = ParameterTypes [0];
2665 TypeSpec first_arg_type_unwrap = first_arg_type;
2666 if (first_arg_type.IsNullableType)
2667 first_arg_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (first_arg_type);
2669 TypeSpec return_type_unwrap = return_type;
2670 if (return_type.IsNullableType)
2671 return_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (return_type);
2674 // Rules for conversion operators
2676 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2677 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type) {
2678 Report.Error (555, Location,
2679 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
2684 if (declaring_type == return_type || declaring_type == return_type_unwrap) {
2685 conv_type = first_arg_type;
2686 } else if (declaring_type == first_arg_type || declaring_type == first_arg_type_unwrap) {
2687 conv_type = return_type;
2689 Report.Error (556, Location,
2690 "User-defined conversion must convert to or from the enclosing type");
2694 if (conv_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2695 Report.Error (1964, Location,
2696 "User-defined conversion `{0}' cannot convert to or from the dynamic type",
2697 GetSignatureForError ());
2702 if (conv_type.IsInterface) {
2703 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
2704 GetSignatureForError ());
2708 if (conv_type.IsClass) {
2709 if (TypeSpec.IsBaseClass (declaring_type, conv_type, true)) {
2710 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
2711 GetSignatureForError ());
2715 if (TypeSpec.IsBaseClass (conv_type, declaring_type, false)) {
2716 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
2717 GetSignatureForError ());
2721 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
2722 if (first_arg_type != declaring_type || parameters.Types[1].BuiltinType != BuiltinTypeSpec.Type.Int) {
2723 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");
2726 } else if (parameters.Count == 1) {
2727 // Checks for Unary operators
2729 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
2730 if (return_type != declaring_type && !TypeSpec.IsBaseClass (return_type, declaring_type, false)) {
2731 Report.Error (448, Location,
2732 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
2735 if (first_arg_type != declaring_type) {
2737 559, Location, "The parameter type for ++ or -- operator must be the containing type");
2742 if (first_arg_type_unwrap != declaring_type) {
2743 Report.Error (562, Location,
2744 "The parameter type of a unary operator must be the containing type");
2748 if (OperatorType == OpType.True || OperatorType == OpType.False) {
2749 if (return_type.BuiltinType != BuiltinTypeSpec.Type.Bool) {
2752 "The return type of operator True or False " +
2758 } else if (first_arg_type_unwrap != declaring_type) {
2759 // Checks for Binary operators
2761 var second_arg_type = ParameterTypes[1];
2762 if (second_arg_type.IsNullableType)
2763 second_arg_type = Nullable.NullableInfo.GetUnderlyingType (second_arg_type);
2765 if (second_arg_type != declaring_type) {
2766 Report.Error (563, Location,
2767 "One of the parameters of a binary operator must be the containing type");
2775 protected override bool ResolveMemberType ()
2777 if (!base.ResolveMemberType ())
2780 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2784 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
2786 // Operator cannot be override
2787 bestCandidate = null;
2791 public static string GetName (OpType ot)
2793 return names [(int) ot] [0];
2796 public static string GetName (string metadata_name)
2798 for (int i = 0; i < names.Length; ++i) {
2799 if (names [i] [1] == metadata_name)
2800 return names [i] [0];
2805 public static string GetMetadataName (OpType ot)
2807 return names [(int) ot] [1];
2810 public static string GetMetadataName (string name)
2812 for (int i = 0; i < names.Length; ++i) {
2813 if (names [i] [0] == name)
2814 return names [i] [1];
2819 public static OpType? GetType (string metadata_name)
2821 for (int i = 0; i < names.Length; ++i) {
2822 if (names[i][1] == metadata_name)
2829 public OpType GetMatchingOperator ()
2831 switch (OperatorType) {
2832 case OpType.Equality:
2833 return OpType.Inequality;
2834 case OpType.Inequality:
2835 return OpType.Equality;
2837 return OpType.False;
2840 case OpType.GreaterThan:
2841 return OpType.LessThan;
2842 case OpType.LessThan:
2843 return OpType.GreaterThan;
2844 case OpType.GreaterThanOrEqual:
2845 return OpType.LessThanOrEqual;
2846 case OpType.LessThanOrEqual:
2847 return OpType.GreaterThanOrEqual;
2853 public override string GetSignatureForDocumentation ()
2855 string s = base.GetSignatureForDocumentation ();
2856 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2857 s = s + "~" + ReturnType.GetSignatureForDocumentation ();
2863 public override string GetSignatureForError ()
2865 StringBuilder sb = new StringBuilder ();
2866 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2867 sb.AppendFormat ("{0}.{1} operator {2}",
2868 Parent.GetSignatureForError (), GetName (OperatorType),
2869 member_type == null ? type_expr.GetSignatureForError () : member_type.GetSignatureForError ());
2872 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
2875 sb.Append (parameters.GetSignatureForError ());
2876 return sb.ToString ();