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