099055b733cf2d9182b0e6b06b950edd402d3c5a
[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 (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 (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 (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                                                 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
964
965                                                 object old_instance = pi.PropertyType.IsEnum ?
966                                                         System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
967                                                         prop_values_arr [i];
968
969                                                 pi.SetValue (sa, old_instance, null);
970                                         }
971                                 }
972                         }
973
974                         IPermission perm;
975                         perm = sa.CreatePermission ();
976                         SecurityAction action = GetSecurityActionValue ();
977
978                         // IS is correct because for corlib we are using an instance from old corlib
979                         if (!(perm is System.Security.CodeAccessPermission)) {
980                                 switch (action) {
981                                         case SecurityAction.Demand:
982                                                 action = (SecurityAction)13;
983                                                 break;
984                                         case SecurityAction.LinkDemand:
985                                                 action = (SecurityAction)14;
986                                                 break;
987                                         case SecurityAction.InheritanceDemand:
988                                                 action = (SecurityAction)15;
989                                                 break;
990                                 }
991                         }
992
993                         PermissionSet ps = (PermissionSet)permissions [action];
994                         if (ps == null) {
995                                 if (sa is PermissionSetAttribute)
996                                         ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
997                                 else
998                                         ps = new PermissionSet (PermissionState.None);
999
1000                                 permissions.Add (action, ps);
1001                         } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
1002                                 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
1003                                 permissions [action] = ps;
1004                         }
1005                         ps.AddPermission (perm);
1006                 }
1007
1008                 static object GetValue (object value)
1009                 {
1010                         if (value is EnumConstant)
1011                                 return ((EnumConstant) value).GetValue ();
1012                         else
1013                                 return value;                           
1014                 }
1015
1016                 public object GetPropertyValue (string name)
1017                 {
1018                         if (prop_info_arr == null)
1019                                 return null;
1020
1021                         for (int i = 0; i < prop_info_arr.Length; ++i) {
1022                                 if (prop_info_arr [i].Name == name)
1023                                         return prop_values_arr [i];
1024                         }
1025
1026                         return null;
1027                 }
1028
1029                 object GetFieldValue (string name)
1030                 {
1031                         int i;
1032                         if (field_info_arr == null)
1033                                 return null;
1034                         i = 0;
1035                         foreach (FieldInfo fi in field_info_arr) {
1036                                 if (fi.Name == name)
1037                                         return GetValue (field_values_arr [i]);
1038                                 i++;
1039                         }
1040                         return null;
1041                 }
1042
1043                 //
1044                 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
1045                 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
1046                 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
1047                 //
1048                 public UnmanagedMarshal GetMarshal (Attributable attr)
1049                 {
1050                         UnmanagedType UnmanagedType;
1051                         if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
1052                                 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
1053                         else
1054                                 UnmanagedType = (UnmanagedType) pos_values [0];
1055
1056                         object value = GetFieldValue ("SizeParamIndex");
1057                         if (value != null && UnmanagedType != UnmanagedType.LPArray) {
1058                                 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
1059                                 return null;
1060                         }
1061
1062                         object o = GetFieldValue ("ArraySubType");
1063                         UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
1064
1065                         switch (UnmanagedType) {
1066                         case UnmanagedType.CustomMarshaler: {
1067                                 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
1068                                         BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1069                                 if (define_custom == null) {
1070                                         Report.RuntimeMissingSupport (Location, "set marshal info");
1071                                         return null;
1072                                 }
1073                                 
1074                                 object [] args = new object [4];
1075                                 args [0] = GetFieldValue ("MarshalTypeRef");
1076                                 args [1] = GetFieldValue ("MarshalCookie");
1077                                 args [2] = GetFieldValue ("MarshalType");
1078                                 args [3] = Guid.Empty;
1079                                 return (UnmanagedMarshal) define_custom.Invoke (null, args);
1080                         }
1081                         case UnmanagedType.LPArray: {
1082                                 object size_const = GetFieldValue ("SizeConst");
1083                                 object size_param_index = GetFieldValue ("SizeParamIndex");
1084
1085                                 if ((size_const != null) || (size_param_index != null)) {
1086                                         MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
1087                                                 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1088                                         if (define_array == null) {
1089                                                 Report.RuntimeMissingSupport (Location, "set marshal info");
1090                                                 return null;
1091                                         }
1092                                 
1093                                         object [] args = new object [3];
1094                                         args [0] = array_sub_type;
1095                                         args [1] = size_const == null ? -1 : size_const;
1096                                         args [2] = size_param_index == null ? -1 : size_param_index;
1097                                         return (UnmanagedMarshal) define_array.Invoke (null, args);
1098                                 }
1099                                 else
1100                                         return UnmanagedMarshal.DefineLPArray (array_sub_type);
1101                         }
1102                         case UnmanagedType.SafeArray:
1103                                 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1104
1105                         case UnmanagedType.ByValArray:
1106                                 FieldBase fm = attr as FieldBase;
1107                                 if (fm == null) {
1108                                         Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1109                                         return null;
1110                                 }
1111                                 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1112
1113                         case UnmanagedType.ByValTStr:
1114                                 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1115
1116                         default:
1117                                 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1118                         }
1119                 }
1120
1121                 public CharSet GetCharSetValue ()
1122                 {
1123                         return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1124                 }
1125
1126                 public bool IsInternalMethodImplAttribute {
1127                         get {
1128                                 if (Type != TypeManager.methodimpl_attr_type)
1129                                         return false;
1130
1131                                 MethodImplOptions options;
1132                                 if (pos_values[0].GetType () != typeof (MethodImplOptions))
1133                                         options = (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values[0]);
1134                                 else
1135                                         options = (MethodImplOptions)pos_values[0];
1136
1137                                 return (options & MethodImplOptions.InternalCall) != 0;
1138                         }
1139                 }
1140
1141                 public LayoutKind GetLayoutKindValue ()
1142                 {
1143                         if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1144                                 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1145
1146                         return (LayoutKind)pos_values [0];
1147                 }
1148
1149                 public object GetParameterDefaultValue ()
1150                 {
1151                         return pos_values [0];
1152                 }
1153
1154                 public override bool Equals (object obj)
1155                 {
1156                         Attribute a = obj as Attribute;
1157                         if (a == null)
1158                                 return false;
1159
1160                         return Type == a.Type && Target == a.Target;
1161                 }
1162
1163                 public override int GetHashCode ()
1164                 {
1165                         return base.GetHashCode ();
1166                 }
1167
1168                 /// <summary>
1169                 /// Emit attribute for Attributable symbol
1170                 /// </summary>
1171                 public void Emit (ListDictionary allEmitted)
1172                 {
1173                         CustomAttributeBuilder cb = Resolve ();
1174                         if (cb == null)
1175                                 return;
1176
1177                         AttributeUsageAttribute usage_attr = GetAttributeUsage (Type);
1178                         if ((usage_attr.ValidOn & Target) == 0) {
1179                                 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1180                                               "It is valid on `{1}' declarations only",
1181                                         GetSignatureForError (), GetValidTargets ());
1182                                 return;
1183                         }
1184
1185                         try {
1186                                 foreach (Attributable owner in owners)
1187                                         owner.ApplyAttributeBuilder (this, cb);
1188                         }
1189                         catch (Exception e) {
1190                                 Error_AttributeEmitError (e.Message);
1191                                 return;
1192                         }
1193
1194                         if (!usage_attr.AllowMultiple && allEmitted != null) {
1195                                 if (allEmitted.Contains (this)) {
1196                                         ArrayList a = allEmitted [this] as ArrayList;
1197                                         if (a == null) {
1198                                                 a = new ArrayList (2);
1199                                                 allEmitted [this] = a;
1200                                         }
1201                                         a.Add (this);
1202                                 } else {
1203                                         allEmitted.Add (this, null);
1204                                 }
1205                         }
1206
1207                         if (!RootContext.VerifyClsCompliance)
1208                                 return;
1209
1210                         // Here we are testing attribute arguments for array usage (error 3016)
1211                         if (Owner.IsClsComplianceRequired ()) {
1212                                 if (PosArguments != null) {
1213                                         foreach (Argument arg in PosArguments) { 
1214                                                 // Type is undefined (was error 246)
1215                                                 if (arg.Type == null)
1216                                                         return;
1217
1218                                                 if (arg.Type.IsArray) {
1219                                                         Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1220                                                         return;
1221                                                 }
1222                                         }
1223                                 }
1224                         
1225                                 if (NamedArguments == null)
1226                                         return;
1227                         
1228                                 foreach (DictionaryEntry de in NamedArguments) {
1229                                         Argument arg  = (Argument) de.Value;
1230
1231                                         // Type is undefined (was error 246)
1232                                         if (arg.Type == null)
1233                                                 return;
1234
1235                                         if (arg.Type.IsArray) {
1236                                                 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1237                                                 return;
1238                                         }
1239                                 }
1240                         }
1241                 }
1242
1243                 private Expression GetValue () 
1244                 {
1245                         if (PosArguments == null || PosArguments.Count < 1)
1246                                 return null;
1247
1248                         return ((Argument) PosArguments [0]).Expr;
1249                 }
1250
1251                 public string GetString () 
1252                 {
1253                         Expression e = GetValue ();
1254                         if (e is StringConstant)
1255                                 return ((StringConstant)e).Value;
1256                         return null;
1257                 }
1258
1259                 public bool GetBoolean () 
1260                 {
1261                         Expression e = GetValue ();
1262                         if (e is BoolConstant)
1263                                 return ((BoolConstant)e).Value;
1264                         return false;
1265                 }
1266
1267                 public Type GetArgumentType ()
1268                 {
1269                         TypeOf e = GetValue () as TypeOf;
1270                         if (e == null)
1271                                 return null;
1272                         return e.TypeArgument;
1273                 }
1274
1275                 public override Expression DoResolve (EmitContext ec)
1276                 {
1277                         throw new NotImplementedException ();
1278                 }
1279
1280                 public override void Emit (EmitContext ec)
1281                 {
1282                         throw new NotImplementedException ();
1283                 }
1284         }
1285         
1286
1287         /// <summary>
1288         /// For global attributes (assembly, module) we need special handling.
1289         /// Attributes can be located in the several files
1290         /// </summary>
1291         public class GlobalAttribute : Attribute
1292         {
1293                 public readonly NamespaceEntry ns;
1294
1295                 public GlobalAttribute (NamespaceEntry ns, string target, 
1296                                         Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped):
1297                         base (target, left_expr, identifier, args, loc, nameEscaped)
1298                 {
1299                         this.ns = ns;
1300                         this.owners = new Attributable[1];
1301                 }
1302                 
1303                 public override void AttachTo (Attributable owner)
1304                 {
1305                         if (ExplicitTarget == "assembly") {
1306                                 owners [0] = CodeGen.Assembly;
1307                                 return;
1308                         }
1309                         if (ExplicitTarget == "module") {
1310                                 owners [0] = CodeGen.Module;
1311                                 return;
1312                         }
1313                         throw new NotImplementedException ("Unknown global explicit target " + ExplicitTarget);
1314                 }
1315
1316                 void Enter ()
1317                 {
1318                         // RootContext.ToplevelTypes has a single NamespaceEntry which gets overwritten
1319                         // each time a new file is parsed.  However, we need to use the NamespaceEntry
1320                         // in effect where the attribute was used.  Since code elsewhere cannot assume
1321                         // that the NamespaceEntry is right, just overwrite it.
1322                         //
1323                         // Precondition: RootContext.ToplevelTypes == null
1324
1325                         if (RootContext.ToplevelTypes.NamespaceEntry != null)
1326                                 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1327
1328                         RootContext.ToplevelTypes.NamespaceEntry = ns;
1329                 }
1330
1331                 protected override bool IsSecurityActionValid (bool for_assembly)
1332                 {
1333                         return base.IsSecurityActionValid (true);
1334                 }
1335
1336                 void Leave ()
1337                 {
1338                         RootContext.ToplevelTypes.NamespaceEntry = null;
1339                 }
1340
1341                 protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
1342                 {
1343                         try {
1344                                 Enter ();
1345                                 return base.ResolveAsTypeTerminal (expr, ec, silent);
1346                         }
1347                         finally {
1348                                 Leave ();
1349                         }
1350                 }
1351
1352                 protected override ConstructorInfo ResolveConstructor (EmitContext ec)
1353                 {
1354                         try {
1355                                 Enter ();
1356                                 return base.ResolveConstructor (ec);
1357                         }
1358                         finally {
1359                                 Leave ();
1360                         }
1361                 }
1362
1363                 protected override bool ResolveNamedArguments (EmitContext ec)
1364                 {
1365                         try {
1366                                 Enter ();
1367                                 return base.ResolveNamedArguments (ec);
1368                         }
1369                         finally {
1370                                 Leave ();
1371                         }
1372                 }
1373         }
1374
1375         public class Attributes {
1376                 public readonly ArrayList Attrs;
1377
1378                 public Attributes (Attribute a)
1379                 {
1380                         Attrs = new ArrayList ();
1381                         Attrs.Add (a);
1382                 }
1383
1384                 public Attributes (ArrayList attrs)
1385                 {
1386                         Attrs = attrs;
1387                 }
1388
1389                 public void AddAttributes (ArrayList attrs)
1390                 {
1391                         Attrs.AddRange (attrs);
1392                 }
1393
1394                 public void AttachTo (Attributable attributable)
1395                 {
1396                         foreach (Attribute a in Attrs)
1397                                 a.AttachTo (attributable);
1398                 }
1399
1400                 /// <summary>
1401                 /// Checks whether attribute target is valid for the current element
1402                 /// </summary>
1403                 public bool CheckTargets ()
1404                 {
1405                         foreach (Attribute a in Attrs) {
1406                                 if (!a.CheckTarget ())
1407                                         return false;
1408                         }
1409                         return true;
1410                 }
1411
1412                 public Attribute Search (Type t)
1413                 {
1414                         foreach (Attribute a in Attrs) {
1415                                 if (a.ResolveType () == t)
1416                                         return a;
1417                         }
1418                         return null;
1419                 }
1420
1421                 /// <summary>
1422                 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1423                 /// </summary>
1424                 public Attribute[] SearchMulti (Type t)
1425                 {
1426                         ArrayList ar = null;
1427
1428                         foreach (Attribute a in Attrs) {
1429                                 if (a.ResolveType () == t) {
1430                                         if (ar == null)
1431                                                 ar = new ArrayList ();
1432                                         ar.Add (a);
1433                                 }
1434                         }
1435
1436                         return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1437                 }
1438
1439                 public void Emit ()
1440                 {
1441                         CheckTargets ();
1442
1443                         ListDictionary ld = Attrs.Count > 1 ? new ListDictionary () : null;
1444
1445                         foreach (Attribute a in Attrs)
1446                                 a.Emit (ld);
1447
1448                         if (ld == null || ld.Count == 0)
1449                                 return;
1450
1451                         foreach (DictionaryEntry d in ld) {
1452                                 if (d.Value == null)
1453                                         continue;
1454
1455                                 foreach (Attribute collision in (ArrayList)d.Value)
1456                                         Report.SymbolRelatedToPreviousError (collision.Location, "");
1457
1458                                 Attribute a = (Attribute)d.Key;
1459                                 Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1460                                         a.GetSignatureForError ());
1461                         }
1462                 }
1463
1464                 public bool Contains (Type t)
1465                 {
1466                         return Search (t) != null;
1467                 }
1468         }
1469
1470         /// <summary>
1471         /// Helper class for attribute verification routine.
1472         /// </summary>
1473         sealed class AttributeTester
1474         {
1475                 static PtrHashtable analyzed_types;
1476                 static PtrHashtable analyzed_types_obsolete;
1477                 static PtrHashtable analyzed_member_obsolete;
1478                 static PtrHashtable analyzed_method_excluded;
1479                 static PtrHashtable fixed_buffer_cache;
1480
1481                 static object TRUE = new object ();
1482                 static object FALSE = new object ();
1483
1484                 static AttributeTester ()
1485                 {
1486                         Reset ();
1487                 }
1488
1489                 private AttributeTester ()
1490                 {
1491                 }
1492
1493                 public static void Reset ()
1494                 {
1495                         analyzed_types = new PtrHashtable ();
1496                         analyzed_types_obsolete = new PtrHashtable ();
1497                         analyzed_member_obsolete = new PtrHashtable ();
1498                         analyzed_method_excluded = new PtrHashtable ();
1499                         fixed_buffer_cache = new PtrHashtable ();
1500                 }
1501
1502                 public enum Result {
1503                         Ok,
1504                         RefOutArrayError,
1505                         ArrayArrayError
1506                 }
1507
1508                 /// <summary>
1509                 /// Returns true if parameters of two compared methods are CLS-Compliant.
1510                 /// It tests differing only in ref or out, or in array rank.
1511                 /// </summary>
1512                 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b) 
1513                 {
1514                         if (types_a == null || types_b == null)
1515                                 return Result.Ok;
1516
1517                         if (types_a.Length != types_b.Length)
1518                                 return Result.Ok;
1519
1520                         Result result = Result.Ok;
1521                         for (int i = 0; i < types_b.Length; ++i) {
1522                                 Type aType = types_a [i];
1523                                 Type bType = types_b [i];
1524
1525                                 if (aType.IsArray && bType.IsArray) {
1526                                         Type a_el_type = aType.GetElementType ();
1527                                         Type b_el_type = bType.GetElementType ();
1528                                         if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1529                                                 result = Result.RefOutArrayError;
1530                                                 continue;
1531                                         }
1532
1533                                         if (a_el_type.IsArray || b_el_type.IsArray) {
1534                                                 result = Result.ArrayArrayError;
1535                                                 continue;
1536                                         }
1537                                 }
1538
1539                                 Type aBaseType = aType;
1540                                 bool is_either_ref_or_out = false;
1541
1542                                 if (aType.IsByRef || aType.IsPointer) {
1543                                         aBaseType = aType.GetElementType ();
1544                                         is_either_ref_or_out = true;
1545                                 }
1546
1547                                 Type bBaseType = bType;
1548                                 if (bType.IsByRef || bType.IsPointer) 
1549                                 {
1550                                         bBaseType = bType.GetElementType ();
1551                                         is_either_ref_or_out = !is_either_ref_or_out;
1552                                 }
1553
1554                                 if (aBaseType != bBaseType)
1555                                         return Result.Ok;
1556
1557                                 if (is_either_ref_or_out)
1558                                         result = Result.RefOutArrayError;
1559                         }
1560                         return result;
1561                 }
1562
1563                 /// <summary>
1564                 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1565                 /// </summary>
1566                 public static bool IsClsCompliant (Type type) 
1567                 {
1568                         if (type == null)
1569                                 return true;
1570
1571                         object type_compliance = analyzed_types[type];
1572                         if (type_compliance != null)
1573                                 return type_compliance == TRUE;
1574
1575                         if (type.IsPointer) {
1576                                 analyzed_types.Add (type, null);
1577                                 return false;
1578                         }
1579
1580                         bool result;
1581                         if (type.IsArray || type.IsByRef) {
1582                                 result = IsClsCompliant (TypeManager.GetElementType (type));
1583                         } else if (TypeManager.IsNullableType (type)) {
1584                                 result = IsClsCompliant (TypeManager.GetTypeArguments (type) [0]);
1585                         } else {
1586                                 result = AnalyzeTypeCompliance (type);
1587                         }
1588                         analyzed_types.Add (type, result ? TRUE : FALSE);
1589                         return result;
1590                 }        
1591         
1592                 /// <summary>
1593                 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1594                 /// </summary>
1595                 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1596                 {
1597                         // Fixed buffer helper type is generated as value type
1598                         if (!fi.FieldType.IsValueType)
1599                                 return null;
1600
1601                         FieldBase fb = TypeManager.GetField (fi);
1602                         if (fb != null) {
1603                                 return fb as IFixedBuffer;
1604                         }
1605                         
1606                         if (TypeManager.GetConstant (fi) != null)
1607                                 return null;
1608
1609                         object o = fixed_buffer_cache [fi];
1610                         if (o == null) {
1611                                 if (TypeManager.fixed_buffer_attr_type == null)
1612                                         return null;
1613
1614                                 if (!fi.IsDefined (TypeManager.fixed_buffer_attr_type, false)) {
1615                                         fixed_buffer_cache.Add (fi, FALSE);
1616                                         return null;
1617                                 }
1618                                 
1619                                 IFixedBuffer iff = new FixedFieldExternal (fi);
1620                                 fixed_buffer_cache.Add (fi, iff);
1621                                 return iff;
1622                         }
1623
1624                         if (o == FALSE)
1625                                 return null;
1626
1627                         return (IFixedBuffer)o;
1628                 }
1629
1630                 public static void VerifyModulesClsCompliance ()
1631                 {
1632                         Module[] modules = RootNamespace.Global.Modules;
1633                         if (modules == null)
1634                                 return;
1635
1636                         // The first module is generated assembly
1637                         for (int i = 1; i < modules.Length; ++i) {
1638                                 Module module = modules [i];
1639                                 if (!GetClsCompliantAttributeValue (module, null)) {
1640                                         Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
1641                                                       "to match the assembly", module.Name);
1642                                         return;
1643                                 }
1644                         }
1645                 }
1646
1647                 public static Type GetImportedIgnoreCaseClsType (string name)
1648                 {
1649                         foreach (Assembly a in RootNamespace.Global.Assemblies) {
1650                                 Type t = a.GetType (name, false, true);
1651                                 if (t == null)
1652                                         continue;
1653
1654                                 if (IsClsCompliant (t))
1655                                         return t;
1656                         }
1657                         return null;
1658                 }
1659
1660                 static bool GetClsCompliantAttributeValue (ICustomAttributeProvider attribute_provider, Assembly a) 
1661                 {
1662                         if (TypeManager.cls_compliant_attribute_type == null)
1663                                 return false;
1664
1665                         object[] cls_attr = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1666                         if (cls_attr.Length == 0) {
1667                                 if (a == null)
1668                                         return false;
1669
1670                                 return GetClsCompliantAttributeValue (a, null);
1671                         }
1672                         
1673                         return ((CLSCompliantAttribute)cls_attr [0]).IsCompliant;
1674                 }
1675
1676                 static bool AnalyzeTypeCompliance (Type type)
1677                 {
1678                         type = TypeManager.DropGenericTypeArguments (type);
1679                         DeclSpace ds = TypeManager.LookupDeclSpace (type);
1680                         if (ds != null) {
1681                                 return ds.IsClsComplianceRequired ();
1682                         }
1683
1684                         if (TypeManager.IsGenericParameter (type))
1685                                 return true;
1686
1687                         return GetClsCompliantAttributeValue (type, type.Assembly);
1688                 }
1689
1690                 // Registers the core type as we assume that they will never be obsolete which
1691                 // makes things easier for bootstrap and faster (we don't need to query Obsolete attribute).
1692                 public static void RegisterNonObsoleteType (Type type)
1693                 {
1694                         analyzed_types_obsolete [type] = FALSE;
1695                 }
1696
1697                 /// <summary>
1698                 /// Returns instance of ObsoleteAttribute when type is obsolete
1699                 /// </summary>
1700                 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1701                 {
1702                         object type_obsolete = analyzed_types_obsolete [type];
1703                         if (type_obsolete == FALSE)
1704                                 return null;
1705
1706                         if (type_obsolete != null)
1707                                 return (ObsoleteAttribute)type_obsolete;
1708
1709                         ObsoleteAttribute result = null;
1710                         if (TypeManager.HasElementType (type)) {
1711                                 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1712                         } else if (TypeManager.IsGenericParameter (type) || TypeManager.IsGenericType (type))
1713                                 return null;
1714                         else {
1715                                 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1716
1717                                 // Type is external, we can get attribute directly
1718                                 if (type_ds == null) {
1719                                         if (TypeManager.obsolete_attribute_type != null) {
1720                                                 object [] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1721                                                 if (attribute.Length == 1)
1722                                                         result = (ObsoleteAttribute) attribute [0];
1723                                         }
1724                                 } else {
1725                                         result = type_ds.GetObsoleteAttribute ();
1726                                 }
1727                         }
1728
1729                         // Cannot use .Add because of corlib bootstrap
1730                         analyzed_types_obsolete [type] = result == null ? FALSE : result;
1731                         return result;
1732                 }
1733
1734                 /// <summary>
1735                 /// Returns instance of ObsoleteAttribute when method is obsolete
1736                 /// </summary>
1737                 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1738                 {
1739                         IMethodData mc = TypeManager.GetMethod (mb);
1740                         if (mc != null) 
1741                                 return mc.GetObsoleteAttribute ();
1742
1743                         // compiler generated methods are not registered by AddMethod
1744                         if (mb.DeclaringType is TypeBuilder)
1745                                 return null;
1746
1747                         MemberInfo mi = TypeManager.GetPropertyFromAccessor (mb);
1748                         if (mi != null)
1749                                 return GetMemberObsoleteAttribute (mi);
1750
1751                         mi = TypeManager.GetEventFromAccessor (mb);
1752                         if (mi != null)
1753                                 return GetMemberObsoleteAttribute (mi);
1754
1755                         return GetMemberObsoleteAttribute (mb);
1756                 }
1757
1758                 /// <summary>
1759                 /// Returns instance of ObsoleteAttribute when member is obsolete
1760                 /// </summary>
1761                 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1762                 {
1763                         object type_obsolete = analyzed_member_obsolete [mi];
1764                         if (type_obsolete == FALSE)
1765                                 return null;
1766
1767                         if (type_obsolete != null)
1768                                 return (ObsoleteAttribute)type_obsolete;
1769
1770                         if ((mi.DeclaringType is TypeBuilder) || TypeManager.IsGenericType (mi.DeclaringType))
1771                                 return null;
1772
1773                         if (TypeManager.obsolete_attribute_type == null)
1774                                 return null;
1775
1776                         ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false)
1777                                 as ObsoleteAttribute;
1778                         analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1779                         return oa;
1780                 }
1781
1782                 /// <summary>
1783                 /// Common method for Obsolete error/warning reporting.
1784                 /// </summary>
1785                 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1786                 {
1787                         if (oa.IsError) {
1788                                 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1789                                 return;
1790                         }
1791
1792                         if (oa.Message == null || oa.Message.Length == 0) {
1793                                 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1794                                 return;
1795                         }
1796                         Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1797                 }
1798
1799                 public static bool IsConditionalMethodExcluded (MethodBase mb)
1800                 {
1801                         object excluded = analyzed_method_excluded [mb];
1802                         if (excluded != null)
1803                                 return excluded == TRUE ? true : false;
1804
1805                         if (TypeManager.conditional_attribute_type == null)
1806                                 return false;
1807
1808                         ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true)
1809                                 as ConditionalAttribute[];
1810                         if (attrs.Length == 0) {
1811                                 analyzed_method_excluded.Add (mb, FALSE);
1812                                 return false;
1813                         }
1814
1815                         foreach (ConditionalAttribute a in attrs) {
1816                                 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1817                                         analyzed_method_excluded.Add (mb, FALSE);
1818                                         return false;
1819                                 }
1820                         }
1821                         analyzed_method_excluded.Add (mb, TRUE);
1822                         return true;
1823                 }
1824
1825                 /// <summary>
1826                 /// Analyzes class whether it has attribute which has ConditionalAttribute
1827                 /// and its condition is not defined.
1828                 /// </summary>
1829                 public static bool IsAttributeExcluded (Type type)
1830                 {
1831                         if (!type.IsClass)
1832                                 return false;
1833
1834                         Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1835
1836                         // TODO: add caching
1837                         // TODO: merge all Type bases attribute caching to one cache to save memory
1838                         if (class_decl == null && TypeManager.conditional_attribute_type != null) {
1839                                 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1840                                 foreach (ConditionalAttribute ca in attributes) {
1841                                         if (RootContext.AllDefines.Contains (ca.ConditionString))
1842                                                 return false;
1843                                 }
1844                                 return attributes.Length > 0;
1845                         }
1846
1847                         return class_decl.IsExcluded ();
1848                 }
1849
1850                 public static Type GetCoClassAttribute (Type type)
1851                 {
1852                         TypeContainer tc = TypeManager.LookupInterface (type);
1853                         if (tc == null) {
1854                                 if (TypeManager.coclass_attr_type == null)
1855                                         return null;
1856
1857                                 object[] o = type.GetCustomAttributes (TypeManager.coclass_attr_type, false);
1858                                 if (o.Length < 1)
1859                                         return null;
1860                                 return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
1861                         }
1862
1863                         if (tc.OptAttributes == null || TypeManager.coclass_attr_type == null)
1864                                 return null;
1865
1866                         Attribute a = tc.OptAttributes.Search (TypeManager.coclass_attr_type);
1867                         if (a == null)
1868                                 return null;
1869
1870                         return a.GetCoClassAttributeValue ();
1871                 }
1872         }
1873 }