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