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