~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

« back to all changes in this revision

Viewing changes to contrib/ICSharpCode.NRefactory.CSharp/Parser/mcs/attribute.cs

  • Committer: Package Import Robot
  • Author(s): Jo Shields
  • Date: 2013-05-12 09:46:03 UTC
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20130512094603-mad323bzcxvmcam0
Tags: upstream-4.0.5+dfsg
ImportĀ upstreamĀ versionĀ 4.0.5+dfsg

Show diffs side-by-side

added added

removed removed

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