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