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