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