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