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