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