Merge pull request #1412 from esdrubal/stackframe
[mono.git] / mcs / mcs / attribute.cs
1 //
2 // attribute.cs: Attributes handling
3 //
4 // Author: Ravi Pratap (ravi@ximian.com)
5 //         Marek Safar (marek.safar@gmail.com)
6 //
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 //
9 // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2003-2008 Novell, Inc.
11 // Copyright 2011-2013 Xamarin Inc
12 //
13
14 using System;
15 using System.Collections.Generic;
16 using System.Runtime.InteropServices;
17 using System.Runtime.CompilerServices;
18 using System.Security; 
19 using System.Security.Permissions;
20 using System.Text;
21 using System.IO;
22
23 #if STATIC
24 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
25 using BadImageFormat = IKVM.Reflection.BadImageFormatException;
26 using IKVM.Reflection;
27 using IKVM.Reflection.Emit;
28 #else
29 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
30 using BadImageFormat = System.BadImageFormatException;
31 using System.Reflection;
32 using System.Reflection.Emit;
33 #endif
34
35 namespace Mono.CSharp {
36
37         /// <summary>
38         ///   Base class for objects that can have Attributes applied to them.
39         /// </summary>
40         public abstract class Attributable {
41                 //
42                 // Holds all attributes attached to this element
43                 //
44                 protected Attributes attributes;
45
46                 public void AddAttributes (Attributes attrs, IMemberContext context)
47                 {
48                         if (attrs == null)
49                                 return;
50
51                         if (attributes == null)
52                                 attributes = attrs;
53                         else
54                                 attributes.AddAttributes (attrs.Attrs);
55
56                         attrs.AttachTo (this, context);
57                 }
58
59                 public Attributes OptAttributes {
60                         get {
61                                 return attributes;
62                         }
63                         set {
64                                 attributes = value;
65                         }
66                 }
67
68                 /// <summary>
69                 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
70                 /// </summary>
71                 public abstract void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa);
72
73                 /// <summary>
74                 /// Returns one AttributeTarget for this element.
75                 /// </summary>
76                 public abstract AttributeTargets AttributeTargets { get; }
77
78                 public abstract bool IsClsComplianceRequired ();
79
80                 /// <summary>
81                 /// Gets list of valid attribute targets for explicit target declaration.
82                 /// The first array item is default target. Don't break this rule.
83                 /// </summary>
84                 public abstract string[] ValidAttributeTargets { get; }
85         };
86
87         public class Attribute
88         {
89                 public readonly string ExplicitTarget;
90                 public AttributeTargets Target;
91                 readonly ATypeNameExpression expression;
92
93                 Arguments pos_args, named_args;
94
95                 bool resolve_error;
96                 bool arg_resolved;
97                 readonly bool nameEscaped;
98                 readonly Location loc;
99                 public TypeSpec Type;   
100
101                 //
102                 // An attribute can be attached to multiple targets (e.g. multiple fields)
103                 //
104                 Attributable[] targets;
105
106                 //
107                 // A member context for the attribute, it's much easier to hold it here
108                 // than trying to pull it during resolve
109                 //
110                 IMemberContext context;
111
112                 public static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
113                 public static readonly object[] EmptyObject = new object [0];
114
115                 List<KeyValuePair<MemberExpr, NamedArgument>> named_values;
116
117                 public Attribute (string target, ATypeNameExpression expr, Arguments[] args, Location loc, bool nameEscaped)
118                 {
119                         this.expression = expr;
120                         if (args != null) {
121                                 pos_args = args[0];
122                                 named_args = args[1];
123                         }
124                         this.loc = loc;
125                         ExplicitTarget = target;
126                         this.nameEscaped = nameEscaped;
127                 }
128
129                 public Location Location {
130                         get {
131                                 return loc;
132                         }
133                 }
134
135                 public Arguments NamedArguments {
136                         get {
137                                 return named_args;
138                         }
139                 }
140
141                 public Arguments PositionalArguments {
142                         get {
143                                 return pos_args;
144                         }
145                 }
146
147                 public bool ResolveError {
148                         get {
149                                 return resolve_error;
150                         }
151                 }
152
153                 public ATypeNameExpression TypeExpression {
154                         get {
155                                 return expression;
156                         }
157                 }
158
159                 void AddModuleCharSet (ResolveContext rc)
160                 {
161                         const string dll_import_char_set = "CharSet";
162
163                         //
164                         // Only when not customized by user
165                         //
166                         if (HasField (dll_import_char_set))
167                                 return;
168
169                         if (!rc.Module.PredefinedTypes.CharSet.Define ()) {
170                                 return;
171                         }
172
173                         if (NamedArguments == null)
174                                 named_args = new Arguments (1);
175
176                         var value = Constant.CreateConstantFromValue (rc.Module.PredefinedTypes.CharSet.TypeSpec, rc.Module.DefaultCharSet, Location);
177                         NamedArguments.Add (new NamedArgument (dll_import_char_set, loc, value));
178                 }
179
180                 public Attribute Clone ()
181                 {
182                         Attribute a = new Attribute (ExplicitTarget, expression, null, loc, nameEscaped);
183                         a.pos_args = pos_args;
184                         a.named_args = NamedArguments;
185                         return a;
186                 }
187
188                 //
189                 // When the same attribute is attached to multiple fiels
190                 // we use @target field as a list of targets. The attribute
191                 // has to be resolved only once but emitted for each target.
192                 //
193                 public void AttachTo (Attributable target, IMemberContext context)
194                 {
195                         if (this.targets == null) {
196                                 this.targets = new Attributable[] { target };
197                                 this.context = context;
198                                 return;
199                         }
200
201                         // When re-attaching global attributes
202                         if (context is NamespaceContainer) {
203                                 this.targets[0] = target;
204                                 this.context = context;
205                                 return;
206                         }
207
208                         // Resize target array
209                         Attributable[] new_array = new Attributable [this.targets.Length + 1];
210                         targets.CopyTo (new_array, 0);
211                         new_array [targets.Length] = target;
212                         this.targets = new_array;
213
214                         // No need to update context, different targets cannot have
215                         // different contexts, it's enough to remove same attributes
216                         // from secondary members.
217
218                         target.OptAttributes = null;
219                 }
220
221                 public ResolveContext CreateResolveContext ()
222                 {
223                         return new ResolveContext (context, ResolveContext.Options.ConstantScope);
224                 }
225
226                 static void Error_InvalidNamedArgument (ResolveContext rc, NamedArgument name)
227                 {
228                         rc.Report.Error (617, name.Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
229                                       "must be fields which are not readonly, static, const or read-write properties which are " +
230                                       "public and not static",
231                               name.Name);
232                 }
233
234                 static void Error_InvalidNamedArgumentType (ResolveContext rc, NamedArgument name)
235                 {
236                         rc.Report.Error (655, name.Location,
237                                 "`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type",
238                                 name.Name);
239                 }
240
241                 public static void Error_AttributeArgumentIsDynamic (IMemberContext context, Location loc)
242                 {
243                         context.Module.Compiler.Report.Error (1982, loc, "An attribute argument cannot be dynamic expression");
244                 }
245                 
246                 public void Error_MissingGuidAttribute ()
247                 {
248                         Report.Error (596, Location, "The Guid attribute must be specified with the ComImport attribute");
249                 }
250
251                 public void Error_MisusedExtensionAttribute ()
252                 {
253                         Report.Error (1112, Location, "Do not use `{0}' directly. Use parameter modifier `this' instead", GetSignatureForError ());
254                 }
255
256                 public void Error_MisusedDynamicAttribute ()
257                 {
258                         Report.Error (1970, loc, "Do not use `{0}' directly. Use `dynamic' keyword instead", GetSignatureForError ());
259                 }
260
261                 void Error_AttributeEmitError (string inner)
262                 {
263                         Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
264                                       Type.GetSignatureForError (), inner);
265                 }
266
267                 public void Error_InvalidArgumentValue (TypeSpec attributeType)
268                 {
269                         Report.Error (591, Location, "Invalid value for argument to `{0}' attribute", attributeType.GetSignatureForError ());
270                 }
271
272                 public void Error_InvalidSecurityParent ()
273                 {
274                         Report.Error (7070, Location,
275                                 "Security attribute `{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations",
276                                 Type.GetSignatureForError ());
277                 }
278
279                 Attributable Owner {
280                         get {
281                                 return targets [0];
282                         }
283                 }
284
285                 /// <summary>
286                 ///   Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
287                 /// </summary>
288                 void ResolveAttributeType (bool comparisonOnly)
289                 {
290                         var resolve_printer = new SessionReportPrinter ();
291                         SessionReportPrinter secondary_printer = null;
292                         ReportPrinter prev_recorder = Report.SetPrinter (resolve_printer);
293
294                         bool t1_is_attr = false;
295                         bool t2_is_attr = false;
296                         TypeSpec t1, t2;
297                         ATypeNameExpression expanded = null;
298
299                         // TODO: Additional warnings such as CS0436 are swallowed because we don't
300                         // print on success
301
302                         try {
303                                 t1 = expression.ResolveAsType (context);
304                                 resolve_printer.EndSession ();
305
306                                 if (t1 != null && resolve_printer.ErrorsCount == 0)
307                                         t1_is_attr = t1.IsAttribute;
308
309                                 if (nameEscaped) {
310                                         t2 = null;
311                                 } else {
312                                         expanded = (ATypeNameExpression) expression.Clone (null);
313                                         expanded.Name += "Attribute";
314
315                                         secondary_printer = new SessionReportPrinter ();
316                                         Report.SetPrinter (secondary_printer);
317                                         t2 = expanded.ResolveAsType (context);
318                                         secondary_printer.EndSession ();
319                                         if (t2 != null && secondary_printer.ErrorsCount == 0)
320                                                 t2_is_attr = t2.IsAttribute;
321
322                                         secondary_printer.EndSession ();
323                                 }
324                         } finally {
325                                 context.Module.Compiler.Report.SetPrinter (prev_recorder);
326                         }
327
328                         if (t1_is_attr && t2_is_attr && t1 != t2) {
329                                 if (!comparisonOnly) {
330                                         Report.Error (1614, Location, "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}Attribute'",
331                                                 GetSignatureForError (), expression.GetSignatureForError (), expanded.GetSignatureForError ());
332                                         resolve_error = true;
333                                 }
334
335                                 return;
336                         }
337
338                         if (t1_is_attr) {
339                                 Type = t1;
340                                 return;
341                         }
342
343                         if (t2_is_attr) {
344                                 Type = t2;
345                                 return;
346                         }
347
348                         if (comparisonOnly)
349                                 return;
350
351                         resolve_error = true;
352
353                         if (t1 != null) {       
354                                 if (resolve_printer.IsEmpty) {
355                                         Report.SymbolRelatedToPreviousError (t1);
356                                         Report.Error (616, Location, "`{0}': is not an attribute class", t1.GetSignatureForError ());
357                                 } else {
358                                         resolve_printer.Merge (prev_recorder);
359                                 }
360
361                                 return;
362                         }
363
364                         if (t2 != null) {
365                                 if (secondary_printer.IsEmpty) {
366                                         Report.SymbolRelatedToPreviousError (t2);
367                                         Report.Error (616, Location, "`{0}': is not an attribute class", t2.GetSignatureForError ());
368                                 } else {
369                                         secondary_printer.Merge (prev_recorder);
370                                 }
371
372                                 return;
373                         }
374
375                         resolve_printer.Merge (prev_recorder);
376                 }
377
378                 public TypeSpec ResolveTypeForComparison ()
379                 {
380                         if (Type == null && !resolve_error)
381                                 ResolveAttributeType (true);
382                         return Type;
383                 }
384
385                 public string GetSignatureForError ()
386                 {
387                         if (Type != null)
388                                 return Type.GetSignatureForError ();
389
390                         return expression.GetSignatureForError ();
391                 }
392
393                 public bool HasSecurityAttribute {
394                         get {
395                                 PredefinedAttribute pa = context.Module.PredefinedAttributes.Security;
396                                 return pa.IsDefined && TypeSpec.IsBaseClass (Type, pa.TypeSpec, false);
397                         }
398                 }
399
400                 public bool IsValidSecurityAttribute ()
401                 {
402                         return HasSecurityAttribute && IsSecurityActionValid ();
403                 }
404
405                 static bool IsValidMethodImplOption (int value)
406                 {
407                         //
408                         // Allow to use AggressiveInlining on any runtime/corlib
409                         //
410                         MethodImplOptions all = (MethodImplOptions) 256;
411                         foreach (MethodImplOptions v in System.Enum.GetValues (typeof (MethodImplOptions))) {
412                                 all |= v;
413                         }
414
415                         return ((MethodImplOptions) value | all) == all;
416                 }
417
418                 public static bool IsValidArgumentType (TypeSpec t)
419                 {
420                         if (t.IsArray) {
421                                 var ac = (ArrayContainer) t;
422                                 if (ac.Rank > 1)
423                                         return false;
424
425                                 t = ac.Element;
426                         }
427
428                         switch (t.BuiltinType) {
429                         case BuiltinTypeSpec.Type.Int:
430                         case BuiltinTypeSpec.Type.UInt:
431                         case BuiltinTypeSpec.Type.Long:
432                         case BuiltinTypeSpec.Type.ULong:
433                         case BuiltinTypeSpec.Type.Float:
434                         case BuiltinTypeSpec.Type.Double:
435                         case BuiltinTypeSpec.Type.Char:
436                         case BuiltinTypeSpec.Type.Short:
437                         case BuiltinTypeSpec.Type.Bool:
438                         case BuiltinTypeSpec.Type.SByte:
439                         case BuiltinTypeSpec.Type.Byte:
440                         case BuiltinTypeSpec.Type.UShort:
441
442                         case BuiltinTypeSpec.Type.String:
443                         case BuiltinTypeSpec.Type.Object:
444                         case BuiltinTypeSpec.Type.Dynamic:
445                         case BuiltinTypeSpec.Type.Type:
446                                 return true;
447                         }
448
449                         return t.IsEnum;
450                 }
451
452                 // TODO: Don't use this ambiguous value
453                 public string Name {
454                         get { return expression.Name; }
455                 }
456
457                 public Report Report {
458                         get { return context.Module.Compiler.Report; }
459                 }
460
461                 public MethodSpec Resolve ()
462                 {
463                         if (resolve_error)
464                                 return null;
465
466                         resolve_error = true;
467                         arg_resolved = true;
468
469                         if (Type == null) {
470                                 ResolveAttributeType (false);
471                                 if (Type == null)
472                                         return null;
473                         }
474
475                         if (Type.IsAbstract) {
476                                 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
477                                 return null;
478                         }
479
480                         ObsoleteAttribute obsolete_attr = Type.GetAttributeObsolete ();
481                         if (obsolete_attr != null) {
482                                 AttributeTester.Report_ObsoleteMessage (obsolete_attr, Type.GetSignatureForError (), Location, Report);
483                         }
484
485                         ResolveContext rc = null;
486
487                         MethodSpec ctor;
488                         // Try if the attribute is simple and has been resolved before
489                         if (pos_args != null || !context.Module.AttributeConstructorCache.TryGetValue (Type, out ctor)) {
490                                 rc = CreateResolveContext ();
491                                 ctor = ResolveConstructor (rc);
492                                 if (ctor == null) {
493                                         return null;
494                                 }
495
496                                 if (pos_args == null && ctor.Parameters.IsEmpty)
497                                         context.Module.AttributeConstructorCache.Add (Type, ctor);
498                         }
499
500                         //
501                         // Add [module: DefaultCharSet] to all DllImport import attributes
502                         //
503                         var module = context.Module;
504                         if ((Type == module.PredefinedAttributes.DllImport || Type == module.PredefinedAttributes.UnmanagedFunctionPointer) && module.HasDefaultCharSet) {
505                                 if (rc == null)
506                                         rc = CreateResolveContext ();
507
508                                 AddModuleCharSet (rc);
509                         }
510
511                         if (NamedArguments != null) {
512                                 if (rc == null)
513                                         rc = CreateResolveContext ();
514
515                                 if (!ResolveNamedArguments (rc))
516                                         return null;
517                         }
518
519                         resolve_error = false;
520                         return ctor;
521                 }
522
523                 MethodSpec ResolveConstructor (ResolveContext ec)
524                 {
525                         if (pos_args != null) {
526                                 bool dynamic;
527                                 pos_args.Resolve (ec, out dynamic);
528                                 if (dynamic) {
529                                         Error_AttributeArgumentIsDynamic (ec.MemberContext, loc);
530                                         return null;
531                                 }
532                         }
533
534                         return Expression.ConstructorLookup (ec, Type, ref pos_args, loc);
535                 }
536
537                 bool ResolveNamedArguments (ResolveContext ec)
538                 {
539                         int named_arg_count = NamedArguments.Count;
540                         var seen_names = new List<string> (named_arg_count);
541
542                         named_values = new List<KeyValuePair<MemberExpr, NamedArgument>> (named_arg_count);
543                         
544                         foreach (NamedArgument a in NamedArguments) {
545                                 string name = a.Name;
546                                 if (seen_names.Contains (name)) {
547                                         ec.Report.Error (643, a.Location, "Duplicate named attribute `{0}' argument", name);
548                                         continue;
549                                 }                       
550         
551                                 seen_names.Add (name);
552
553                                 a.Resolve (ec);
554
555                                 Expression member = Expression.MemberLookup (ec, false, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
556
557                                 if (member == null) {
558                                         member = Expression.MemberLookup (ec, true, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
559
560                                         if (member != null) {
561                                                 // TODO: ec.Report.SymbolRelatedToPreviousError (member);
562                                                 Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
563                                                 return false;
564                                         }
565                                 }
566
567                                 if (member == null){
568                                         Expression.Error_TypeDoesNotContainDefinition (ec, Location, Type, name);
569                                         return false;
570                                 }
571                                 
572                                 if (!(member is PropertyExpr || member is FieldExpr)) {
573                                         Error_InvalidNamedArgument (ec, a);
574                                         return false;
575                                 }
576
577                                 ObsoleteAttribute obsolete_attr;
578
579                                 if (member is PropertyExpr) {
580                                         var pi = ((PropertyExpr) member).PropertyInfo;
581
582                                         if (!pi.HasSet || !pi.HasGet || pi.IsStatic || !pi.Get.IsPublic || !pi.Set.IsPublic) {
583                                                 ec.Report.SymbolRelatedToPreviousError (pi);
584                                                 Error_InvalidNamedArgument (ec, a);
585                                                 return false;
586                                         }
587
588                                         if (!IsValidArgumentType (member.Type)) {
589                                                 ec.Report.SymbolRelatedToPreviousError (pi);
590                                                 Error_InvalidNamedArgumentType (ec, a);
591                                                 return false;
592                                         }
593
594                                         obsolete_attr = pi.GetAttributeObsolete ();
595                                         pi.MemberDefinition.SetIsAssigned ();
596                                 } else {
597                                         var fi = ((FieldExpr) member).Spec;
598
599                                         if (fi.IsReadOnly || fi.IsStatic || !fi.IsPublic) {
600                                                 Error_InvalidNamedArgument (ec, a);
601                                                 return false;
602                                         }
603
604                                         if (!IsValidArgumentType (member.Type)) {
605                                                 ec.Report.SymbolRelatedToPreviousError (fi);
606                                                 Error_InvalidNamedArgumentType (ec, a);
607                                                 return false;
608                                         }
609
610                                         obsolete_attr = fi.GetAttributeObsolete ();
611                                         fi.MemberDefinition.SetIsAssigned ();
612                                 }
613
614                                 if (obsolete_attr != null && !context.IsObsolete)
615                                         AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location, Report);
616
617                                 if (a.Type != member.Type) {
618                                         a.Expr = Convert.ImplicitConversionRequired (ec, a.Expr, member.Type, a.Expr.Location);
619                                 }
620
621                                 if (a.Expr != null)
622                                         named_values.Add (new KeyValuePair<MemberExpr, NamedArgument> ((MemberExpr) member, a));
623                         }
624
625                         return true;
626                 }
627
628                 /// <summary>
629                 ///   Get a string containing a list of valid targets for the attribute 'attr'
630                 /// </summary>
631                 public string GetValidTargets ()
632                 {
633                         StringBuilder sb = new StringBuilder ();
634                         AttributeTargets targets = Type.GetAttributeUsage (context.Module.PredefinedAttributes.AttributeUsage).ValidOn;
635
636                         if ((targets & AttributeTargets.Assembly) != 0)
637                                 sb.Append ("assembly, ");
638
639                         if ((targets & AttributeTargets.Module) != 0)
640                                 sb.Append ("module, ");
641
642                         if ((targets & AttributeTargets.Class) != 0)
643                                 sb.Append ("class, ");
644
645                         if ((targets & AttributeTargets.Struct) != 0)
646                                 sb.Append ("struct, ");
647
648                         if ((targets & AttributeTargets.Enum) != 0)
649                                 sb.Append ("enum, ");
650
651                         if ((targets & AttributeTargets.Constructor) != 0)
652                                 sb.Append ("constructor, ");
653
654                         if ((targets & AttributeTargets.Method) != 0)
655                                 sb.Append ("method, ");
656
657                         if ((targets & AttributeTargets.Property) != 0)
658                                 sb.Append ("property, indexer, ");
659
660                         if ((targets & AttributeTargets.Field) != 0)
661                                 sb.Append ("field, ");
662
663                         if ((targets & AttributeTargets.Event) != 0)
664                                 sb.Append ("event, ");
665
666                         if ((targets & AttributeTargets.Interface) != 0)
667                                 sb.Append ("interface, ");
668
669                         if ((targets & AttributeTargets.Parameter) != 0)
670                                 sb.Append ("parameter, ");
671
672                         if ((targets & AttributeTargets.Delegate) != 0)
673                                 sb.Append ("delegate, ");
674
675                         if ((targets & AttributeTargets.ReturnValue) != 0)
676                                 sb.Append ("return, ");
677
678                         if ((targets & AttributeTargets.GenericParameter) != 0)
679                                 sb.Append ("type parameter, ");
680
681                         return sb.Remove (sb.Length - 2, 2).ToString ();
682                 }
683
684                 public AttributeUsageAttribute GetAttributeUsageAttribute ()
685                 {
686                         if (!arg_resolved)
687                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
688                                 // But because a lot of attribute class code must be rewritten will be better to wait...
689                                 Resolve ();
690
691                         if (resolve_error)
692                                 return DefaultUsageAttribute;
693
694                         AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets) ((Constant) pos_args[0].Expr).GetValue ());
695
696                         var field = GetNamedValue ("AllowMultiple") as BoolConstant;
697                         if (field != null)
698                                 usage_attribute.AllowMultiple = field.Value;
699
700                         field = GetNamedValue ("Inherited") as BoolConstant;
701                         if (field != null)
702                                 usage_attribute.Inherited = field.Value;
703
704                         return usage_attribute;
705                 }
706
707                 /// <summary>
708                 /// Returns custom name of indexer
709                 /// </summary>
710                 public string GetIndexerAttributeValue ()
711                 {
712                         if (!arg_resolved)
713                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
714                                 // But because a lot of attribute class code must be rewritten will be better to wait...
715                                 Resolve ();
716
717                         if (resolve_error || pos_args.Count != 1 || !(pos_args[0].Expr is Constant))
718                                 return null;
719
720                         return ((Constant) pos_args[0].Expr).GetValue () as string;
721                 }
722
723                 /// <summary>
724                 /// Returns condition of ConditionalAttribute
725                 /// </summary>
726                 public string GetConditionalAttributeValue ()
727                 {
728                         if (!arg_resolved)
729                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
730                                 // But because a lot of attribute class code must be rewritten will be better to wait...
731                                 Resolve ();
732
733                         if (resolve_error)
734                                 return null;
735
736                         return ((Constant) pos_args[0].Expr).GetValue () as string;
737                 }
738
739                 /// <summary>
740                 /// Creates the instance of ObsoleteAttribute from this attribute instance
741                 /// </summary>
742                 public ObsoleteAttribute GetObsoleteAttribute ()
743                 {
744                         if (!arg_resolved) {
745                                 // corlib only case when obsolete is used before is resolved
746                                 var c = Type.MemberDefinition as Class;
747                                 if (c != null && !c.HasMembersDefined)
748                                         c.Define ();
749                                 
750                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
751                                 // But because a lot of attribute class code must be rewritten will be better to wait...
752                                 Resolve ();
753                         }
754
755                         if (resolve_error)
756                                 return null;
757
758                         if (pos_args == null)
759                                 return new ObsoleteAttribute ();
760
761                         string msg = ((Constant) pos_args[0].Expr).GetValue () as string;
762                         if (pos_args.Count == 1)
763                                 return new ObsoleteAttribute (msg);
764
765                         return new ObsoleteAttribute (msg, ((BoolConstant) pos_args[1].Expr).Value);
766                 }
767
768                 /// <summary>
769                 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
770                 /// before ApplyAttribute. We need to resolve the arguments.
771                 /// This situation occurs when class deps is differs from Emit order.  
772                 /// </summary>
773                 public bool GetClsCompliantAttributeValue ()
774                 {
775                         if (!arg_resolved)
776                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
777                                 // But because a lot of attribute class code must be rewritten will be better to wait...
778                                 Resolve ();
779
780                         if (resolve_error)
781                                 return false;
782
783                         return ((BoolConstant) pos_args[0].Expr).Value;
784                 }
785
786                 public TypeSpec GetCoClassAttributeValue ()
787                 {
788                         if (!arg_resolved)
789                                 Resolve ();
790
791                         if (resolve_error)
792                                 return null;
793
794                         return GetArgumentType ();
795                 }
796
797                 public bool CheckTarget ()
798                 {
799                         string[] valid_targets = Owner.ValidAttributeTargets;
800                         if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
801                                 Target = Owner.AttributeTargets;
802                                 return true;
803                         }
804
805                         // TODO: we can skip the first item
806                         if (Array.Exists (valid_targets, i => i == ExplicitTarget)) {
807                                 switch (ExplicitTarget) {
808                                 case "return": Target = AttributeTargets.ReturnValue; return true;
809                                 case "param": Target = AttributeTargets.Parameter; return true;
810                                 case "field": Target = AttributeTargets.Field; return true;
811                                 case "method": Target = AttributeTargets.Method; return true;
812                                 case "property": Target = AttributeTargets.Property; return true;
813                                 case "module": Target = AttributeTargets.Module; return true;
814                                 }
815                                 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
816                         }
817                                 
818                         StringBuilder sb = new StringBuilder ();
819                         foreach (string s in valid_targets) {
820                                 sb.Append (s);
821                                 sb.Append (", ");
822                         }
823                         sb.Remove (sb.Length - 2, 2);
824                         Report.Warning (657, 1, Location,
825                                 "`{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are `{1}'. All attributes in this section will be ignored",
826                                 ExplicitTarget, sb.ToString ());
827                         return false;
828                 }
829
830                 /// <summary>
831                 /// Tests permitted SecurityAction for assembly or other types
832                 /// </summary>
833                 bool IsSecurityActionValid ()
834                 {
835                         Constant c = null;
836                         var action = GetSecurityActionValue (ref c);
837                         bool for_assembly = Target == AttributeTargets.Assembly || Target == AttributeTargets.Module;
838
839                         switch (action) {
840 #pragma warning disable 618
841                         case SecurityAction.Demand:
842                         case SecurityAction.Assert:
843                         case SecurityAction.Deny:
844                         case SecurityAction.PermitOnly:
845                         case SecurityAction.LinkDemand:
846                         case SecurityAction.InheritanceDemand:
847                                 if (!for_assembly)
848                                         return true;
849                                 break;
850
851                         case SecurityAction.RequestMinimum:
852                         case SecurityAction.RequestOptional:
853                         case SecurityAction.RequestRefuse:
854                                 if (for_assembly)
855                                         return true;
856                                 break;
857 #pragma warning restore 618
858                         case null:
859                                 Report.Error (7048, loc, "First argument of a security attribute `{0}' must be a valid SecurityAction",
860                                         Type.GetSignatureForError ());
861                                 return false;
862
863                         default:
864                                 Report.Error (7049, c.Location, "Security attribute `{0}' has an invalid SecurityAction value `{1}'",
865                                         Type.GetSignatureForError (), c.GetValueAsLiteral());
866                                 return false;
867                         }
868
869                         switch (Target) {
870                         case AttributeTargets.Assembly:
871                                 Report.Error (7050, c.Location, "SecurityAction value `{0}' is invalid for security attributes applied to an assembly",
872                                         c.GetSignatureForError ());
873                                 break;
874                         default:
875                                 Report.Error (7051, c.Location, "SecurityAction value `{0}' is invalid for security attributes applied to a type or a method",
876                                         c.GetSignatureForError ());
877                                 break;
878                         }
879
880                         return false;
881                 }
882
883                 SecurityAction? GetSecurityActionValue (ref Constant value)
884                 {
885                         if (pos_args == null) {
886                                 var predefined = context.Module.PredefinedAttributes;
887
888                                 //
889                                 // BCL defines System.Security.Permissions.HostProtectionAttribute with parameterless
890                                 // contructor which should not be valid but it's already part of the framework
891                                 //
892                                 if (Type == predefined.HostProtection.TypeSpec) {
893                                         value = new IntConstant (context.Module.Compiler.BuiltinTypes, (int)SecurityAction.LinkDemand, loc);
894                                         return SecurityAction.LinkDemand;
895                                 }
896
897                                 return null;
898                         }
899
900                         value = (Constant) pos_args [0].Expr;
901                         return (SecurityAction) value.GetValue ();
902                 }
903
904                 /// <summary>
905                 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
906                 /// </summary>
907                 /// <returns></returns>
908                 public void ExtractSecurityPermissionSet (MethodSpec ctor, ref SecurityType permissions)
909                 {
910 #if STATIC
911                         object[] values;
912                         if (pos_args != null) {
913                                 values = new object[pos_args.Count];
914                                 for (int i = 0; i < values.Length; ++i)
915                                         values[i] = ((Constant) pos_args[i].Expr).GetValue ();
916                         } else {
917                                 values = null;
918                         }
919
920                         PropertyInfo[] prop;
921                         object[] prop_values;
922                         if (named_values == null) {
923                                 prop = null;
924                                 prop_values = null;
925                         } else {
926                                 prop = new PropertyInfo[named_values.Count];
927                                 prop_values = new object [named_values.Count];
928                                 for (int i = 0; i < prop.Length; ++i) {
929                                         prop [i] = ((PropertyExpr) named_values [i].Key).PropertyInfo.MetaInfo;
930                                         prop_values [i] = ((Constant) named_values [i].Value.Expr).GetValue ();
931                                 }
932                         }
933
934                         if (permissions == null)
935                                 permissions = new SecurityType ();
936
937                         var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), values, prop, prop_values);
938                         permissions.Add (cab);
939 #else
940                         throw new NotSupportedException ();
941 #endif
942                 }
943
944                 public Constant GetNamedValue (string name)
945                 {
946                         if (named_values == null)
947                                 return null;
948
949                         for (int i = 0; i < named_values.Count; ++i) {
950                                 if (named_values [i].Value.Name == name)
951                                         return named_values [i].Value.Expr as Constant;
952                         }
953
954                         return null;
955                 }
956
957                 public CharSet GetCharSetValue ()
958                 {
959                         return (CharSet) System.Enum.Parse (typeof (CharSet), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
960                 }
961
962                 public bool HasField (string fieldName)
963                 {
964                         if (named_values == null)
965                                 return false;
966
967                         foreach (var na in named_values) {
968                                 if (na.Value.Name == fieldName)
969                                         return true;
970                         }
971
972                         return false;
973                 }
974
975                 //
976                 // Returns true for MethodImplAttribute with MethodImplOptions.InternalCall value
977                 // 
978                 public bool IsInternalCall ()
979                 {
980                         return (GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0;
981                 }
982
983                 public MethodImplOptions GetMethodImplOptions ()
984                 {
985                         MethodImplOptions options = 0;
986                         if (pos_args.Count == 1) {
987                                 options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
988                         } else if (HasField ("Value")) {
989                                 var named = GetNamedValue ("Value");
990                                 options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), named.GetValue ().ToString ());
991                         }
992
993                         return options;
994                 }
995
996                 //
997                 // Returns true for StructLayoutAttribute with LayoutKind.Explicit value
998                 // 
999                 public bool IsExplicitLayoutKind ()
1000                 {
1001                         if (pos_args == null || pos_args.Count != 1)
1002                                 return false;
1003
1004                         var value = (LayoutKind) System.Enum.Parse (typeof (LayoutKind), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
1005                         return value == LayoutKind.Explicit;
1006                 }
1007
1008                 public Expression GetParameterDefaultValue ()
1009                 {
1010                         if (pos_args == null)
1011                                 return null;
1012
1013                         return pos_args[0].Expr;
1014                 }
1015
1016                 public override bool Equals (object obj)
1017                 {
1018                         Attribute a = obj as Attribute;
1019                         if (a == null)
1020                                 return false;
1021
1022                         return Type == a.Type && Target == a.Target;
1023                 }
1024
1025                 public override int GetHashCode ()
1026                 {
1027                         return Type.GetHashCode () ^ Target.GetHashCode ();
1028                 }
1029
1030                 /// <summary>
1031                 /// Emit attribute for Attributable symbol
1032                 /// </summary>
1033                 public void Emit (Dictionary<Attribute, List<Attribute>> allEmitted)
1034                 {
1035                         var ctor = Resolve ();
1036                         if (ctor == null)
1037                                 return;
1038
1039                         var predefined = context.Module.PredefinedAttributes;
1040
1041                         AttributeUsageAttribute usage_attr = Type.GetAttributeUsage (predefined.AttributeUsage);
1042                         if ((usage_attr.ValidOn & Target) == 0) {
1043                                 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1044                                               "It is valid on `{1}' declarations only",
1045                                         GetSignatureForError (), GetValidTargets ());
1046                                 return;
1047                         }
1048
1049                         byte[] cdata;
1050                         if (pos_args == null && named_values == null) {
1051                                 cdata = AttributeEncoder.Empty;
1052                         } else {
1053                                 AttributeEncoder encoder = new AttributeEncoder ();
1054
1055                                 if (pos_args != null) {
1056                                         var param_types = ctor.Parameters.Types;
1057                                         for (int j = 0; j < pos_args.Count; ++j) {
1058                                                 var pt = param_types[j];
1059                                                 var arg_expr = pos_args[j].Expr;
1060                                                 if (j == 0) {
1061                                                         if ((Type == predefined.IndexerName || Type == predefined.Conditional) && arg_expr is Constant) {
1062                                                                 string v = ((Constant) arg_expr).GetValue () as string;
1063                                                                 if (!Tokenizer.IsValidIdentifier (v) || (Type == predefined.IndexerName && Tokenizer.IsKeyword (v))) {
1064                                                                         context.Module.Compiler.Report.Error (633, arg_expr.Location,
1065                                                                                 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
1066                                                                         return;
1067                                                                 }
1068                                                         } else if (Type == predefined.Guid) {
1069                                                                 string v = ((StringConstant) arg_expr).Value;
1070                                                                 try {
1071                                                                         new Guid (v);
1072                                                                 } catch {
1073                                                                         Error_InvalidArgumentValue (Type);
1074                                                                         return;
1075                                                                 }
1076                                                         } else if (Type == predefined.AttributeUsage) {
1077                                                                 int v = ((IntConstant) ((EnumConstant) arg_expr).Child).Value;
1078                                                                 if (v == 0)
1079                                                                         Error_InvalidArgumentValue (Type);
1080                                                         } else if (Type == predefined.MarshalAs) {
1081                                                                 if (pos_args.Count == 1) {
1082                                                                         var u_type = (UnmanagedType) System.Enum.Parse (typeof (UnmanagedType), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
1083                                                                         if (u_type == UnmanagedType.ByValArray && !(Owner is FieldBase)) {
1084                                                                                 Report.Error (7055, pos_args [0].Expr.Location, "Unmanaged type `ByValArray' is only valid for fields");
1085                                                                         }
1086                                                                 }
1087                                                         } else if (Type == predefined.DllImport) {
1088                                                                 if (pos_args.Count == 1 && pos_args[0].Expr is Constant) {
1089                                                                         var value = ((Constant) pos_args[0].Expr).GetValue () as string;
1090                                                                         if (string.IsNullOrEmpty (value))
1091                                                                                 Error_InvalidArgumentValue (Type);
1092                                                                 }
1093                                                         } else if (Type == predefined.MethodImpl) {
1094                                                                 if (pos_args.Count == 1) {
1095                                                                         var value = (int) ((Constant) arg_expr).GetValueAsLong ();
1096
1097                                                                         if (!IsValidMethodImplOption (value)) {
1098                                                                                 Error_InvalidArgumentValue (Type);
1099                                                                         }
1100                                                                 }
1101                                                         }
1102                                                 }
1103
1104                                                 arg_expr.EncodeAttributeValue (context, encoder, pt, pt);
1105                                         }
1106                                 }
1107
1108                                 if (named_values != null) {
1109                                         encoder.Encode ((ushort) named_values.Count);
1110                                         foreach (var na in named_values) {
1111                                                 if (na.Key is FieldExpr)
1112                                                         encoder.Encode ((byte) 0x53);
1113                                                 else
1114                                                         encoder.Encode ((byte) 0x54);
1115
1116                                                 encoder.Encode (na.Key.Type);
1117                                                 encoder.Encode (na.Value.Name);
1118                                                 na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type, na.Key.Type);
1119                                         }
1120                                 } else {
1121                                         encoder.EncodeEmptyNamedArguments ();
1122                                 }
1123
1124                                 cdata = encoder.ToArray ();
1125                         }
1126
1127                         if (!ctor.DeclaringType.IsConditionallyExcluded (context)) {
1128                                 try {
1129                                         foreach (Attributable target in targets)
1130                                                 target.ApplyAttributeBuilder (this, ctor, cdata, predefined);
1131                                 } catch (Exception e) {
1132                                         if (e is BadImageFormat && Report.Errors > 0)
1133                                                 return;
1134
1135                                         Error_AttributeEmitError (e.Message);
1136                                         return;
1137                                 }
1138                         }
1139
1140                         if (!usage_attr.AllowMultiple && allEmitted != null) {
1141                                 if (allEmitted.ContainsKey (this)) {
1142                                         var a = allEmitted [this];
1143                                         if (a == null) {
1144                                                 a = new List<Attribute> (2);
1145                                                 allEmitted [this] = a;
1146                                         }
1147                                         a.Add (this);
1148                                 } else {
1149                                         allEmitted.Add (this, null);
1150                                 }
1151                         }
1152
1153                         if (!context.Module.Compiler.Settings.VerifyClsCompliance)
1154                                 return;
1155
1156                         // Here we are testing attribute arguments for array usage (error 3016)
1157                         if (Owner.IsClsComplianceRequired ()) {
1158                                 if (pos_args != null)
1159                                         pos_args.CheckArrayAsAttribute (context.Module.Compiler);
1160                         
1161                                 if (NamedArguments == null)
1162                                         return;
1163
1164                                 NamedArguments.CheckArrayAsAttribute (context.Module.Compiler);
1165                         }
1166                 }
1167
1168                 private Expression GetValue () 
1169                 {
1170                         if (pos_args == null || pos_args.Count < 1)
1171                                 return null;
1172
1173                         return pos_args[0].Expr;
1174                 }
1175
1176                 public string GetString () 
1177                 {
1178                         Expression e = GetValue ();
1179                         if (e is StringConstant)
1180                                 return ((StringConstant)e).Value;
1181                         return null;
1182                 }
1183
1184                 public bool GetBoolean () 
1185                 {
1186                         Expression e = GetValue ();
1187                         if (e is BoolConstant)
1188                                 return ((BoolConstant)e).Value;
1189                         return false;
1190                 }
1191
1192                 public TypeSpec GetArgumentType ()
1193                 {
1194                         TypeOf e = GetValue () as TypeOf;
1195                         if (e == null)
1196                                 return null;
1197                         return e.TypeArgument;
1198                 }
1199         }
1200         
1201         public class Attributes
1202         {
1203                 public readonly List<Attribute> Attrs;
1204
1205                 public Attributes (Attribute a)
1206                 {
1207                         Attrs = new List<Attribute> ();
1208                         Attrs.Add (a);
1209                 }
1210
1211                 public Attributes (List<Attribute> attrs)
1212                 {
1213                         Attrs = attrs ?? new List<Attribute> ();
1214                 }
1215
1216                 public void AddAttribute (Attribute attr)
1217                 {
1218                         Attrs.Add (attr);
1219                 }
1220
1221                 public void AddAttributes (List<Attribute> attrs)
1222                 {
1223                         Attrs.AddRange (attrs);
1224                 }
1225
1226                 public void AttachTo (Attributable attributable, IMemberContext context)
1227                 {
1228                         foreach (Attribute a in Attrs)
1229                                 a.AttachTo (attributable, context);
1230                 }
1231
1232                 public Attributes Clone ()
1233                 {
1234                         var al = new List<Attribute> (Attrs.Count);
1235                         foreach (Attribute a in Attrs)
1236                                 al.Add (a.Clone ());
1237
1238                         return new Attributes (al);
1239                 }
1240
1241                 /// <summary>
1242                 /// Checks whether attribute target is valid for the current element
1243                 /// </summary>
1244                 public bool CheckTargets ()
1245                 {
1246                         for (int i = 0; i < Attrs.Count; ++i) {
1247                                 if (!Attrs [i].CheckTarget ())
1248                                         Attrs.RemoveAt (i--);
1249                         }
1250
1251                         return true;
1252                 }
1253
1254                 public void ConvertGlobalAttributes (TypeContainer member, NamespaceContainer currentNamespace, bool isGlobal)
1255                 {
1256                         var member_explicit_targets = member.ValidAttributeTargets;
1257                         for (int i = 0; i < Attrs.Count; ++i) {
1258                                 var attr = Attrs[0];
1259                                 if (attr.ExplicitTarget == null)
1260                                         continue;
1261
1262                                 int ii;
1263                                 for (ii = 0; ii < member_explicit_targets.Length; ++ii) {
1264                                         if (attr.ExplicitTarget == member_explicit_targets[ii]) {
1265                                                 ii = -1;
1266                                                 break;
1267                                         }
1268                                 }
1269
1270                                 if (ii < 0 || !isGlobal)
1271                                         continue;
1272
1273                                 member.Module.AddAttribute (attr, currentNamespace);
1274                                 Attrs.RemoveAt (i);
1275                                 --i;
1276                         }
1277                 }
1278
1279                 public bool HasResolveError()
1280                 {
1281                         foreach (var a in Attrs) {
1282                                 if (a.ResolveError)
1283                                         return true;
1284                         }
1285
1286                         return false;
1287                 }
1288
1289                 public Attribute Search (PredefinedAttribute t)
1290                 {
1291                         return Search (null, t);
1292                 }
1293
1294                 public Attribute Search (string explicitTarget, PredefinedAttribute t)
1295                 {
1296                         foreach (Attribute a in Attrs) {
1297                                 if (explicitTarget != null && a.ExplicitTarget != explicitTarget)
1298                                         continue;
1299
1300                                 if (a.ResolveTypeForComparison () == t)
1301                                         return a;
1302                         }
1303                         return null;
1304                 }
1305
1306                 /// <summary>
1307                 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1308                 /// </summary>
1309                 public Attribute[] SearchMulti (PredefinedAttribute t)
1310                 {
1311                         List<Attribute> ar = null;
1312
1313                         foreach (Attribute a in Attrs) {
1314                                 if (a.ResolveTypeForComparison () == t) {
1315                                         if (ar == null)
1316                                                 ar = new List<Attribute> (Attrs.Count);
1317                                         ar.Add (a);
1318                                 }
1319                         }
1320
1321                         return ar == null ? null : ar.ToArray ();
1322                 }
1323
1324                 public void Emit ()
1325                 {
1326                         CheckTargets ();
1327
1328                         Dictionary<Attribute, List<Attribute>> ld = Attrs.Count > 1 ? new Dictionary<Attribute, List<Attribute>> () : null;
1329
1330                         foreach (Attribute a in Attrs)
1331                                 a.Emit (ld);
1332
1333                         if (ld == null || ld.Count == 0)
1334                                 return;
1335
1336                         foreach (var d in ld) {
1337                                 if (d.Value == null)
1338                                         continue;
1339
1340                                 Attribute a = d.Key;
1341
1342                                 foreach (Attribute collision in d.Value)
1343                                         a.Report.SymbolRelatedToPreviousError (collision.Location, "");
1344
1345                                 a.Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1346                                         a.GetSignatureForError ());
1347                         }
1348                 }
1349
1350                 public bool Contains (PredefinedAttribute t)
1351                 {
1352                         return Search (t) != null;
1353                 }
1354         }
1355
1356         public sealed class AttributeEncoder
1357         {
1358                 [Flags]
1359                 public enum EncodedTypeProperties
1360                 {
1361                         None = 0,
1362                         DynamicType = 1,
1363                         TypeParameter = 1 << 1
1364                 }
1365
1366                 public static readonly byte[] Empty;
1367
1368                 byte[] buffer;
1369                 int pos;
1370                 const ushort Version = 1;
1371
1372                 static AttributeEncoder ()
1373                 {
1374                         Empty = new byte[4];
1375                         Empty[0] = (byte) Version;
1376                 }
1377
1378                 public AttributeEncoder ()
1379                 {
1380                         buffer = new byte[32];
1381                         Encode (Version);
1382                 }
1383
1384                 public void Encode (bool value)
1385                 {
1386                         Encode (value ? (byte) 1 : (byte) 0);
1387                 }
1388
1389                 public void Encode (byte value)
1390                 {
1391                         if (pos == buffer.Length)
1392                                 Grow (1);
1393
1394                         buffer [pos++] = value;
1395                 }
1396
1397                 public void Encode (sbyte value)
1398                 {
1399                         Encode ((byte) value);
1400                 }
1401
1402                 public void Encode (short value)
1403                 {
1404                         if (pos + 2 > buffer.Length)
1405                                 Grow (2);
1406
1407                         buffer[pos++] = (byte) value;
1408                         buffer[pos++] = (byte) (value >> 8);
1409                 }
1410
1411                 public void Encode (ushort value)
1412                 {
1413                         Encode ((short) value);
1414                 }
1415
1416                 public void Encode (int value)
1417                 {
1418                         if (pos + 4 > buffer.Length)
1419                                 Grow (4);
1420
1421                         buffer[pos++] = (byte) value;
1422                         buffer[pos++] = (byte) (value >> 8);
1423                         buffer[pos++] = (byte) (value >> 16);
1424                         buffer[pos++] = (byte) (value >> 24);
1425                 }
1426
1427                 public void Encode (uint value)
1428                 {
1429                         Encode ((int) value);
1430                 }
1431
1432                 public void Encode (long value)
1433                 {
1434                         if (pos + 8 > buffer.Length)
1435                                 Grow (8);
1436
1437                         buffer[pos++] = (byte) value;
1438                         buffer[pos++] = (byte) (value >> 8);
1439                         buffer[pos++] = (byte) (value >> 16);
1440                         buffer[pos++] = (byte) (value >> 24);
1441                         buffer[pos++] = (byte) (value >> 32);
1442                         buffer[pos++] = (byte) (value >> 40);
1443                         buffer[pos++] = (byte) (value >> 48);
1444                         buffer[pos++] = (byte) (value >> 56);
1445                 }
1446
1447                 public void Encode (ulong value)
1448                 {
1449                         Encode ((long) value);
1450                 }
1451
1452                 public void Encode (float value)
1453                 {
1454                         Encode (SingleConverter.SingleToInt32Bits (value));
1455                 }
1456
1457                 public void Encode (double value)
1458                 {
1459                         Encode (BitConverter.DoubleToInt64Bits (value));
1460                 }
1461
1462                 public void Encode (string value)
1463                 {
1464                         if (value == null) {
1465                                 Encode ((byte) 0xFF);
1466                                 return;
1467                         }
1468
1469                         var buf = Encoding.UTF8.GetBytes(value);
1470                         WriteCompressedValue (buf.Length);
1471
1472                         if (pos + buf.Length > buffer.Length)
1473                                 Grow (buf.Length);
1474
1475                         Buffer.BlockCopy (buf, 0, buffer, pos, buf.Length);
1476                         pos += buf.Length;
1477                 }
1478
1479                 public EncodedTypeProperties Encode (TypeSpec type)
1480                 {
1481                         switch (type.BuiltinType) {
1482                         case BuiltinTypeSpec.Type.Bool:
1483                                 Encode ((byte) 0x02);
1484                                 break;
1485                         case BuiltinTypeSpec.Type.Char:
1486                                 Encode ((byte) 0x03);
1487                                 break;
1488                         case BuiltinTypeSpec.Type.SByte:
1489                                 Encode ((byte) 0x04);
1490                                 break;
1491                         case BuiltinTypeSpec.Type.Byte:
1492                                 Encode ((byte) 0x05);
1493                                 break;
1494                         case BuiltinTypeSpec.Type.Short:
1495                                 Encode ((byte) 0x06);
1496                                 break;
1497                         case BuiltinTypeSpec.Type.UShort:
1498                                 Encode ((byte) 0x07);
1499                                 break;
1500                         case BuiltinTypeSpec.Type.Int:
1501                                 Encode ((byte) 0x08);
1502                                 break;
1503                         case BuiltinTypeSpec.Type.UInt:
1504                                 Encode ((byte) 0x09);
1505                                 break;
1506                         case BuiltinTypeSpec.Type.Long:
1507                                 Encode ((byte) 0x0A);
1508                                 break;
1509                         case BuiltinTypeSpec.Type.ULong:
1510                                 Encode ((byte) 0x0B);
1511                                 break;
1512                         case BuiltinTypeSpec.Type.Float:
1513                                 Encode ((byte) 0x0C);
1514                                 break;
1515                         case BuiltinTypeSpec.Type.Double:
1516                                 Encode ((byte) 0x0D);
1517                                 break;
1518                         case BuiltinTypeSpec.Type.String:
1519                                 Encode ((byte) 0x0E);
1520                                 break;
1521                         case BuiltinTypeSpec.Type.Type:
1522                                 Encode ((byte) 0x50);
1523                                 break;
1524                         case BuiltinTypeSpec.Type.Object:
1525                                 Encode ((byte) 0x51);
1526                                 break;
1527                         case BuiltinTypeSpec.Type.Dynamic:
1528                                 Encode ((byte) 0x51);
1529                                 return EncodedTypeProperties.DynamicType;
1530                         default:
1531                                 if (type.IsArray) {
1532                                         Encode ((byte) 0x1D);
1533                                         return Encode (TypeManager.GetElementType (type));
1534                                 }
1535
1536                                 if (type.Kind == MemberKind.Enum) {
1537                                         Encode ((byte) 0x55);
1538                                         EncodeTypeName (type);
1539                                 }
1540
1541                                 break;
1542                         }
1543
1544                         return EncodedTypeProperties.None;
1545                 }
1546
1547                 public void EncodeTypeName (TypeSpec type)
1548                 {
1549                         var old_type = type.GetMetaInfo ();
1550                         Encode (type.MemberDefinition.IsImported ? old_type.AssemblyQualifiedName : old_type.FullName);
1551                 }
1552
1553                 public void EncodeTypeName (TypeContainer type)
1554                 {
1555                         Encode (type.GetSignatureForMetadata ());
1556                 }
1557
1558
1559                 //
1560                 // Encodes single property named argument per call
1561                 //
1562                 public void EncodeNamedPropertyArgument (PropertySpec property, Constant value)
1563                 {
1564                         Encode ((ushort) 1);    // length
1565                         Encode ((byte) 0x54); // property
1566                         Encode (property.MemberType);
1567                         Encode (property.Name);
1568                         value.EncodeAttributeValue (null, this, property.MemberType, property.MemberType);
1569                 }
1570
1571                 //
1572                 // Encodes single field named argument per call
1573                 //
1574                 public void EncodeNamedFieldArgument (FieldSpec field, Constant value)
1575                 {
1576                         Encode ((ushort) 1);    // length
1577                         Encode ((byte) 0x53); // field
1578                         Encode (field.MemberType);
1579                         Encode (field.Name);
1580                         value.EncodeAttributeValue (null, this, field.MemberType, field.MemberType);
1581                 }
1582
1583                 public void EncodeNamedArguments<T> (T[] members, Constant[] values) where T : MemberSpec, IInterfaceMemberSpec
1584                 {
1585                         Encode ((ushort) members.Length);
1586
1587                         for (int i = 0; i < members.Length; ++i)
1588                         {
1589                                 var member = members[i];
1590
1591                                 if (member.Kind == MemberKind.Field)
1592                                         Encode ((byte) 0x53);
1593                                 else if (member.Kind == MemberKind.Property)
1594                                         Encode ((byte) 0x54);
1595                                 else
1596                                         throw new NotImplementedException (member.Kind.ToString ());
1597
1598                                 Encode (member.MemberType);
1599                                 Encode (member.Name);
1600                                 values [i].EncodeAttributeValue (null, this, member.MemberType, member.MemberType);
1601                         }
1602                 }
1603
1604                 public void EncodeEmptyNamedArguments ()
1605                 {
1606                         Encode ((ushort) 0);
1607                 }
1608
1609                 void Grow (int inc)
1610                 {
1611                         int size = System.Math.Max (pos * 4, pos + inc + 2);
1612                         Array.Resize (ref buffer, size);
1613                 }
1614
1615                 void WriteCompressedValue (int value)
1616                 {
1617                         if (value < 0x80) {
1618                                 Encode ((byte) value);
1619                                 return;
1620                         }
1621
1622                         if (value < 0x4000) {
1623                                 Encode ((byte) (0x80 | (value >> 8)));
1624                                 Encode ((byte) value);
1625                                 return;
1626                         }
1627
1628                         Encode (value);
1629                 }
1630
1631                 public byte[] ToArray ()
1632                 {
1633                         byte[] buf = new byte[pos];
1634                         Array.Copy (buffer, buf, pos);
1635                         return buf;
1636                 }
1637         }
1638
1639
1640         /// <summary>
1641         /// Helper class for attribute verification routine.
1642         /// </summary>
1643         static class AttributeTester
1644         {
1645                 /// <summary>
1646                 /// Common method for Obsolete error/warning reporting.
1647                 /// </summary>
1648                 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc, Report Report)
1649                 {
1650                         if (oa.IsError) {
1651                                 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1652                                 return;
1653                         }
1654
1655                         if (oa.Message == null || oa.Message.Length == 0) {
1656                                 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1657                                 return;
1658                         }
1659                         Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1660                 }
1661         }
1662
1663         //
1664         // Predefined attribute types
1665         //
1666         public class PredefinedAttributes
1667         {
1668                 // Build-in attributes
1669                 public readonly PredefinedAttribute ParamArray;
1670                 public readonly PredefinedAttribute Out;
1671
1672                 // Optional attributes
1673                 public readonly PredefinedAttribute Obsolete;
1674                 public readonly PredefinedAttribute DllImport;
1675                 public readonly PredefinedAttribute MethodImpl;
1676                 public readonly PredefinedAttribute MarshalAs;
1677                 public readonly PredefinedAttribute In;
1678                 public readonly PredefinedAttribute IndexerName;
1679                 public readonly PredefinedAttribute Conditional;
1680                 public readonly PredefinedAttribute CLSCompliant;
1681                 public readonly PredefinedAttribute Security;
1682                 public readonly PredefinedAttribute Required;
1683                 public readonly PredefinedAttribute Guid;
1684                 public readonly PredefinedAttribute AssemblyCulture;
1685                 public readonly PredefinedAttribute AssemblyVersion;
1686                 public readonly PredefinedAttribute AssemblyAlgorithmId;
1687                 public readonly PredefinedAttribute AssemblyFlags;
1688                 public readonly PredefinedAttribute AssemblyFileVersion;
1689                 public readonly PredefinedAttribute ComImport;
1690                 public readonly PredefinedAttribute CoClass;
1691                 public readonly PredefinedAttribute AttributeUsage;
1692                 public readonly PredefinedAttribute DefaultParameterValue;
1693                 public readonly PredefinedAttribute OptionalParameter;
1694                 public readonly PredefinedAttribute UnverifiableCode;
1695                 public readonly PredefinedAttribute DefaultCharset;
1696                 public readonly PredefinedAttribute TypeForwarder;
1697                 public readonly PredefinedAttribute FixedBuffer;
1698                 public readonly PredefinedAttribute CompilerGenerated;
1699                 public readonly PredefinedAttribute InternalsVisibleTo;
1700                 public readonly PredefinedAttribute RuntimeCompatibility;
1701                 public readonly PredefinedAttribute DebuggerHidden;
1702                 public readonly PredefinedAttribute UnsafeValueType;
1703                 public readonly PredefinedAttribute UnmanagedFunctionPointer;
1704                 public readonly PredefinedDebuggerBrowsableAttribute DebuggerBrowsable;
1705                 public readonly PredefinedAttribute DebuggerStepThrough;
1706                 public readonly PredefinedDebuggableAttribute Debuggable;
1707                 public readonly PredefinedAttribute HostProtection;
1708
1709                 // New in .NET 3.5
1710                 public readonly PredefinedAttribute Extension;
1711
1712                 // New in .NET 4.0
1713                 public readonly PredefinedDynamicAttribute Dynamic;
1714
1715                 // New in .NET 4.5
1716                 public readonly PredefinedStateMachineAttribute AsyncStateMachine;
1717
1718                 //
1719                 // Optional types which are used as types and for member lookup
1720                 //
1721                 public readonly PredefinedAttribute DefaultMember;
1722                 public readonly PredefinedDecimalAttribute DecimalConstant;
1723                 public readonly PredefinedAttribute StructLayout;
1724                 public readonly PredefinedAttribute FieldOffset;
1725                 public readonly PredefinedAttribute AssemblyProduct;
1726                 public readonly PredefinedAttribute AssemblyCompany;
1727                 public readonly PredefinedAttribute AssemblyCopyright;
1728                 public readonly PredefinedAttribute AssemblyTrademark;
1729                 public readonly PredefinedAttribute CallerMemberNameAttribute;
1730                 public readonly PredefinedAttribute CallerLineNumberAttribute;
1731                 public readonly PredefinedAttribute CallerFilePathAttribute;
1732
1733                 public PredefinedAttributes (ModuleContainer module)
1734                 {
1735                         ParamArray = new PredefinedAttribute (module, "System", "ParamArrayAttribute");
1736                         Out = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OutAttribute");
1737                         ParamArray.Resolve ();
1738                         Out.Resolve ();
1739
1740                         Obsolete = new PredefinedAttribute (module, "System", "ObsoleteAttribute");
1741                         DllImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DllImportAttribute");
1742                         MethodImpl = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "MethodImplAttribute");
1743                         MarshalAs = new PredefinedAttribute (module, "System.Runtime.InteropServices", "MarshalAsAttribute");
1744                         In = new PredefinedAttribute (module, "System.Runtime.InteropServices", "InAttribute");
1745                         IndexerName = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "IndexerNameAttribute");
1746                         Conditional = new PredefinedAttribute (module, "System.Diagnostics", "ConditionalAttribute");
1747                         CLSCompliant = new PredefinedAttribute (module, "System", "CLSCompliantAttribute");
1748                         Security = new PredefinedAttribute (module, "System.Security.Permissions", "SecurityAttribute");
1749                         Required = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1750                         Guid = new PredefinedAttribute (module, "System.Runtime.InteropServices", "GuidAttribute");
1751                         AssemblyCulture = new PredefinedAttribute (module, "System.Reflection", "AssemblyCultureAttribute");
1752                         AssemblyVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyVersionAttribute");
1753                         AssemblyAlgorithmId = new PredefinedAttribute (module, "System.Reflection", "AssemblyAlgorithmIdAttribute");
1754                         AssemblyFlags = new PredefinedAttribute (module, "System.Reflection", "AssemblyFlagsAttribute");
1755                         AssemblyFileVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyFileVersionAttribute");
1756                         ComImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "ComImportAttribute");
1757                         CoClass = new PredefinedAttribute (module, "System.Runtime.InteropServices", "CoClassAttribute");
1758                         AttributeUsage = new PredefinedAttribute (module, "System", "AttributeUsageAttribute");
1759                         DefaultParameterValue = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultParameterValueAttribute");
1760                         OptionalParameter = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OptionalAttribute");
1761                         UnverifiableCode = new PredefinedAttribute (module, "System.Security", "UnverifiableCodeAttribute");
1762                         HostProtection = new PredefinedAttribute (module, "System.Security.Permissions", "HostProtectionAttribute");
1763
1764                         DefaultCharset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultCharSetAttribute");
1765                         TypeForwarder = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "TypeForwardedToAttribute");
1766                         FixedBuffer = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "FixedBufferAttribute");
1767                         CompilerGenerated = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1768                         InternalsVisibleTo = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
1769                         RuntimeCompatibility = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1770                         DebuggerHidden = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerHiddenAttribute");
1771                         UnsafeValueType = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
1772                         UnmanagedFunctionPointer = new PredefinedAttribute (module, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
1773                         DebuggerBrowsable = new PredefinedDebuggerBrowsableAttribute (module, "System.Diagnostics", "DebuggerBrowsableAttribute");
1774                         DebuggerStepThrough = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerStepThroughAttribute");
1775                         Debuggable = new PredefinedDebuggableAttribute (module, "System.Diagnostics", "DebuggableAttribute");
1776
1777                         Extension = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "ExtensionAttribute");
1778
1779                         Dynamic = new PredefinedDynamicAttribute (module, "System.Runtime.CompilerServices", "DynamicAttribute");
1780
1781                         DefaultMember = new PredefinedAttribute (module, "System.Reflection", "DefaultMemberAttribute");
1782                         DecimalConstant = new PredefinedDecimalAttribute (module, "System.Runtime.CompilerServices", "DecimalConstantAttribute");
1783                         StructLayout = new PredefinedAttribute (module, "System.Runtime.InteropServices", "StructLayoutAttribute");
1784                         FieldOffset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "FieldOffsetAttribute");
1785                         AssemblyProduct = new PredefinedAttribute (module, "System.Reflection", "AssemblyProductAttribute");
1786                         AssemblyCompany = new PredefinedAttribute (module, "System.Reflection", "AssemblyCompanyAttribute");
1787                         AssemblyCopyright = new PredefinedAttribute (module, "System.Reflection", "AssemblyCopyrightAttribute");
1788                         AssemblyTrademark = new PredefinedAttribute (module, "System.Reflection", "AssemblyTrademarkAttribute");
1789
1790                         AsyncStateMachine = new PredefinedStateMachineAttribute (module, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute");
1791
1792                         CallerMemberNameAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerMemberNameAttribute");
1793                         CallerLineNumberAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerLineNumberAttribute");
1794                         CallerFilePathAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerFilePathAttribute");
1795
1796                         // TODO: Should define only attributes which are used for comparison
1797                         const System.Reflection.BindingFlags all_fields = System.Reflection.BindingFlags.Public |
1798                                 System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly;
1799
1800                         foreach (var fi in GetType ().GetFields (all_fields)) {
1801                                 ((PredefinedAttribute) fi.GetValue (this)).Define ();
1802                         }
1803                 }
1804         }
1805
1806         public class PredefinedAttribute : PredefinedType
1807         {
1808                 protected MethodSpec ctor;
1809
1810                 public PredefinedAttribute (ModuleContainer module, string ns, string name)
1811                         : base (module, MemberKind.Class, ns, name)
1812                 {
1813                 }
1814
1815                 #region Properties
1816
1817                 public MethodSpec Constructor {
1818                         get {
1819                                 return ctor;
1820                         }
1821                 }
1822
1823                 #endregion
1824
1825                 public static bool operator == (TypeSpec type, PredefinedAttribute pa)
1826                 {
1827                         return type == pa.type && pa.type != null;
1828                 }
1829
1830                 public static bool operator != (TypeSpec type, PredefinedAttribute pa)
1831                 {
1832                         return type != pa.type;
1833                 }
1834
1835                 public override int GetHashCode ()
1836                 {
1837                         return base.GetHashCode ();
1838                 }
1839
1840                 public override bool Equals (object obj)
1841                 {
1842                         throw new NotSupportedException ();
1843                 }
1844
1845                 public void EmitAttribute (ConstructorBuilder builder)
1846                 {
1847                         if (ResolveBuilder ())
1848                                 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1849                 }
1850
1851                 public void EmitAttribute (MethodBuilder builder)
1852                 {
1853                         if (ResolveBuilder ())
1854                                 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1855                 }
1856
1857                 public void EmitAttribute (PropertyBuilder builder)
1858                 {
1859                         if (ResolveBuilder ())
1860                                 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1861                 }
1862
1863                 public void EmitAttribute (FieldBuilder builder)
1864                 {
1865                         if (ResolveBuilder ())
1866                                 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1867                 }
1868
1869                 public void EmitAttribute (TypeBuilder builder)
1870                 {
1871                         if (ResolveBuilder ())
1872                                 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1873                 }
1874
1875                 public void EmitAttribute (AssemblyBuilder builder)
1876                 {
1877                         if (ResolveBuilder ())
1878                                 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1879                 }
1880
1881                 public void EmitAttribute (ModuleBuilder builder)
1882                 {
1883                         if (ResolveBuilder ())
1884                                 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1885                 }
1886
1887                 public void EmitAttribute (ParameterBuilder builder)
1888                 {
1889                         if (ResolveBuilder ())
1890                                 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1891                 }
1892
1893                 ConstructorInfo GetCtorMetaInfo ()
1894                 {
1895                         return (ConstructorInfo) ctor.GetMetaInfo ();
1896                 }
1897
1898                 public bool ResolveBuilder ()
1899                 {
1900                         if (ctor != null)
1901                                 return true;
1902
1903                         //
1904                         // Handle all parameter-less attributes as optional
1905                         //
1906                         if (!Define ())
1907                                 return false;
1908
1909                         ctor = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters), BindingRestriction.DeclaredOnly);
1910                         return ctor != null;
1911                 }
1912         }
1913
1914         public class PredefinedDebuggerBrowsableAttribute : PredefinedAttribute
1915         {
1916                 public PredefinedDebuggerBrowsableAttribute (ModuleContainer module, string ns, string name)
1917                         : base (module, ns, name)
1918                 {
1919                 }
1920
1921                 public void EmitAttribute (FieldBuilder builder, System.Diagnostics.DebuggerBrowsableState state)
1922                 {
1923                         var ctor = module.PredefinedMembers.DebuggerBrowsableAttributeCtor.Get ();
1924                         if (ctor == null)
1925                                 return;
1926
1927                         AttributeEncoder encoder = new AttributeEncoder ();
1928                         encoder.Encode ((int) state);
1929                         encoder.EncodeEmptyNamedArguments ();
1930
1931                         builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1932                 }
1933         }
1934
1935         public class PredefinedDebuggableAttribute : PredefinedAttribute
1936         {
1937                 public PredefinedDebuggableAttribute (ModuleContainer module, string ns, string name)
1938                         : base (module, ns, name)
1939                 {
1940                 }
1941
1942                 public void EmitAttribute (AssemblyBuilder builder, System.Diagnostics.DebuggableAttribute.DebuggingModes modes)
1943                 {
1944                         var atype = module.PredefinedAttributes.Debuggable;
1945                         if (!atype.Define ())
1946                                 return;
1947
1948                         MethodSpec ctor = null;
1949                         foreach (MethodSpec m in MemberCache.FindMembers (atype.TypeSpec, CSharp.Constructor.ConstructorName, true)) {
1950                                 if (m.Parameters.Count != 1)
1951                                         continue;
1952
1953                                 if (m.Parameters.Types[0].Kind == MemberKind.Enum) {
1954                                         ctor = m;
1955                                 }
1956                         }
1957
1958                         if (ctor == null)
1959                                 return;
1960
1961                         AttributeEncoder encoder = new AttributeEncoder ();
1962                         encoder.Encode ((int) modes);
1963                         encoder.EncodeEmptyNamedArguments ();
1964
1965                         builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1966                 }
1967         }
1968
1969         public class PredefinedDecimalAttribute : PredefinedAttribute
1970         {
1971                 public PredefinedDecimalAttribute (ModuleContainer module, string ns, string name)
1972                         : base (module, ns, name)
1973                 {
1974                 }
1975
1976                 public void EmitAttribute (ParameterBuilder builder, decimal value, Location loc)
1977                 {
1978                         var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
1979                         if (ctor == null)
1980                                 return;
1981
1982                         int[] bits = decimal.GetBits (value);
1983                         AttributeEncoder encoder = new AttributeEncoder ();
1984                         encoder.Encode ((byte) (bits[3] >> 16));
1985                         encoder.Encode ((byte) (bits[3] >> 31));
1986                         encoder.Encode ((uint) bits[2]);
1987                         encoder.Encode ((uint) bits[1]);
1988                         encoder.Encode ((uint) bits[0]);
1989                         encoder.EncodeEmptyNamedArguments ();
1990
1991                         builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1992                 }
1993
1994                 public void EmitAttribute (FieldBuilder builder, decimal value, Location loc)
1995                 {
1996                         var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
1997                         if (ctor == null)
1998                                 return;
1999
2000                         int[] bits = decimal.GetBits (value);
2001                         AttributeEncoder encoder = new AttributeEncoder ();
2002                         encoder.Encode ((byte) (bits[3] >> 16));
2003                         encoder.Encode ((byte) (bits[3] >> 31));
2004                         encoder.Encode ((uint) bits[2]);
2005                         encoder.Encode ((uint) bits[1]);
2006                         encoder.Encode ((uint) bits[0]);
2007                         encoder.EncodeEmptyNamedArguments ();
2008
2009                         builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
2010                 }
2011         }
2012
2013         public class PredefinedStateMachineAttribute : PredefinedAttribute
2014         {
2015                 public PredefinedStateMachineAttribute (ModuleContainer module, string ns, string name)
2016                         : base (module, ns, name)
2017                 {
2018                 }
2019
2020                 public void EmitAttribute (MethodBuilder builder, StateMachine type)
2021                 {
2022                         var predefined_ctor = module.PredefinedMembers.AsyncStateMachineAttributeCtor;
2023
2024                         var ctor = predefined_ctor.Get ();
2025
2026                         if (ctor == null)
2027                                 return;
2028
2029                         AttributeEncoder encoder = new AttributeEncoder ();
2030                         encoder.EncodeTypeName (type);
2031                         encoder.EncodeEmptyNamedArguments ();
2032
2033                         builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
2034                 }
2035         }
2036
2037         public class PredefinedDynamicAttribute : PredefinedAttribute
2038         {
2039                 MethodSpec tctor;
2040
2041                 public PredefinedDynamicAttribute (ModuleContainer module, string ns, string name)
2042                         : base (module, ns, name)
2043                 {
2044                 }
2045
2046                 public void EmitAttribute (FieldBuilder builder, TypeSpec type, Location loc)
2047                 {
2048                         if (ResolveTransformationCtor (loc)) {
2049                                 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
2050                                 builder.SetCustomAttribute (cab);
2051                         }
2052                 }
2053
2054                 public void EmitAttribute (ParameterBuilder builder, TypeSpec type, Location loc)
2055                 {
2056                         if (ResolveTransformationCtor (loc)) {
2057                                 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
2058                                 builder.SetCustomAttribute (cab);
2059                         }
2060                 }
2061
2062                 public void EmitAttribute (PropertyBuilder builder, TypeSpec type, Location loc)
2063                 {
2064                         if (ResolveTransformationCtor (loc)) {
2065                                 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
2066                                 builder.SetCustomAttribute (cab);
2067                         }
2068                 }
2069
2070                 public void EmitAttribute (TypeBuilder builder, TypeSpec type, Location loc)
2071                 {
2072                         if (ResolveTransformationCtor (loc)) {
2073                                 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
2074                                 builder.SetCustomAttribute (cab);
2075                         }
2076                 }
2077
2078                 //
2079                 // When any element of the type is a dynamic type
2080                 //
2081                 // This method builds a transformation array for dynamic types
2082                 // used in places where DynamicAttribute cannot be applied to.
2083                 // It uses bool flag when type is of dynamic type and each
2084                 // section always starts with "false" for some reason.
2085                 //
2086                 // LAMESPEC: This should be part of C# specification
2087                 // 
2088                 // Example: Func<dynamic, int, dynamic[]>
2089                 // Transformation: { false, true, false, false, true }
2090                 //
2091                 static bool[] GetTransformationFlags (TypeSpec t)
2092                 {
2093                         bool[] element;
2094                         var ac = t as ArrayContainer;
2095                         if (ac != null) {
2096                                 element = GetTransformationFlags (ac.Element);
2097                                 if (element == null)
2098                                         return new bool[] { false, false };
2099
2100                                 bool[] res = new bool[element.Length + 1];
2101                                 res[0] = false;
2102                                 Array.Copy (element, 0, res, 1, element.Length);
2103                                 return res;
2104                         }
2105
2106                         if (t == null)
2107                                 return null;
2108
2109                         if (t.IsGeneric) {
2110                                 List<bool> transform = null;
2111                                 var targs = t.TypeArguments;
2112                                 for (int i = 0; i < targs.Length; ++i) {
2113                                         element = GetTransformationFlags (targs[i]);
2114                                         if (element != null) {
2115                                                 if (transform == null) {
2116                                                         transform = new List<bool> ();
2117                                                         for (int ii = 0; ii <= i; ++ii)
2118                                                                 transform.Add (false);
2119                                                 }
2120
2121                                                 transform.AddRange (element);
2122                                         } else if (transform != null) {
2123                                                 transform.Add (false);
2124                                         }
2125                                 }
2126
2127                                 if (transform != null)
2128                                         return transform.ToArray ();
2129                         }
2130
2131                         if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2132                                 return new bool[] { true };
2133
2134                         return null;
2135                 }
2136
2137                 bool ResolveTransformationCtor (Location loc)
2138                 {
2139                         if (tctor != null)
2140                                 return true;
2141
2142                         tctor = module.PredefinedMembers.DynamicAttributeCtor.Resolve (loc);
2143                         return tctor != null;
2144                 }
2145         }
2146 }