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