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