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