Merge branch 'master' of http://github.com/mono/mono
[mono.git] / mcs / mcs / method.cs
1 //
2 // method.cs: Method based declarations
3 //
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 //          Martin Baulig (martin@ximian.com)
6 //          Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 //
13
14 using System;
15 using System.Collections.Generic;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Runtime.CompilerServices;
19 using System.Runtime.InteropServices;
20 using System.Security;
21 using System.Security.Permissions;
22 using System.Text;
23 using System.Linq;
24
25 #if NET_2_1
26 using XmlElement = System.Object;
27 #else
28 using System.Xml;
29 #endif
30
31 using Mono.CompilerServices.SymbolWriter;
32
33 namespace Mono.CSharp {
34
35         public abstract class MethodCore : InterfaceMemberBase, IParametersMember
36         {
37                 protected ParametersCompiled parameters;
38                 protected ToplevelBlock block;
39                 protected MethodSpec spec;
40
41                 public MethodCore (DeclSpace parent, GenericMethod generic,
42                         FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
43                         MemberName name, Attributes attrs, ParametersCompiled parameters)
44                         : base (parent, generic, type, mod, allowed_mod, name, attrs)
45                 {
46                         this.parameters = parameters;
47                 }
48
49                 //
50                 //  Returns the System.Type array for the parameters of this method
51                 //
52                 public TypeSpec [] ParameterTypes {
53                         get {
54                                 return parameters.Types;
55                         }
56                 }
57
58                 public ParametersCompiled ParameterInfo {
59                         get {
60                                 return parameters;
61                         }
62                 }
63
64                 AParametersCollection IParametersMember.Parameters {
65                         get { return parameters; }
66                 }
67                 
68                 public ToplevelBlock Block {
69                         get {
70                                 return block;
71                         }
72
73                         set {
74                                 block = value;
75                         }
76                 }
77
78                 public CallingConventions CallingConventions {
79                         get {
80                                 CallingConventions cc = parameters.CallingConvention;
81                                 if (!IsInterface)
82                                         if ((ModFlags & Modifiers.STATIC) == 0)
83                                                 cc |= CallingConventions.HasThis;
84
85                                 // FIXME: How is `ExplicitThis' used in C#?
86                         
87                                 return cc;
88                         }
89                 }
90
91                 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
92                 {
93                         bool res = base.CheckOverrideAgainstBase (base_member);
94
95                         //
96                         // Check that the permissions are not being changed
97                         //
98                         if (!CheckAccessModifiers (this, base_member)) {
99                                 Error_CannotChangeAccessModifiers (this, base_member);
100                                 res = false;
101                         }
102
103                         return res;
104                 }
105
106                 protected override bool CheckBase ()
107                 {
108                         // Check whether arguments were correct.
109                         if (!DefineParameters (parameters))
110                                 return false;
111
112                         return base.CheckBase ();
113                 }
114
115                 //
116                 // Returns a string that represents the signature for this 
117                 // member which should be used in XML documentation.
118                 //
119                 public override string GetDocCommentName (DeclSpace ds)
120                 {
121                         return DocUtil.GetMethodDocCommentName (this, parameters, ds);
122                 }
123
124                 //
125                 // Raised (and passed an XmlElement that contains the comment)
126                 // when GenerateDocComment is writing documentation expectedly.
127                 //
128                 // FIXME: with a few effort, it could be done with XmlReader,
129                 // that means removal of DOM use.
130                 //
131                 internal override void OnGenerateDocComment (XmlElement el)
132                 {
133                         DocUtil.OnMethodGenerateDocComment (this, el, Report);
134                 }
135
136                 //
137                 //   Represents header string for documentation comment.
138                 //
139                 public override string DocCommentHeader 
140                 {
141                         get { return "M:"; }
142                 }
143
144                 public override bool EnableOverloadChecks (MemberCore overload)
145                 {
146                         if (overload is MethodCore) {
147                                 caching_flags |= Flags.MethodOverloadsExist;
148                                 return true;
149                         }
150
151                         if (overload is AbstractPropertyEventMethod)
152                                 return true;
153
154                         return base.EnableOverloadChecks (overload);
155                 }
156
157                 public MethodSpec Spec {
158                         get { return spec; }
159                 }
160
161                 protected override bool VerifyClsCompliance ()
162                 {
163                         if (!base.VerifyClsCompliance ())
164                                 return false;
165
166                         if (parameters.HasArglist) {
167                                 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
168                         }
169
170                         if (member_type != null && !member_type.IsCLSCompliant ()) {
171                                 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
172                                         GetSignatureForError ());
173                         }
174
175                         parameters.VerifyClsCompliance (this);
176                         return true;
177                 }
178         }
179
180         public interface IGenericMethodDefinition : IMemberDefinition
181         {
182                 TypeParameterSpec[] TypeParameters { get; }
183                 int TypeParametersCount { get; }
184
185 //              MethodInfo MakeGenericMethod (TypeSpec[] targs);
186         }
187
188         public class MethodSpec : MemberSpec, IParametersMember
189         {
190                 MethodBase metaInfo;
191                 AParametersCollection parameters;
192                 TypeSpec returnType;
193
194                 TypeSpec[] targs;
195                 TypeParameterSpec[] constraints;
196
197                 public MethodSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition details, TypeSpec returnType,
198                         MethodBase info, AParametersCollection parameters, Modifiers modifiers)
199                         : base (kind, declaringType, details, modifiers)
200                 {
201                         this.metaInfo = info;
202                         this.parameters = parameters;
203                         this.returnType = returnType;
204                 }
205
206                 #region Properties
207
208                 public override int Arity {
209                         get {
210                                 return IsGeneric ? GenericDefinition.TypeParametersCount : 0;
211                         }
212                 }
213
214                 public TypeParameterSpec[] Constraints {
215                         get {
216                                 if (constraints == null && IsGeneric)
217                                         constraints = GenericDefinition.TypeParameters;
218
219                                 return constraints;
220                         }
221                 }
222
223                 public bool IsConstructor {
224                         get {
225                                 return Kind == MemberKind.Constructor;
226                         }
227                 }
228
229                 public IGenericMethodDefinition GenericDefinition {
230                         get {
231                                 return (IGenericMethodDefinition) definition;
232                         }
233                 }
234
235                 public bool IsExtensionMethod {
236                         get {
237                                 return IsStatic && parameters.HasExtensionMethodType;
238                         }
239                 }
240
241                 public bool IsSealed {
242                         get {
243                                 return (Modifiers & Modifiers.SEALED) != 0;
244                         }
245                 }
246
247                 // When is virtual or abstract
248                 public bool IsVirtual {
249                         get {
250                                 return (Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) != 0;
251                         }
252                 }
253
254                 public bool IsReservedMethod {
255                         get {
256                                 return Kind == MemberKind.Operator || IsAccessor;
257                         }
258                 }
259
260                 TypeSpec IInterfaceMemberSpec.MemberType {
261                         get {
262                                 return returnType;
263                         }
264                 }
265
266                 public AParametersCollection Parameters {
267                         get { 
268                                 return parameters;
269                         }
270                 }
271
272                 public TypeSpec ReturnType {
273                         get {
274                                 return returnType;
275                         }
276                 }
277
278                 public TypeSpec[] TypeArguments {
279                         get {
280                                 return targs;
281                         }
282                 }
283
284                 #endregion
285
286                 public MethodSpec GetGenericMethodDefinition ()
287                 {
288                         if (!IsGeneric && !DeclaringType.IsGeneric)
289                                 return this;
290
291                         return MemberCache.GetMember (declaringType, this);
292                 }
293
294                 public MethodBase GetMetaInfo ()
295                 {
296                         if ((state & StateFlags.PendingMetaInflate) != 0) {
297                                 if (DeclaringType.IsTypeBuilder) {
298                                         if (IsConstructor)
299                                                 metaInfo = TypeBuilder.GetConstructor (DeclaringType.GetMetaInfo (), (ConstructorInfo) metaInfo);
300                                         else
301                                                 metaInfo = TypeBuilder.GetMethod (DeclaringType.GetMetaInfo (), (MethodInfo) metaInfo);
302                                 } else {
303                                         metaInfo = MethodInfo.GetMethodFromHandle (metaInfo.MethodHandle, DeclaringType.GetMetaInfo ().TypeHandle);
304                                 }
305
306                                 state &= ~StateFlags.PendingMetaInflate;
307                         }
308
309                         if ((state & StateFlags.PendingMakeMethod) != 0) {
310                                 metaInfo = ((MethodInfo) metaInfo).MakeGenericMethod (targs.Select (l => l.GetMetaInfo ()).ToArray ());
311                                 state &= ~StateFlags.PendingMakeMethod;
312                         }
313
314                         return metaInfo;
315                 }
316
317                 public override string GetSignatureForError ()
318                 {
319                         string name;
320                         if (IsConstructor) {
321                                 name = DeclaringType.GetSignatureForError () + "." + DeclaringType.Name;
322                         } else if (Kind == MemberKind.Operator) {
323                                 var op = Operator.GetType (Name).Value;
324                                 if (op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) {
325                                         name = DeclaringType.GetSignatureForError () + "." + Operator.GetName (op) + " operator " + returnType.GetSignatureForError ();
326                                 } else {
327                                         name = DeclaringType.GetSignatureForError () + ".operator " + Operator.GetName (op);
328                                 }
329                         } else if (IsAccessor) {
330                                 int split = Name.IndexOf ('_');
331                                 name = Name.Substring (split + 1);
332                                 var postfix = Name.Substring (0, split);
333                                 if (split == 3) {
334                                         var pc = parameters.Count;
335                                         if (pc > 0 && postfix == "get") {
336                                                 name = "this" + parameters.GetSignatureForError ("[", "]", pc);
337                                         } else if (pc > 1 && postfix == "set") {
338                                                 name = "this" + parameters.GetSignatureForError ("[", "]", pc - 1);
339                                         }
340                                 }
341
342                                 return DeclaringType.GetSignatureForError () + "." + name + "." + postfix;
343                         } else {
344                                 name = base.GetSignatureForError ();
345                                 if (targs != null)
346                                         name += "<" + TypeManager.CSharpName (targs) + ">";
347                                 else if (IsGeneric)
348                                         name += "<" + TypeManager.CSharpName (GenericDefinition.TypeParameters) + ">";
349                         }
350
351                         return name + parameters.GetSignatureForError ();
352                 }
353
354                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
355                 {
356                         var ms = (MethodSpec) base.InflateMember (inflator);
357                         ms.returnType = inflator.Inflate (returnType);
358                         ms.parameters = parameters.Inflate (inflator);
359                         if (IsGeneric)
360                                 ms.constraints = TypeParameterSpec.InflateConstraints (inflator, GenericDefinition.TypeParameters);
361
362                         return ms;
363                 }
364
365                 public MethodSpec MakeGenericMethod (params TypeSpec[] targs)
366                 {
367                         if (targs == null)
368                                 throw new ArgumentNullException ();
369 // TODO MemberCache
370 //                      if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
371 //                              return ginstance;
372
373                         //if (generic_intances == null)
374                         //    generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
375
376                         var inflator = new TypeParameterInflator (DeclaringType, GenericDefinition.TypeParameters, targs);
377
378                         var inflated = (MethodSpec) MemberwiseClone ();
379                         inflated.declaringType = inflator.TypeInstance;
380                         inflated.returnType = inflator.Inflate (returnType);
381                         inflated.parameters = parameters.Inflate (inflator);
382                         inflated.targs = targs;
383                         inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
384                         inflated.state |= StateFlags.PendingMakeMethod;
385
386                         //                      if (inflated.parent == null)
387                         //                              inflated.parent = parent;
388
389                         //generic_intances.Add (targs, inflated);
390                         return inflated;
391                 }
392
393                 public MethodSpec Mutate (TypeParameterMutator mutator)
394                 {
395                         var targs = TypeArguments;
396                         if (targs != null)
397                                 targs = mutator.Mutate (targs);
398
399                         var decl = DeclaringType;
400                         if (DeclaringType.IsGenericOrParentIsGeneric) {
401                                 decl = mutator.Mutate (decl);
402                         }
403
404                         if (targs == TypeArguments && decl == DeclaringType)
405                                 return this;
406
407                         var ms = (MethodSpec) MemberwiseClone ();
408                         if (decl != DeclaringType) {
409                                 // Gets back MethodInfo in case of metaInfo was inflated
410                                 ms.metaInfo = MemberCache.GetMember (DeclaringType.GetDefinition (), this).metaInfo;
411
412                                 ms.declaringType = decl;
413                                 ms.state |= StateFlags.PendingMetaInflate;
414                         }
415
416                         if (targs != null) {
417                                 ms.targs = targs;
418                                 ms.state |= StateFlags.PendingMakeMethod;
419                         }
420
421                         return ms;
422                 }
423
424                 public void SetMetaInfo (MethodInfo info)
425                 {
426                         if (this.metaInfo != null)
427                                 throw new InternalErrorException ("MetaInfo reset");
428
429                         this.metaInfo = info;
430                 }
431         }
432
433         public abstract class MethodOrOperator : MethodCore, IMethodData
434         {
435                 public MethodBuilder MethodBuilder;
436                 ReturnParameter return_attributes;
437                 Dictionary<SecurityAction, PermissionSet> declarative_security;
438                 protected MethodData MethodData;
439
440                 static string[] attribute_targets = new string [] { "method", "return" };
441
442                 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, Modifiers mod,
443                                 Modifiers allowed_mod, MemberName name,
444                                 Attributes attrs, ParametersCompiled parameters)
445                         : base (parent, generic, type, mod, allowed_mod, name,
446                                         attrs, parameters)
447                 {
448                 }
449
450                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
451                 {
452                         if (a.Target == AttributeTargets.ReturnValue) {
453                                 if (return_attributes == null)
454                                         return_attributes = new ReturnParameter (this, MethodBuilder, Location);
455
456                                 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
457                                 return;
458                         }
459
460                         if (a.IsInternalMethodImplAttribute) {
461                                 is_external_implementation = true;
462                         }
463
464                         if (a.Type == pa.DllImport) {
465                                 const Modifiers extern_static = Modifiers.EXTERN | Modifiers.STATIC;
466                                 if ((ModFlags & extern_static) != extern_static) {
467                                         Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
468                                 }
469                                 is_external_implementation = true;
470                         }
471
472                         if (a.IsValidSecurityAttribute ()) {
473                                 if (declarative_security == null)
474                                         declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
475                                 a.ExtractSecurityPermissionSet (declarative_security);
476                                 return;
477                         }
478
479                         if (MethodBuilder != null)
480                                 MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
481                 }
482
483                 public override AttributeTargets AttributeTargets {
484                         get {
485                                 return AttributeTargets.Method; 
486                         }
487                 }
488
489                 protected override bool CheckForDuplications ()
490                 {
491                         return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
492                 }
493
494                 public virtual EmitContext CreateEmitContext (ILGenerator ig)
495                 {
496                         return new EmitContext (this, ig, MemberType);
497                 }
498
499                 public override bool Define ()
500                 {
501                         if (!base.Define ())
502                                 return false;
503
504                         if (!CheckBase ())
505                                 return false;
506
507                         MemberKind kind;
508                         if (this is Operator)
509                                 kind = MemberKind.Operator;
510                         else if (this is Destructor)
511                                 kind = MemberKind.Destructor;
512                         else
513                                 kind = MemberKind.Method;
514
515                         if (IsPartialDefinition) {
516                                 caching_flags &= ~Flags.Excluded_Undetected;
517                                 caching_flags |= Flags.Excluded;
518
519                                 // Add to member cache only when a partial method implementation has not been found yet
520                                 if ((caching_flags & Flags.PartialDefinitionExists) == 0) {
521 //                                      MethodBase mb = new PartialMethodDefinitionInfo (this);
522
523                                         spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, null, parameters, ModFlags);
524                                         Parent.MemberCache.AddMember (spec);
525                                 }
526
527                                 return true;
528                         }
529
530                         MethodData = new MethodData (
531                                 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
532
533                         if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName), Report))
534                                 return false;
535                                         
536                         MethodBuilder = MethodData.MethodBuilder;
537
538                         spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, MethodBuilder, parameters, ModFlags);
539                         if (MemberName.Arity > 0)
540                                 spec.IsGeneric = true;
541                         
542                         Parent.MemberCache.AddMember (this, MethodBuilder.Name, spec);
543
544                         return true;
545                 }
546
547                 protected override void DoMemberTypeIndependentChecks ()
548                 {
549                         base.DoMemberTypeIndependentChecks ();
550
551                         CheckAbstractAndExtern (block != null);
552
553                         if ((ModFlags & Modifiers.PARTIAL) != 0) {
554                                 for (int i = 0; i < parameters.Count; ++i) {
555                                         IParameterData p = parameters.FixedParameters [i];
556                                         if (p.ModFlags == Parameter.Modifier.OUT) {
557                                                 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
558                                                         GetSignatureForError ());
559                                         }
560
561                                         if (p.HasDefaultValue && IsPartialImplementation)
562                                                 ((Parameter) p).Warning_UselessOptionalParameter (Report);
563                                 }
564                         }
565                 }
566
567                 protected override void DoMemberTypeDependentChecks ()
568                 {
569                         base.DoMemberTypeDependentChecks ();
570
571                         if (MemberType.IsStatic) {
572                                 Error_StaticReturnType ();
573                         }
574                 }
575
576                 public override void Emit ()
577                 {
578                         if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
579                                 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (MethodBuilder);
580                         if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
581                                 PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (MethodBuilder);
582
583                         if (ReturnType == InternalType.Dynamic) {
584                                 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
585                                 PredefinedAttributes.Get.Dynamic.EmitAttribute (return_attributes.Builder);
586                         } else {
587                                 var trans_flags = TypeManager.HasDynamicTypeUsed (ReturnType);
588                                 if (trans_flags != null) {
589                                         var pa = PredefinedAttributes.Get.DynamicTransform;
590                                         if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
591                                                 return_attributes = new ReturnParameter (this, MethodBuilder, Location);
592                                                 return_attributes.Builder.SetCustomAttribute (
593                                                         new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
594                                         }
595                                 }
596                         }
597
598                         if (OptAttributes != null)
599                                 OptAttributes.Emit ();
600
601                         if (declarative_security != null) {
602                                 foreach (var de in declarative_security) {
603                                         MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
604                                 }
605                         }
606
607                         if (MethodData != null)
608                                 MethodData.Emit (Parent);
609
610                         base.Emit ();
611
612                         Block = null;
613                         MethodData = null;
614                 }
615
616                 protected void Error_ConditionalAttributeIsNotValid ()
617                 {
618                         Report.Error (577, Location,
619                                 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
620                                 GetSignatureForError ());
621                 }
622
623                 public bool IsPartialDefinition {
624                         get {
625                                 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
626                         }
627                 }
628
629                 public bool IsPartialImplementation {
630                         get {
631                                 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
632                         }
633                 }
634
635                 public override string[] ValidAttributeTargets {
636                         get {
637                                 return attribute_targets;
638                         }
639                 }
640
641                 #region IMethodData Members
642
643                 public TypeSpec ReturnType {
644                         get {
645                                 return MemberType;
646                         }
647                 }
648
649                 public MemberName MethodName {
650                         get {
651                                 return MemberName;
652                         }
653                 }
654
655                 /// <summary>
656                 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
657                 /// </summary>
658                 public override string[] ConditionalConditions ()
659                 {
660                         if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
661                                 return null;
662
663                         if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
664                                 return new string [0];
665
666                         caching_flags &= ~Flags.Excluded_Undetected;
667                         string[] conditions;
668
669                         if (base_method == null) {
670                                 if (OptAttributes == null)
671                                         return null;
672
673                                 Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
674                                 if (attrs == null)
675                                         return null;
676
677                                 conditions = new string[attrs.Length];
678                                 for (int i = 0; i < conditions.Length; ++i)
679                                         conditions[i] = attrs[i].GetConditionalAttributeValue ();
680                         } else {
681                                 conditions = base_method.MemberDefinition.ConditionalConditions();
682                         }
683
684                         if (conditions != null)
685                                 caching_flags |= Flags.Excluded;
686
687                         return conditions;
688                 }
689
690                 GenericMethod IMethodData.GenericMethod {
691                         get {
692                                 return GenericMethod;
693                         }
694                 }
695
696                 public virtual void EmitExtraSymbolInfo (SourceMethod source)
697                 { }
698
699                 #endregion
700
701         }
702
703         public class SourceMethod : IMethodDef
704         {
705                 MethodBase method;
706                 SourceMethodBuilder builder;
707
708                 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
709                 {
710                         this.method = method;
711                         
712                         builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
713                 }
714
715                 public string Name {
716                         get { return method.Name; }
717                 }
718
719                 public int Token {
720                         get {
721                                 if (method is MethodBuilder)
722                                         return ((MethodBuilder) method).GetToken ().Token;
723                                 else if (method is ConstructorBuilder)
724                                         return ((ConstructorBuilder) method).GetToken ().Token;
725                                 else
726                                         throw new NotSupportedException ();
727                         }
728                 }
729
730                 public void CloseMethod ()
731                 {
732                         SymbolWriter.CloseMethod ();
733                 }
734
735                 public void SetRealMethodName (string name)
736                 {
737                         if (builder != null)
738                                 builder.SetRealMethodName (name);
739                 }
740
741                 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
742                 {
743                         if (!SymbolWriter.HasSymbolWriter)
744                                 return null;
745                         if (block == null)
746                                 return null;
747
748                         Location start_loc = block.StartLocation;
749                         if (start_loc.IsNull)
750                                 return null;
751
752                         ICompileUnit compile_unit = start_loc.CompilationUnit;
753                         if (compile_unit == null)
754                                 return null;
755
756                         return new SourceMethod (parent, method, compile_unit);
757                 }
758         }
759
760         public class Method : MethodOrOperator, IGenericMethodDefinition
761         {
762                 /// <summary>
763                 ///   Modifiers allowed in a class declaration
764                 /// </summary>
765                 const Modifiers AllowedModifiers =
766                         Modifiers.NEW |
767                         Modifiers.PUBLIC |
768                         Modifiers.PROTECTED |
769                         Modifiers.INTERNAL |
770                         Modifiers.PRIVATE |
771                         Modifiers.STATIC |
772                         Modifiers.VIRTUAL |
773                         Modifiers.SEALED |
774                         Modifiers.OVERRIDE |
775                         Modifiers.ABSTRACT |
776                         Modifiers.UNSAFE |
777                         Modifiers.EXTERN;
778
779                 const Modifiers AllowedInterfaceModifiers = 
780                         Modifiers.NEW | Modifiers.UNSAFE;
781
782                 Method partialMethodImplementation;
783
784                 public Method (DeclSpace parent, GenericMethod generic,
785                                FullNamedExpression return_type, Modifiers mod,
786                                MemberName name, ParametersCompiled parameters, Attributes attrs)
787                         : base (parent, generic, return_type, mod,
788                                 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
789                                 name, attrs, parameters)
790                 {
791                 }
792
793                 protected Method (DeclSpace parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
794                                         MemberName name, ParametersCompiled parameters, Attributes attrs)
795                         : base (parent, null, return_type, mod, amod, name, attrs, parameters)
796                 {
797                 }
798
799 #region Properties
800
801                 public override TypeParameter[] CurrentTypeParameters {
802                         get {
803                                 if (GenericMethod != null)
804                                         return GenericMethod.CurrentTypeParameters;
805
806                                 return null;
807                         }
808                 }
809
810                 public override bool HasUnresolvedConstraints {
811                         get {
812                                 if (CurrentTypeParameters == null)
813                                         return false;
814
815                                 // When overriding base method constraints are fetched from
816                                 // base method but to find it we have to resolve parameters
817                                 // to find exact base method match
818                                 if (IsExplicitImpl || (ModFlags & Modifiers.OVERRIDE) != 0)
819                                         return base_method == null;
820
821                                 // Even for non-override generic method constraints check has to be
822                                 // delayed after all constraints are resolved
823                                 return true;
824                         }
825                 }
826
827                 public TypeParameterSpec[] TypeParameters {
828                         get {
829                                 return CurrentTypeParameters.Select (l => l.Type).ToArray ();
830                         }
831                 }
832
833                 public int TypeParametersCount {
834                         get {
835                                 return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Length;
836                         }
837                 }
838
839 #endregion
840
841                 public override string GetSignatureForError()
842                 {
843                         return base.GetSignatureForError () + parameters.GetSignatureForError ();
844                 }
845
846                 void Error_DuplicateEntryPoint (Method b)
847                 {
848                         Report.Error (17, b.Location,
849                                 "Program `{0}' has more than one entry point defined: `{1}'",
850                                 CodeGen.FileName, b.GetSignatureForError ());
851                 }
852
853                 bool IsEntryPoint ()
854                 {
855                         if (ReturnType != TypeManager.void_type &&
856                                 ReturnType != TypeManager.int32_type)
857                                 return false;
858
859                         if (parameters.IsEmpty)
860                                 return true;
861
862                         if (parameters.Count > 1)
863                                 return false;
864
865                         var ac = parameters.Types [0] as ArrayContainer;
866                         return ac != null && ac.Rank == 1 && ac.Element == TypeManager.string_type &&
867                                         (parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
868                 }
869
870                 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
871                 {
872                         if (arity == 0) {
873                                 TypeParameter[] tp = CurrentTypeParameters;
874                                 if (tp != null) {
875                                         TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
876                                         if (t != null)
877                                                 return new TypeParameterExpr (t, loc);
878                                 }
879                         }
880
881                         return base.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
882                 }
883
884                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
885                 {
886                         if (a.Type == pa.Conditional) {
887                                 if (IsExplicitImpl) {
888                                         Error_ConditionalAttributeIsNotValid ();
889                                         return;
890                                 }
891
892                                 if (ReturnType != TypeManager.void_type) {
893                                         Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
894                                         return;
895                                 }
896
897                                 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
898                                         Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
899                                         return;
900                                 }
901
902                                 if (IsInterface) {
903                                         Report.Error (582, Location, "Conditional not valid on interface members");
904                                         return;
905                                 }
906
907                                 if (MethodData.implementing != null) {
908                                         Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
909                                         Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
910                                                 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
911                                         return;
912                                 }
913
914                                 for (int i = 0; i < parameters.Count; ++i) {
915                                         if (parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
916                                                 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
917                                                 return;
918                                         }
919                                 }
920                         }
921
922                         if (a.Type == pa.Extension) {
923                                 a.Error_MisusedExtensionAttribute ();
924                                 return;
925                         }
926
927                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
928                 }
929
930                 protected virtual void DefineTypeParameters ()
931                 {
932                         var tparams = CurrentTypeParameters;
933
934                         TypeParameterSpec[] base_tparams = null;
935                         TypeParameterSpec[] base_decl_tparams = TypeParameterSpec.EmptyTypes;
936                         TypeSpec[] base_targs = TypeSpec.EmptyTypes;
937                         if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
938                                 if (base_method != null) {
939                                         base_tparams = base_method.GenericDefinition.TypeParameters;
940                                         if (base_method.DeclaringType.IsGeneric) {
941                                                 base_decl_tparams = base_method.DeclaringType.MemberDefinition.TypeParameters;
942                                                 base_targs = Parent.BaseType.TypeArguments;
943                                         }
944                                 } else if (MethodData.implementing != null) {
945                                         base_tparams = MethodData.implementing.GenericDefinition.TypeParameters;
946                                         if (MethodData.implementing.DeclaringType.IsGeneric) {
947                                                 base_decl_tparams = MethodData.implementing.DeclaringType.MemberDefinition.TypeParameters;
948                                                 foreach (var iface in Parent.CurrentType.Interfaces) {
949                                                         if (iface == MethodData.implementing.DeclaringType) {
950                                                                 base_targs = iface.TypeArguments;
951                                                                 break;
952                                                         }
953                                                 }
954                                         }
955                                 }
956                         }
957
958                         for (int i = 0; i < tparams.Length; ++i) {
959                                 var tp = tparams[i];
960
961                                 if (!tp.ResolveConstraints (this))
962                                         continue;
963
964                                 //
965                                 // Copy base constraints for override/explicit methods
966                                 //
967                                 if (base_tparams != null) {
968                                         var base_tparam = base_tparams[i];
969                                         tp.Type.SpecialConstraint = base_tparam.SpecialConstraint;
970
971                                         var inflator = new TypeParameterInflator (CurrentType, base_decl_tparams, base_targs);
972                                         base_tparam.InflateConstraints (inflator, tp.Type);
973                                 } else if (MethodData.implementing != null) {
974                                         var base_tp = MethodData.implementing.Constraints[i];
975                                         if (!tp.Type.HasSameConstraintsImplementation (base_tp)) {
976                                                 Report.SymbolRelatedToPreviousError (MethodData.implementing);
977                                                 Report.Error (425, Location,
978                                                         "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",
979                                                         tp.GetSignatureForError (), GetSignatureForError (), base_tp.GetSignatureForError (), MethodData.implementing.GetSignatureForError ());
980                                         }
981                                 }
982                         }
983                 }
984
985                 //
986                 // Creates the type
987                 //
988                 public override bool Define ()
989                 {
990                         if (type_expr.Type == TypeManager.void_type && parameters.IsEmpty && MemberName.Arity == 0 && MemberName.Name == Destructor.MetadataName) {
991                                 Report.Warning (465, 1, Location, "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
992                         }
993
994                         if (!base.Define ())
995                                 return false;
996
997                         if (partialMethodImplementation != null && IsPartialDefinition)
998                                 MethodBuilder = partialMethodImplementation.MethodBuilder;
999
1000                         if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
1001                                 Error1599 (Location, ReturnType, Report);
1002                                 return false;
1003                         }
1004
1005                         if (CurrentTypeParameters == null) {
1006                                 if (base_method != null) {
1007                                         if (parameters.Count == 1 && ParameterTypes[0] == TypeManager.object_type && Name == "Equals")
1008                                                 Parent.PartialContainer.Mark_HasEquals ();
1009                                         else if (parameters.IsEmpty && Name == "GetHashCode")
1010                                                 Parent.PartialContainer.Mark_HasGetHashCode ();
1011                                 }
1012                                         
1013                         } else {
1014                                 DefineTypeParameters ();
1015                         }
1016
1017                         if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
1018                                 //
1019                                 // Current method is turned into automatically generated
1020                                 // wrapper which creates an instance of iterator
1021                                 //
1022                                 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
1023                                 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
1024                         }
1025
1026                         if ((ModFlags & Modifiers.STATIC) == 0)
1027                                 return true;
1028
1029                         if (parameters.HasExtensionMethodType) {
1030                                 if (Parent.PartialContainer.IsStatic && !Parent.IsGeneric) {
1031                                         if (!Parent.IsTopLevel)
1032                                                 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
1033                                                         GetSignatureForError ());
1034
1035                                         PredefinedAttribute pa = PredefinedAttributes.Get.Extension;
1036                                         if (!pa.IsDefined) {
1037                                                 Report.Error (1110, Location,
1038                                                         "`{0}': Extension methods cannot be declared without a reference to System.Core.dll assembly. Add the assembly reference or remove `this' modifer from the first parameter",
1039                                                         GetSignatureForError ());
1040                                         }
1041
1042                                         ModFlags |= Modifiers.METHOD_EXTENSION;
1043                                         Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
1044                                         Spec.DeclaringType.SetExtensionMethodContainer ();
1045                                         CodeGen.Assembly.HasExtensionMethods = true;
1046                                 } else {
1047                                         Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
1048                                                 GetSignatureForError ());
1049                                 }
1050                         }
1051
1052                         //
1053                         // This is used to track the Entry Point,
1054                         //
1055                         if (RootContext.NeedsEntryPoint &&
1056                                 Name == "Main" &&
1057                                 (RootContext.MainClass == null ||
1058                                 RootContext.MainClass == Parent.TypeBuilder.FullName)){
1059                                 if (IsEntryPoint ()) {
1060
1061                                         if (RootContext.EntryPoint == null) {
1062                                                 if (Parent.IsGeneric || MemberName.IsGeneric) {
1063                                                         Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
1064                                                                 GetSignatureForError ());
1065                                                 } else {
1066                                                         SetIsUsed ();
1067                                                         RootContext.EntryPoint = this;
1068                                                 }
1069                                         } else {
1070                                                 Error_DuplicateEntryPoint (RootContext.EntryPoint);
1071                                                 Error_DuplicateEntryPoint (this);
1072                                         }
1073                                 } else {
1074                                         Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
1075                                                 GetSignatureForError ());
1076                                 }
1077                         }
1078
1079                         return true;
1080                 }
1081
1082                 //
1083                 // Emits the code
1084                 // 
1085                 public override void Emit ()
1086                 {
1087                         try {
1088                                 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
1089                                 if (IsPartialDefinition) {
1090                                         //
1091                                         // Use partial method implementation builder for partial method declaration attributes
1092                                         //
1093                                         if (partialMethodImplementation != null) {
1094                                                 MethodBuilder = partialMethodImplementation.MethodBuilder;
1095                                                 return;
1096                                         }
1097                                 } else if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
1098                                         Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
1099                                                 GetSignatureForError ());
1100                                 }
1101
1102                                 if (CurrentTypeParameters != null) {
1103                                         var ge = type_expr as GenericTypeExpr;
1104                                         if (ge != null)
1105                                                 ge.CheckConstraints (this);
1106
1107                                         foreach (Parameter p in parameters.FixedParameters) {
1108                                                 ge = p.TypeExpression as GenericTypeExpr;
1109                                                 if (ge != null)
1110                                                         ge.CheckConstraints (this);
1111                                         }
1112
1113                                         for (int i = 0; i < CurrentTypeParameters.Length; ++i) {
1114                                                 var tp = CurrentTypeParameters [i];
1115                                                 tp.CheckGenericConstraints ();
1116                                                 tp.Emit ();
1117                                         }
1118                                 }
1119
1120                                 base.Emit ();
1121                                 
1122                                 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
1123                                         PredefinedAttributes.Get.Extension.EmitAttribute (MethodBuilder);
1124                         } catch {
1125                                 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
1126                                                    Location, MethodBuilder);
1127                                 throw;
1128                         }
1129                 }
1130
1131                 public override bool EnableOverloadChecks (MemberCore overload)
1132                 {
1133                         // TODO: It can be deleted when members will be defined in correct order
1134                         if (overload is Operator)
1135                                 return overload.EnableOverloadChecks (this);
1136
1137                         if (overload is Indexer)
1138                                 return false;
1139
1140                         return base.EnableOverloadChecks (overload);
1141                 }
1142
1143                 public static void Error1599 (Location loc, TypeSpec t, Report Report)
1144                 {
1145                         Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
1146                 }
1147
1148                 protected override bool ResolveMemberType ()
1149                 {
1150                         if (GenericMethod != null) {
1151                                 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
1152                                 if (!GenericMethod.Define (this))
1153                                         return false;
1154                         }
1155
1156                         return base.ResolveMemberType ();
1157                 }
1158
1159                 public void SetPartialDefinition (Method methodDefinition)
1160                 {
1161                         caching_flags |= Flags.PartialDefinitionExists;
1162                         methodDefinition.partialMethodImplementation = this;
1163
1164                         // Ensure we are always using method declaration parameters
1165                         for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
1166                                 parameters [i].Name = methodDefinition.parameters [i].Name;
1167                                 parameters [i].DefaultValue = methodDefinition.parameters [i].DefaultValue;
1168                         }
1169
1170                         if (methodDefinition.attributes == null)
1171                                 return;
1172
1173                         if (attributes == null) {
1174                                 attributes = methodDefinition.attributes;
1175                         } else {
1176                                 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
1177                         }
1178                 }
1179         }
1180
1181         public abstract class ConstructorInitializer : ExpressionStatement
1182         {
1183                 Arguments argument_list;
1184                 MethodSpec base_ctor;
1185
1186                 public ConstructorInitializer (Arguments argument_list, Location loc)
1187                 {
1188                         this.argument_list = argument_list;
1189                         this.loc = loc;
1190                 }
1191
1192                 public Arguments Arguments {
1193                         get {
1194                                 return argument_list;
1195                         }
1196                 }
1197
1198                 public override Expression CreateExpressionTree (ResolveContext ec)
1199                 {
1200                         throw new NotSupportedException ("ET");
1201                 }
1202
1203                 protected override Expression DoResolve (ResolveContext ec)
1204                 {
1205                         eclass = ExprClass.Value;
1206
1207                         // FIXME: Hack
1208                         var caller_builder = (Constructor) ec.MemberContext;
1209
1210                         if (argument_list != null) {
1211                                 bool dynamic;
1212
1213                                 //
1214                                 // Spec mandates that constructor initializer will not have `this' access
1215                                 //
1216                                 using (ec.Set (ResolveContext.Options.BaseInitializer)) {
1217                                         argument_list.Resolve (ec, out dynamic);
1218                                 }
1219
1220                                 if (dynamic) {
1221                                         ec.Report.Error (1975, loc,
1222                                                 "The constructor call cannot be dynamically dispatched within constructor initializer");
1223
1224                                         return null;
1225                                 }
1226                         }
1227
1228                         type = ec.CurrentType;
1229                         if (this is ConstructorBaseInitializer) {
1230                                 if (ec.CurrentType.BaseType == null)
1231                                         return this;
1232
1233                                 type = ec.CurrentType.BaseType;
1234                                 if (ec.CurrentType.IsStruct) {
1235                                         ec.Report.Error (522, loc,
1236                                                 "`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
1237                                         return this;
1238                                 }
1239                         } else {
1240                                 //
1241                                 // It is legal to have "this" initializers that take no arguments
1242                                 // in structs, they are just no-ops.
1243                                 //
1244                                 // struct D { public D (int a) : this () {}
1245                                 //
1246                                 if (TypeManager.IsStruct (ec.CurrentType) && argument_list == null)
1247                                         return this;                    
1248                         }
1249
1250                         base_ctor = ConstructorLookup (ec, type, ref argument_list, loc);
1251         
1252                         // TODO MemberCache: Does it work for inflated types ?
1253                         if (base_ctor == caller_builder.Spec){
1254                                 ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
1255                                         caller_builder.GetSignatureForError ());
1256                         }
1257                                                 
1258                         return this;
1259                 }
1260
1261                 public override void Emit (EmitContext ec)
1262                 {
1263                         // It can be null for static initializers
1264                         if (base_ctor == null)
1265                                 return;
1266                         
1267                         ec.Mark (loc);
1268
1269                         Invocation.EmitCall (ec, new CompilerGeneratedThis (type, loc), base_ctor, argument_list, loc);
1270                 }
1271
1272                 public override void EmitStatement (EmitContext ec)
1273                 {
1274                         Emit (ec);
1275                 }
1276         }
1277
1278         public class ConstructorBaseInitializer : ConstructorInitializer {
1279                 public ConstructorBaseInitializer (Arguments argument_list, Location l) :
1280                         base (argument_list, l)
1281                 {
1282                 }
1283         }
1284
1285         class GeneratedBaseInitializer: ConstructorBaseInitializer {
1286                 public GeneratedBaseInitializer (Location loc):
1287                         base (null, loc)
1288                 {
1289                 }
1290         }
1291
1292         public class ConstructorThisInitializer : ConstructorInitializer {
1293                 public ConstructorThisInitializer (Arguments argument_list, Location l) :
1294                         base (argument_list, l)
1295                 {
1296                 }
1297         }
1298         
1299         public class Constructor : MethodCore, IMethodData {
1300                 public ConstructorBuilder ConstructorBuilder;
1301                 public ConstructorInitializer Initializer;
1302                 Dictionary<SecurityAction, PermissionSet> declarative_security;
1303                 bool has_compliant_args;
1304
1305                 // <summary>
1306                 //   Modifiers allowed for a constructor.
1307                 // </summary>
1308                 public const Modifiers AllowedModifiers =
1309                         Modifiers.PUBLIC |
1310                         Modifiers.PROTECTED |
1311                         Modifiers.INTERNAL |
1312                         Modifiers.STATIC |
1313                         Modifiers.UNSAFE |
1314                         Modifiers.EXTERN |              
1315                         Modifiers.PRIVATE;
1316
1317                 static readonly string[] attribute_targets = new string [] { "method" };
1318
1319                 //
1320                 // The spec claims that static is not permitted, but
1321                 // my very own code has static constructors.
1322                 //
1323                 public Constructor (DeclSpace parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args,
1324                                     ConstructorInitializer init, Location loc)
1325                         : base (parent, null, null, mod, AllowedModifiers,
1326                                 new MemberName (name, loc), attrs, args)
1327                 {
1328                         Initializer = init;
1329                 }
1330
1331                 public bool HasCompliantArgs {
1332                         get { return has_compliant_args; }
1333                 }
1334
1335                 public override AttributeTargets AttributeTargets {
1336                         get { return AttributeTargets.Constructor; }
1337                 }
1338
1339                 //
1340                 // Returns true if this is a default constructor
1341                 //
1342                 public bool IsDefault ()
1343                 {
1344                         if ((ModFlags & Modifiers.STATIC) != 0)
1345                                 return parameters.IsEmpty;
1346
1347                         return parameters.IsEmpty &&
1348                                         (Initializer is ConstructorBaseInitializer) &&
1349                                         (Initializer.Arguments == null);
1350                 }
1351
1352                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1353                 {
1354                         if (a.IsValidSecurityAttribute ()) {
1355                                 if (declarative_security == null) {
1356                                         declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
1357                                 }
1358                                 a.ExtractSecurityPermissionSet (declarative_security);
1359                                 return;
1360                         }
1361
1362                         if (a.IsInternalMethodImplAttribute) {
1363                                 is_external_implementation = true;
1364                         }
1365
1366                         ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1367                 }
1368
1369                 protected override bool CheckBase ()
1370                 {
1371                         if ((ModFlags & Modifiers.STATIC) != 0) {
1372                                 if (!parameters.IsEmpty) {
1373                                         Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
1374                                                 GetSignatureForError ());
1375                                         return false;
1376                                 }
1377
1378                                 // the rest can be ignored
1379                                 return true;
1380                         }
1381
1382                         // Check whether arguments were correct.
1383                         if (!DefineParameters (parameters))
1384                                 return false;
1385
1386                         if ((caching_flags & Flags.MethodOverloadsExist) != 0)
1387                                 Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1388
1389                         if (Parent.PartialContainer.Kind == MemberKind.Struct && parameters.IsEmpty) {
1390                                 Report.Error (568, Location, 
1391                                         "Structs cannot contain explicit parameterless constructors");
1392                                 return false;
1393                         }
1394
1395                         CheckProtectedModifier ();
1396                         
1397                         return true;
1398                 }
1399                 
1400                 //
1401                 // Creates the ConstructorBuilder
1402                 //
1403                 public override bool Define ()
1404                 {
1405                         if (ConstructorBuilder != null)
1406                                 return true;
1407
1408                         var ca = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
1409                         
1410                         if ((ModFlags & Modifiers.STATIC) != 0) {
1411                                 ca |= MethodAttributes.Static | MethodAttributes.Private;
1412                         } else {
1413                                 ca |= ModifiersExtensions.MethodAttr (ModFlags);
1414                         }
1415
1416                         if (!CheckAbstractAndExtern (block != null))
1417                                 return false;
1418                         
1419                         // Check if arguments were correct.
1420                         if (!CheckBase ())
1421                                 return false;
1422
1423                         ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
1424                                 ca, CallingConventions,
1425                                 parameters.GetMetaInfo ());
1426
1427                         spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, TypeManager.void_type, ConstructorBuilder, parameters, ModFlags);
1428                         
1429                         Parent.MemberCache.AddMember (spec);
1430                         
1431                         // It's here only to report an error
1432                         if (block != null && block.IsIterator) {
1433                                 member_type = TypeManager.void_type;
1434                                 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
1435                         }
1436
1437                         return true;
1438                 }
1439
1440                 //
1441                 // Emits the code
1442                 //
1443                 public override void Emit ()
1444                 {
1445                         if (Parent.PartialContainer.IsComImport) {
1446                                 if (!IsDefault ()) {
1447                                         Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
1448                                                 Parent.GetSignatureForError ());
1449                                 }
1450                                 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
1451                         }
1452
1453                         if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
1454                                 PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (ConstructorBuilder);
1455
1456                         if (OptAttributes != null)
1457                                 OptAttributes.Emit ();
1458
1459                         base.Emit ();
1460
1461                         //
1462                         // If we use a "this (...)" constructor initializer, then
1463                         // do not emit field initializers, they are initialized in the other constructor
1464                         //
1465                         bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
1466                                 !(Initializer is ConstructorThisInitializer);
1467
1468                         BlockContext bc = new BlockContext (this, block, TypeManager.void_type);
1469                         bc.Set (ResolveContext.Options.ConstructorScope);
1470
1471                         if (emit_field_initializers)
1472                                 Parent.PartialContainer.ResolveFieldInitializers (bc);
1473
1474                         if (block != null) {
1475                                 // If this is a non-static `struct' constructor and doesn't have any
1476                                 // initializer, it must initialize all of the struct's fields.
1477                                 if ((Parent.PartialContainer.Kind == MemberKind.Struct) &&
1478                                         ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
1479                                         block.AddThisVariable (Parent, Location);
1480
1481                                 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
1482                                         if (Parent.PartialContainer.Kind == MemberKind.Class && Initializer == null)
1483                                                 Initializer = new GeneratedBaseInitializer (Location);
1484
1485                                         if (Initializer != null) {
1486                                                 block.AddScopeStatement (new StatementExpression (Initializer));
1487                                         }
1488                                 }
1489                         }
1490
1491                         parameters.ApplyAttributes (ConstructorBuilder);
1492
1493                         SourceMethod source = SourceMethod.Create (Parent, ConstructorBuilder, block);
1494
1495                         if (block != null) {
1496                                 if (block.Resolve (null, bc, parameters, this)) {
1497                                         EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType);
1498                                         ec.With (EmitContext.Options.ConstructorScope, true);
1499
1500                                         if (!ec.HasReturnLabel && bc.HasReturnLabel) {
1501                                                 ec.ReturnLabel = bc.ReturnLabel;
1502                                                 ec.HasReturnLabel = true;
1503                                         }
1504
1505                                         block.Emit (ec);
1506                                 }
1507                         }
1508
1509                         if (source != null)
1510                                 source.CloseMethod ();
1511
1512                         if (declarative_security != null) {
1513                                 foreach (var de in declarative_security) {
1514                                         ConstructorBuilder.AddDeclarativeSecurity (de.Key, de.Value);
1515                                 }
1516                         }
1517
1518                         block = null;
1519                 }
1520
1521                 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate)
1522                 {
1523                         // Is never override
1524                         bestCandidate = null;
1525                         return null;
1526                 }
1527
1528                 public override string GetSignatureForError()
1529                 {
1530                         return base.GetSignatureForError () + parameters.GetSignatureForError ();
1531                 }
1532
1533                 public override string[] ValidAttributeTargets {
1534                         get {
1535                                 return attribute_targets;
1536                         }
1537                 }
1538
1539                 protected override bool VerifyClsCompliance ()
1540                 {
1541                         if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
1542                                 return false;
1543                         }
1544
1545                         if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
1546                                 foreach (TypeSpec param in parameters.Types) {
1547                                         if (param.IsArray) {
1548                                                 return true;
1549                                         }
1550                                 }
1551                         }
1552
1553                         has_compliant_args = true;
1554                         return true;
1555                 }
1556
1557                 #region IMethodData Members
1558
1559                 public MemberName MethodName {
1560                         get {
1561                                 return MemberName;
1562                         }
1563                 }
1564
1565                 public TypeSpec ReturnType {
1566                         get {
1567                                 return MemberType;
1568                         }
1569                 }
1570
1571                 public EmitContext CreateEmitContext (ILGenerator ig)
1572                 {
1573                         throw new NotImplementedException ();
1574                 }
1575
1576                 public bool IsExcluded()
1577                 {
1578                         return false;
1579                 }
1580
1581                 GenericMethod IMethodData.GenericMethod {
1582                         get {
1583                                 return null;
1584                         }
1585                 }
1586
1587                 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
1588                 { }
1589
1590                 #endregion
1591         }
1592
1593         /// <summary>
1594         /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
1595         /// </summary>
1596         public interface IMethodData
1597         {
1598                 CallingConventions CallingConventions { get; }
1599                 Location Location { get; }
1600                 MemberName MethodName { get; }
1601                 TypeSpec ReturnType { get; }
1602                 GenericMethod GenericMethod { get; }
1603                 ParametersCompiled ParameterInfo { get; }
1604                 MethodSpec Spec { get; }
1605
1606                 Attributes OptAttributes { get; }
1607                 ToplevelBlock Block { get; set; }
1608
1609                 EmitContext CreateEmitContext (ILGenerator ig);
1610                 string GetSignatureForError ();
1611                 void EmitExtraSymbolInfo (SourceMethod source);
1612         }
1613
1614         //
1615         // Encapsulates most of the Method's state
1616         //
1617         public class MethodData {
1618                 static FieldInfo methodbuilder_attrs_field;
1619                 public readonly IMethodData method;
1620
1621                 public readonly GenericMethod GenericMethod;
1622
1623                 //
1624                 // Are we implementing an interface ?
1625                 //
1626                 public MethodSpec implementing;
1627
1628                 //
1629                 // Protected data.
1630                 //
1631                 protected InterfaceMemberBase member;
1632                 protected Modifiers modifiers;
1633                 protected MethodAttributes flags;
1634                 protected TypeSpec declaring_type;
1635                 protected MethodSpec parent_method;
1636
1637                 MethodBuilder builder;
1638                 public MethodBuilder MethodBuilder {
1639                         get {
1640                                 return builder;
1641                         }
1642                 }
1643
1644                 public TypeSpec DeclaringType {
1645                         get {
1646                                 return declaring_type;
1647                         }
1648                 }
1649
1650                 public MethodData (InterfaceMemberBase member,
1651                                    Modifiers modifiers, MethodAttributes flags, IMethodData method)
1652                 {
1653                         this.member = member;
1654                         this.modifiers = modifiers;
1655                         this.flags = flags;
1656
1657                         this.method = method;
1658                 }
1659
1660                 public MethodData (InterfaceMemberBase member,
1661                                    Modifiers modifiers, MethodAttributes flags, 
1662                                    IMethodData method, MethodBuilder builder,
1663                                    GenericMethod generic, MethodSpec parent_method)
1664                         : this (member, modifiers, flags, method)
1665                 {
1666                         this.builder = builder;
1667                         this.GenericMethod = generic;
1668                         this.parent_method = parent_method;
1669                 }
1670
1671                 public bool Define (DeclSpace parent, string method_full_name, Report Report)
1672                 {
1673                         TypeContainer container = parent.PartialContainer;
1674
1675                         PendingImplementation pending = container.PendingImplementations;
1676                         if (pending != null){
1677                                 implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this);
1678
1679                                 if (member.InterfaceType != null){
1680                                         if (implementing == null){
1681                                                 if (member is PropertyBase) {
1682                                                         Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
1683                                                                       method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
1684                                                                       member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
1685
1686                                                 } else {
1687                                                         Report.Error (539, method.Location,
1688                                                                       "`{0}.{1}' in explicit interface declaration is not a member of interface",
1689                                                                       TypeManager.CSharpName (member.InterfaceType), member.ShortName);
1690                                                 }
1691                                                 return false;
1692                                         }
1693                                         if (implementing.IsAccessor && !(method is AbstractPropertyEventMethod)) {
1694                                                 Report.SymbolRelatedToPreviousError (implementing);
1695                                                 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
1696                                                         member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1697                                                 return false;
1698                                         }
1699                                 } else {
1700                                         if (implementing != null) {
1701                                                 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
1702                                                 if (prop_method == null) {
1703                                                         if (implementing.IsAccessor) {
1704                                                                 Report.SymbolRelatedToPreviousError (implementing);
1705                                                                 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}'",
1706                                                                         method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
1707                                                         }
1708                                                 } else if (implementing.DeclaringType.IsInterface) {
1709                                                         if (!implementing.IsAccessor) {
1710                                                                 Report.SymbolRelatedToPreviousError (implementing);
1711                                                                 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
1712                                                                         method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
1713                                                         } else {
1714                                                                 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
1715                                                                 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
1716                                                                         Report.SymbolRelatedToPreviousError (implementing);
1717                                                                         Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
1718                                                                                 method.GetSignatureForError (), implementing.GetSignatureForError ());
1719                                                                 }
1720                                                         }
1721                                                 }
1722                                         }
1723                                 }
1724                         }
1725
1726                         //
1727                         // For implicit implementations, make sure we are public, for
1728                         // explicit implementations, make sure we are private.
1729                         //
1730                         if (implementing != null){
1731                                 //
1732                                 // Setting null inside this block will trigger a more
1733                                 // verbose error reporting for missing interface implementations
1734                                 //
1735                                 // The "candidate" function has been flagged already
1736                                 // but it wont get cleared
1737                                 //
1738                                 if (member.IsExplicitImpl){
1739                                         if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
1740                                                 Report.SymbolRelatedToPreviousError (implementing);
1741                                                 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
1742                                                         method.GetSignatureForError ());
1743                                         }
1744                                 } else {
1745                                         if (implementing.DeclaringType.IsInterface) {
1746                                                 //
1747                                                 // If this is an interface method implementation,
1748                                                 // check for public accessibility
1749                                                 //
1750                                                 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
1751                                                 {
1752                                                         implementing = null;
1753                                                 }
1754                                         } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
1755                                                 // We may never be private.
1756                                                 implementing = null;
1757
1758                                         } else if ((modifiers & Modifiers.OVERRIDE) == 0){
1759                                                 //
1760                                                 // We may be protected if we're overriding something.
1761                                                 //
1762                                                 implementing = null;
1763                                         }
1764                                 }
1765                                         
1766                                 //
1767                                 // Static is not allowed
1768                                 //
1769                                 if ((modifiers & Modifiers.STATIC) != 0){
1770                                         implementing = null;
1771                                 }
1772                         }
1773                         
1774                         //
1775                         // If implementing is still valid, set flags
1776                         //
1777                         if (implementing != null){
1778                                 //
1779                                 // When implementing interface methods, set NewSlot
1780                                 // unless, we are overwriting a method.
1781                                 //
1782                                 if (implementing.DeclaringType.IsInterface){
1783                                         if ((modifiers & Modifiers.OVERRIDE) == 0)
1784                                                 flags |= MethodAttributes.NewSlot;
1785                                 }
1786
1787                                 flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;
1788
1789                                 // Set Final unless we're virtual, abstract or already overriding a method.
1790                                 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
1791                                         flags |= MethodAttributes.Final;
1792
1793                                 //
1794                                 // clear the pending implementation flag (requires explicit methods to be defined first)
1795                                 //
1796                                 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName,
1797                                         member.InterfaceType, this, member.IsExplicitImpl);
1798
1799                                 //
1800                                 // Update indexer accessor name to match implementing abstract accessor
1801                                 //
1802                                 if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
1803                                         method_full_name = implementing.MemberDefinition.Name;
1804                         }
1805
1806                         DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
1807
1808                         if (builder == null)
1809                                 return false;
1810
1811 //                      if (container.CurrentType != null)
1812 //                              declaring_type = container.CurrentType;
1813 //                      else
1814                                 declaring_type = container.Definition;
1815
1816                         if (implementing != null && member.IsExplicitImpl) {
1817                                 container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
1818                         }
1819
1820                         return true;
1821                 }
1822
1823
1824                 /// <summary>
1825                 /// Create the MethodBuilder for the method 
1826                 /// </summary>
1827                 void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
1828                 {
1829                         var return_type = method.ReturnType.GetMetaInfo ();
1830                         var p_types = param.GetMetaInfo ();
1831
1832                         if (builder == null) {
1833                                 builder = container.TypeBuilder.DefineMethod (
1834                                         method_name, flags, method.CallingConventions,
1835                                         return_type, p_types);
1836                                 return;
1837                         }
1838
1839                         //
1840                         // Generic method has been already defined to resolve method parameters
1841                         // correctly when they use type parameters
1842                         //
1843                         builder.SetParameters (p_types);
1844                         builder.SetReturnType (return_type);
1845                         if (builder.Attributes != flags) {
1846                                 try {
1847                                         if (methodbuilder_attrs_field == null)
1848                                                 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
1849                                         methodbuilder_attrs_field.SetValue (builder, flags);
1850                                 } catch {
1851                                         container.Compiler.Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
1852                                 }
1853                         }
1854                 }
1855
1856                 //
1857                 // Emits the code
1858                 // 
1859                 public void Emit (DeclSpace parent)
1860                 {
1861                         if (GenericMethod != null)
1862                                 GenericMethod.EmitAttributes ();
1863
1864                         method.ParameterInfo.ApplyAttributes (MethodBuilder);
1865
1866                         SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
1867
1868                         ToplevelBlock block = method.Block;
1869                         if (block != null) {
1870                                 BlockContext bc = new BlockContext ((IMemberContext) method, block, method.ReturnType);
1871                                 if (block.Resolve (null, bc, method.ParameterInfo, method)) {
1872                                         EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator ());
1873                                         if (!ec.HasReturnLabel && bc.HasReturnLabel) {
1874                                                 ec.ReturnLabel = bc.ReturnLabel;
1875                                                 ec.HasReturnLabel = true;
1876                                         }
1877
1878                                         block.Emit (ec);
1879                                 }
1880                         }
1881
1882                         if (source != null) {
1883                                 method.EmitExtraSymbolInfo (source);
1884                                 source.CloseMethod ();
1885                         }
1886                 }
1887         }
1888
1889         public class Destructor : MethodOrOperator
1890         {
1891                 const Modifiers AllowedModifiers =
1892                         Modifiers.UNSAFE |
1893                         Modifiers.EXTERN;
1894
1895                 static readonly string[] attribute_targets = new string [] { "method" };
1896
1897                 public static readonly string MetadataName = "Finalize";
1898
1899                 public Destructor (DeclSpace parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
1900                         : base (parent, null, null, mod, AllowedModifiers,
1901                                 new MemberName (MetadataName, l), attrs, parameters)
1902                 {
1903                         ModFlags &= ~Modifiers.PRIVATE;
1904                         ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
1905                 }
1906
1907                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1908                 {
1909                         if (a.Type == pa.Conditional) {
1910                                 Error_ConditionalAttributeIsNotValid ();
1911                                 return;
1912                         }
1913
1914                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1915                 }
1916
1917                 protected override bool CheckBase ()
1918                 {
1919                         // Don't check base, destructors have special syntax
1920                         return true;
1921                 }
1922
1923                 public override void Emit()
1924                 {
1925                         var base_type = Parent.PartialContainer.BaseType;
1926                         if (base_type != null && Block != null) {
1927                                 var base_dtor = MemberCache.FindMember (base_type,
1928                                         new MemberFilter (MetadataName, 0, MemberKind.Destructor, null, null), BindingRestriction.InstanceOnly) as MethodSpec;
1929
1930                                 if (base_dtor == null)
1931                                         throw new NotImplementedException ();
1932
1933                                 MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
1934                                 method_expr.InstanceExpression = new BaseThis (base_type, Location);
1935
1936                                 ToplevelBlock new_block = new ToplevelBlock (Compiler, Block.StartLocation);
1937                                 new_block.EndLocation = Block.EndLocation;
1938
1939                                 Block finaly_block = new ExplicitBlock (new_block, Location, Location);
1940                                 Block try_block = new Block (new_block, block);
1941
1942                                 //
1943                                 // 0-size arguments to avoid CS0250 error
1944                                 // TODO: Should use AddScopeStatement or something else which emits correct
1945                                 // debugger scope
1946                                 //
1947                                 finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0))));
1948                                 new_block.AddStatement (new TryFinally (try_block, finaly_block, Location));
1949
1950                                 block = new_block;
1951                         }
1952
1953                         base.Emit ();
1954                 }
1955
1956                 public override string GetSignatureForError ()
1957                 {
1958                         return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
1959                 }
1960
1961                 protected override bool ResolveMemberType ()
1962                 {
1963                         member_type = TypeManager.void_type;
1964                         return true;
1965                 }
1966
1967                 public override string[] ValidAttributeTargets {
1968                         get {
1969                                 return attribute_targets;
1970                         }
1971                 }
1972         }
1973
1974         // Ooouh Martin, templates are missing here.
1975         // When it will be possible move here a lot of child code and template method type.
1976         public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
1977                 protected MethodData method_data;
1978                 protected ToplevelBlock block;
1979                 protected Dictionary<SecurityAction, PermissionSet> declarative_security;
1980
1981                 protected readonly string prefix;
1982
1983                 ReturnParameter return_attributes;
1984
1985                 public AbstractPropertyEventMethod (InterfaceMemberBase member, string prefix, Attributes attrs, Location loc)
1986                         : base (member.Parent, SetupName (prefix, member, loc), attrs)
1987                 {
1988                         this.prefix = prefix;
1989                 }
1990
1991                 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
1992                 {
1993                         return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
1994                 }
1995
1996                 public void UpdateName (InterfaceMemberBase member)
1997                 {
1998                         SetMemberName (SetupName (prefix, member, Location));
1999                 }
2000
2001                 #region IMethodData Members
2002
2003                 public ToplevelBlock Block {
2004                         get {
2005                                 return block;
2006                         }
2007
2008                         set {
2009                                 block = value;
2010                         }
2011                 }
2012
2013                 public CallingConventions CallingConventions {
2014                         get {
2015                                 return CallingConventions.Standard;
2016                         }
2017                 }
2018
2019                 public EmitContext CreateEmitContext (ILGenerator ig)
2020                 {
2021                         return new EmitContext (this, ig, ReturnType);
2022                 }
2023
2024                 public bool IsExcluded ()
2025                 {
2026                         return false;
2027                 }
2028
2029                 GenericMethod IMethodData.GenericMethod {
2030                         get {
2031                                 return null;
2032                         }
2033                 }
2034
2035                 public MemberName MethodName {
2036                         get {
2037                                 return MemberName;
2038                         }
2039                 }
2040
2041                 public TypeSpec[] ParameterTypes { 
2042                         get {
2043                                 return ParameterInfo.Types;
2044                         }
2045                 }
2046
2047                 public abstract ParametersCompiled ParameterInfo { get ; }
2048                 public abstract TypeSpec ReturnType { get; }
2049
2050                 #endregion
2051
2052                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2053                 {
2054                         if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
2055                                 Report.Error (1667, a.Location,
2056                                         "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
2057                                         TypeManager.CSharpName (a.Type), a.GetValidTargets ());
2058                                 return;
2059                         }
2060
2061                         if (a.IsValidSecurityAttribute ()) {
2062                                 if (declarative_security == null)
2063                                         declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
2064                                 a.ExtractSecurityPermissionSet (declarative_security);
2065                                 return;
2066                         }
2067
2068                         if (a.Target == AttributeTargets.Method) {
2069                                 method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
2070                                 return;
2071                         }
2072
2073                         if (a.Target == AttributeTargets.ReturnValue) {
2074                                 if (return_attributes == null)
2075                                         return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2076
2077                                 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
2078                                 return;
2079                         }
2080
2081                         ApplyToExtraTarget (a, ctor, cdata, pa);
2082                 }
2083
2084                 protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2085                 {
2086                         throw new NotSupportedException ("You forgot to define special attribute target handling");
2087                 }
2088
2089                 // It is not supported for the accessors
2090                 public sealed override bool Define()
2091                 {
2092                         throw new NotSupportedException ();
2093                 }
2094
2095                 public virtual void Emit (DeclSpace parent)
2096                 {
2097                         method_data.Emit (parent);
2098
2099                         if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
2100                                 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
2101                         if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
2102                                 PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
2103
2104                         if (ReturnType == InternalType.Dynamic) {
2105                                 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2106                                 PredefinedAttributes.Get.Dynamic.EmitAttribute (return_attributes.Builder);
2107                         } else {
2108                                 var trans_flags = TypeManager.HasDynamicTypeUsed (ReturnType);
2109                                 if (trans_flags != null) {
2110                                         var pa = PredefinedAttributes.Get.DynamicTransform;
2111                                         if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
2112                                                 return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
2113                                                 return_attributes.Builder.SetCustomAttribute (
2114                                                         new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
2115                                         }
2116                                 }
2117                         }
2118
2119                         if (OptAttributes != null)
2120                                 OptAttributes.Emit ();
2121
2122                         if (declarative_security != null) {
2123                                 foreach (var de in declarative_security) {
2124                                         method_data.MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2125                                 }
2126                         }
2127
2128                         block = null;
2129                 }
2130
2131                 public override bool EnableOverloadChecks (MemberCore overload)
2132                 {
2133                         if (overload is MethodCore) {
2134                                 caching_flags |= Flags.MethodOverloadsExist;
2135                                 return true;
2136                         }
2137
2138                         // This can only happen with indexers and it will
2139                         // be catched as indexer difference
2140                         if (overload is AbstractPropertyEventMethod)
2141                                 return true;
2142
2143                         return false;
2144                 }
2145
2146                 public override bool IsClsComplianceRequired()
2147                 {
2148                         return false;
2149                 }
2150
2151                 public MethodSpec Spec { get; protected set; }
2152
2153                 //
2154                 //   Represents header string for documentation comment.
2155                 //
2156                 public override string DocCommentHeader {
2157                         get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
2158                 }
2159
2160                 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
2161                 { }
2162         }
2163
2164         public class Operator : MethodOrOperator {
2165
2166                 const Modifiers AllowedModifiers =
2167                         Modifiers.PUBLIC |
2168                         Modifiers.UNSAFE |
2169                         Modifiers.EXTERN |
2170                         Modifiers.STATIC;
2171
2172                 public enum OpType : byte {
2173
2174                         // Unary operators
2175                         LogicalNot,
2176                         OnesComplement,
2177                         Increment,
2178                         Decrement,
2179                         True,
2180                         False,
2181
2182                         // Unary and Binary operators
2183                         Addition,
2184                         Subtraction,
2185
2186                         UnaryPlus,
2187                         UnaryNegation,
2188                         
2189                         // Binary operators
2190                         Multiply,
2191                         Division,
2192                         Modulus,
2193                         BitwiseAnd,
2194                         BitwiseOr,
2195                         ExclusiveOr,
2196                         LeftShift,
2197                         RightShift,
2198                         Equality,
2199                         Inequality,
2200                         GreaterThan,
2201                         LessThan,
2202                         GreaterThanOrEqual,
2203                         LessThanOrEqual,
2204
2205                         // Implicit and Explicit
2206                         Implicit,
2207                         Explicit,
2208
2209                         // Just because of enum
2210                         TOP
2211                 };
2212
2213                 public readonly OpType OperatorType;
2214
2215                 static readonly string [] [] names;
2216
2217                 static Operator ()
2218                 {
2219                         names = new string[(int)OpType.TOP][];
2220                         names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
2221                         names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
2222                         names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
2223                         names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
2224                         names [(int) OpType.True] = new string [] { "true", "op_True" };
2225                         names [(int) OpType.False] = new string [] { "false", "op_False" };
2226                         names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
2227                         names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
2228                         names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
2229                         names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
2230                         names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
2231                         names [(int) OpType.Division] = new string [] { "/", "op_Division" };
2232                         names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
2233                         names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
2234                         names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
2235                         names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
2236                         names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
2237                         names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
2238                         names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
2239                         names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
2240                         names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
2241                         names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
2242                         names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
2243                         names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
2244                         names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
2245                         names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
2246                 }
2247                 
2248                 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
2249                                  Modifiers mod_flags, ParametersCompiled parameters,
2250                                  ToplevelBlock block, Attributes attrs, Location loc)
2251                         : base (parent, null, ret_type, mod_flags, AllowedModifiers,
2252                                 new MemberName (GetMetadataName (type), loc), attrs, parameters)
2253                 {
2254                         OperatorType = type;
2255                         Block = block;
2256                 }
2257
2258                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2259                 {
2260                         if (a.Type == pa.Conditional) {
2261                                 Error_ConditionalAttributeIsNotValid ();
2262                                 return;
2263                         }
2264
2265                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2266                 }
2267                 
2268                 public override bool Define ()
2269                 {
2270                         const Modifiers RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
2271                         if ((ModFlags & RequiredModifiers) != RequiredModifiers){
2272                                 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
2273                         }
2274
2275                         if (!base.Define ())
2276                                 return false;
2277
2278                         if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
2279                                 //
2280                                 // Current method is turned into automatically generated
2281                                 // wrapper which creates an instance of iterator
2282                                 //
2283                                 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
2284                                 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
2285                         }
2286
2287                         // imlicit and explicit operator of same types are not allowed
2288                         if (OperatorType == OpType.Explicit)
2289                                 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
2290                         else if (OperatorType == OpType.Implicit)
2291                                 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
2292
2293                         TypeSpec declaring_type = Parent.CurrentType;
2294                         TypeSpec return_type = MemberType;
2295                         TypeSpec first_arg_type = ParameterTypes [0];
2296                         
2297                         TypeSpec first_arg_type_unwrap = first_arg_type;
2298                         if (TypeManager.IsNullableType (first_arg_type))
2299                                 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
2300                         
2301                         TypeSpec return_type_unwrap = return_type;
2302                         if (TypeManager.IsNullableType (return_type))
2303                                 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
2304
2305                         //
2306                         // Rules for conversion operators
2307                         //
2308                         if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2309                                 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type) {
2310                                         Report.Error (555, Location,
2311                                                 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
2312                                         return false;
2313                                 }
2314
2315                                 TypeSpec conv_type;
2316                                 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
2317                                         conv_type = first_arg_type;
2318                                 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
2319                                         conv_type = return_type;
2320                                 } else {
2321                                         Report.Error (556, Location,
2322                                                 "User-defined conversion must convert to or from the enclosing type");
2323                                         return false;
2324                                 }
2325
2326                                 if (conv_type == InternalType.Dynamic) {
2327                                         Report.Error (1964, Location,
2328                                                 "User-defined conversion `{0}' cannot convert to or from the dynamic type",
2329                                                 GetSignatureForError ());
2330
2331                                         return false;
2332                                 }
2333
2334                                 if (conv_type.IsInterface) {
2335                                         Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
2336                                                 GetSignatureForError ());
2337                                         return false;
2338                                 }
2339
2340                                 if (conv_type.IsClass) {
2341                                         if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
2342                                                 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
2343                                                         GetSignatureForError ());
2344                                                 return false;
2345                                         }
2346
2347                                         if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
2348                                                 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
2349                                                         GetSignatureForError ());
2350                                                 return false;
2351                                         }
2352                                 }
2353                         } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
2354                                 if (first_arg_type != declaring_type || parameters.Types[1] != TypeManager.int32_type) {
2355                                         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");
2356                                         return false;
2357                                 }
2358                         } else if (parameters.Count == 1) {
2359                                 // Checks for Unary operators
2360
2361                                 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
2362                                         if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
2363                                                 Report.Error (448, Location,
2364                                                         "The return type for ++ or -- operator must be the containing type or derived from the containing type");
2365                                                 return false;
2366                                         }
2367                                         if (first_arg_type != declaring_type) {
2368                                                 Report.Error (
2369                                                         559, Location, "The parameter type for ++ or -- operator must be the containing type");
2370                                                 return false;
2371                                         }
2372                                 }
2373
2374                                 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)) {
2375                                         Report.Error (562, Location,
2376                                                 "The parameter type of a unary operator must be the containing type");
2377                                         return false;
2378                                 }
2379
2380                                 if (OperatorType == OpType.True || OperatorType == OpType.False) {
2381                                         if (return_type != TypeManager.bool_type) {
2382                                                 Report.Error (
2383                                                         215, Location,
2384                                                         "The return type of operator True or False " +
2385                                                         "must be bool");
2386                                                 return false;
2387                                         }
2388                                 }
2389
2390                         } else if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)) {
2391                                 // Checks for Binary operators
2392
2393                                 var second_arg_type = ParameterTypes[1];
2394                                 if (TypeManager.IsNullableType (second_arg_type))
2395                                         second_arg_type = TypeManager.GetTypeArguments (second_arg_type)[0];
2396
2397                                 if (!TypeManager.IsEqual (second_arg_type, declaring_type)) {
2398                                         Report.Error (563, Location,
2399                                                 "One of the parameters of a binary operator must be the containing type");
2400                                         return false;
2401                                 }
2402                         }
2403
2404                         return true;
2405                 }
2406
2407                 protected override bool ResolveMemberType ()
2408                 {
2409                         if (!base.ResolveMemberType ())
2410                                 return false;
2411
2412                         flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2413                         return true;
2414                 }
2415
2416                 protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate)
2417                 {
2418                         // Operator cannot be override
2419                         bestCandidate = null;
2420                         return null;
2421                 }
2422
2423                 public static string GetName (OpType ot)
2424                 {
2425                         return names [(int) ot] [0];
2426                 }
2427
2428                 public static string GetName (string metadata_name)
2429                 {
2430                         for (int i = 0; i < names.Length; ++i) {
2431                                 if (names [i] [1] == metadata_name)
2432                                         return names [i] [0];
2433                         }
2434                         return null;
2435                 }
2436
2437                 public static string GetMetadataName (OpType ot)
2438                 {
2439                         return names [(int) ot] [1];
2440                 }
2441
2442                 public static string GetMetadataName (string name)
2443                 {
2444                         for (int i = 0; i < names.Length; ++i) {
2445                                 if (names [i] [0] == name)
2446                                         return names [i] [1];
2447                         }
2448                         return null;
2449                 }
2450
2451                 public static OpType? GetType (string metadata_name)
2452                 {
2453                         for (int i = 0; i < names.Length; ++i) {
2454                                 if (names[i][1] == metadata_name)
2455                                         return (OpType) i;
2456                         }
2457
2458                         return null;
2459                 }
2460
2461                 public OpType GetMatchingOperator ()
2462                 {
2463                         switch (OperatorType) {
2464                         case OpType.Equality:
2465                                 return OpType.Inequality;
2466                         case OpType.Inequality:
2467                                 return OpType.Equality;
2468                         case OpType.True:
2469                                 return OpType.False;
2470                         case OpType.False:
2471                                 return OpType.True;
2472                         case OpType.GreaterThan:
2473                                 return OpType.LessThan;
2474                         case OpType.LessThan:
2475                                 return OpType.GreaterThan;
2476                         case OpType.GreaterThanOrEqual:
2477                                 return OpType.LessThanOrEqual;
2478                         case OpType.LessThanOrEqual:
2479                                 return OpType.GreaterThanOrEqual;
2480                         default:
2481                                 return OpType.TOP;
2482                         }
2483                 }
2484
2485                 public override string GetSignatureForError ()
2486                 {
2487                         StringBuilder sb = new StringBuilder ();
2488                         if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2489                                 sb.AppendFormat ("{0}.{1} operator {2}",
2490                                         Parent.GetSignatureForError (), GetName (OperatorType), type_expr.GetSignatureForError ());
2491                         }
2492                         else {
2493                                 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
2494                         }
2495
2496                         sb.Append (parameters.GetSignatureForError ());
2497                         return sb.ToString ();
2498                 }
2499         }
2500 }
2501