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