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