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