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