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