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