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