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