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