2005-09-21 Marek Safar <marek.safar@seznam.cz>
[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                                 }
527                         }
528 // TODO: reenable
529 //                      if (Type == TypeManager.methodimpl_attr_type &&
530 //                              pos_values.Length == 1 && ((Argument)pos_args [0]).Type == TypeManager.short_type &&
531 //                              !System.Enum.IsDefined (TypeManager.method_impl_options, pos_values [0])) {
532 //                                      Error_AttributeEmitError ("Incorrect argument value.");
533 //                      }
534
535                         //
536                         // Now we perform some checks on the positional args as they
537                         // cannot be null for a constructor which expects a parameter
538                         // of type object
539                         //
540
541                         ParameterData pd = TypeManager.GetParameterData (constructor);
542
543                         int last_real_param = pd.Count;
544                         if (pd.HasParams) {
545                                 // When the params is not filled we need to put one
546                                 if (last_real_param > pos_arg_count) {
547                                         object [] new_pos_values = new object [pos_arg_count + 1];
548                                         pos_values.CopyTo (new_pos_values, 0);
549                                         new_pos_values [pos_arg_count] = new object [] {} ;
550                                         pos_values = new_pos_values;
551                                 }
552                                 last_real_param--;
553                         }
554
555                         for (int j = 0; j < pos_arg_count; ++j) {
556                                 Argument a = (Argument) pos_args [j];
557                                 
558                                 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
559                                         Error_AttributeArgumentNotValid (Location);
560                                         return null;
561                                 }
562
563                                 object value = pos_values [j];
564                                 if (value != null && a.Type != value.GetType () && TypeManager.IsPrimitiveType (a.Type)) {
565                                         bool fail;
566                                         pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
567                                         if (fail) {
568                                                 // TODO: Can failed ?
569                                                 throw new NotImplementedException ();
570                                         }
571                                 }
572
573                                 if (j < last_real_param)
574                                         continue;
575                                 
576                                 if (j == last_real_param) {
577                                         object [] array = new object [pos_arg_count - last_real_param];
578                                         array [0] = pos_values [j];
579                                         pos_values [j] = array;
580                                         continue;
581                                 }
582
583                                 object [] params_array = (object []) pos_values [last_real_param];
584                                 params_array [j - last_real_param] = pos_values [j];
585                         }
586
587                         // Adjust the size of the pos_values if it had params
588                         if (last_real_param != pos_arg_count) {
589                                 object [] new_pos_values = new object [last_real_param + 1];
590                                 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
591                                 pos_values = new_pos_values;
592                         }
593
594                         if (named_arg_count > 0) {
595                                 prop_info_arr = new PropertyInfo [prop_infos.Count];
596                                 field_info_arr = new FieldInfo [field_infos.Count];
597                                 field_values_arr = new object [field_values.Count];
598                                 prop_values_arr = new object [prop_values.Count];
599
600                                 field_infos.CopyTo  (field_info_arr, 0);
601                                 field_values.CopyTo (field_values_arr, 0);
602
603                                 prop_values.CopyTo  (prop_values_arr, 0);
604                                 prop_infos.CopyTo   (prop_info_arr, 0);
605                         }
606
607                         return (ConstructorInfo) constructor;
608                 }
609
610                 /// <summary>
611                 ///   Get a string containing a list of valid targets for the attribute 'attr'
612                 /// </summary>
613                 public string GetValidTargets ()
614                 {
615                         StringBuilder sb = new StringBuilder ();
616                         AttributeTargets targets = GetAttributeUsage (null).ValidOn;
617
618                         if ((targets & AttributeTargets.Assembly) != 0)
619                                 sb.Append ("assembly, ");
620
621                         if ((targets & AttributeTargets.Module) != 0)
622                                 sb.Append ("module, ");
623
624                         if ((targets & AttributeTargets.Class) != 0)
625                                 sb.Append ("class, ");
626
627                         if ((targets & AttributeTargets.Struct) != 0)
628                                 sb.Append ("struct, ");
629
630                         if ((targets & AttributeTargets.Enum) != 0)
631                                 sb.Append ("enum, ");
632
633                         if ((targets & AttributeTargets.Constructor) != 0)
634                                 sb.Append ("constructor, ");
635
636                         if ((targets & AttributeTargets.Method) != 0)
637                                 sb.Append ("method, ");
638
639                         if ((targets & AttributeTargets.Property) != 0)
640                                 sb.Append ("property, indexer, ");
641
642                         if ((targets & AttributeTargets.Field) != 0)
643                                 sb.Append ("field, ");
644
645                         if ((targets & AttributeTargets.Event) != 0)
646                                 sb.Append ("event, ");
647
648                         if ((targets & AttributeTargets.Interface) != 0)
649                                 sb.Append ("interface, ");
650
651                         if ((targets & AttributeTargets.Parameter) != 0)
652                                 sb.Append ("parameter, ");
653
654                         if ((targets & AttributeTargets.Delegate) != 0)
655                                 sb.Append ("delegate, ");
656
657                         if ((targets & AttributeTargets.ReturnValue) != 0)
658                                 sb.Append ("return, ");
659
660 #if NET_2_0
661                         if ((targets & AttributeTargets.GenericParameter) != 0)
662                                 sb.Append ("type parameter, ");
663 #endif                  
664                         return sb.Remove (sb.Length - 2, 2).ToString ();
665                 }
666
667                 /// <summary>
668                 /// Returns AttributeUsage attribute for this type
669                 /// </summary>
670                 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
671                 {
672                         AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
673                         if (ua != null)
674                                 return ua;
675
676                         Class attr_class = TypeManager.LookupClass (Type);
677
678                         if (attr_class == null) {
679                                 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
680                                 ua = (AttributeUsageAttribute)usage_attr [0];
681                                 usage_attr_cache.Add (Type, ua);
682                                 return ua;
683                         }
684
685                         Attribute a = attr_class.OptAttributes == null
686                                 ? null
687                                 : attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, attr_class.EmitContext);
688
689                         ua = a == null
690                                 ? DefaultUsageAttribute 
691                                 : a.GetAttributeUsageAttribute (attr_class.EmitContext);
692
693                         usage_attr_cache.Add (Type, ua);
694                         return ua;
695                 }
696
697                 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
698                 {
699                         if (pos_values == null)
700                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
701                                 // But because a lot of attribute class code must be rewritten will be better to wait...
702                                 Resolve (ec);
703
704                         if (resolve_error)
705                                 return DefaultUsageAttribute;
706
707                         AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
708
709                         object field = GetPropertyValue ("AllowMultiple");
710                         if (field != null)
711                                 usage_attribute.AllowMultiple = (bool)field;
712
713                         field = GetPropertyValue ("Inherited");
714                         if (field != null)
715                                 usage_attribute.Inherited = (bool)field;
716
717                         return usage_attribute;
718                 }
719
720                 /// <summary>
721                 /// Returns custom name of indexer
722                 /// </summary>
723                 public string GetIndexerAttributeValue (EmitContext ec)
724                 {
725                         if (pos_values == null)
726                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
727                                 // But because a lot of attribute class code must be rewritten will be better to wait...
728                                 Resolve (ec);
729
730                         if (resolve_error)
731                                 return null;
732
733                         return pos_values [0] as string;
734                 }
735
736                 /// <summary>
737                 /// Returns condition of ConditionalAttribute
738                 /// </summary>
739                 public string GetConditionalAttributeValue (EmitContext ec)
740                 {
741                         if (pos_values == null)
742                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
743                                 // But because a lot of attribute class code must be rewritten will be better to wait...
744                                 Resolve (ec);
745
746                         if (resolve_error)
747                                 return null;
748
749                         return (string)pos_values [0];
750                 }
751
752                 /// <summary>
753                 /// Creates the instance of ObsoleteAttribute from this attribute instance
754                 /// </summary>
755                 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
756                 {
757                         if (pos_values == null)
758                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
759                                 // But because a lot of attribute class code must be rewritten will be better to wait...
760                                 Resolve (ec);
761
762                         if (resolve_error)
763                                 return null;
764
765                         if (pos_values == null || pos_values.Length == 0)
766                                 return new ObsoleteAttribute ();
767
768                         if (pos_values.Length == 1)
769                                 return new ObsoleteAttribute ((string)pos_values [0]);
770
771                         return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
772                 }
773
774                 /// <summary>
775                 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
776                 /// before ApplyAttribute. We need to resolve the arguments.
777                 /// This situation occurs when class deps is differs from Emit order.  
778                 /// </summary>
779                 public bool GetClsCompliantAttributeValue (EmitContext ec)
780                 {
781                         if (pos_values == null)
782                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
783                                 // But because a lot of attribute class code must be rewritten will be better to wait...
784                                 Resolve (ec);
785
786                         if (resolve_error)
787                                 return false;
788
789                         return (bool)pos_values [0];
790                 }
791
792                 /// <summary>
793                 /// Tests permitted SecurityAction for assembly or other types
794                 /// </summary>
795                 public bool CheckSecurityActionValidity (bool for_assembly)
796                 {
797                         SecurityAction action  = GetSecurityActionValue ();
798
799                         if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
800                                 return true;
801
802                         if (!for_assembly) {
803                                 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
804                                         Error_AttributeEmitError ("SecurityAction is out of range");
805                                         return false;
806                                 }
807
808                                 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
809                                         return true;
810                         }
811
812                         Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
813                         return false;
814                 }
815
816                 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
817                 {
818                         return (SecurityAction)pos_values [0];
819                 }
820
821                 /// <summary>
822                 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
823                 /// </summary>
824                 /// <returns></returns>
825                 public void ExtractSecurityPermissionSet (ListDictionary permissions)
826                 {
827                         Type orig_assembly_type = null;
828
829                         if (TypeManager.LookupDeclSpace (Type) != null) {
830                                 if (!RootContext.StdLib) {
831                                         orig_assembly_type = Type.GetType (Type.FullName);
832                                 } else {
833                                         string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
834                                         if (orig_version_path == null) {
835                                                 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
836                                                 return;
837                                         }
838
839                                         if (orig_sec_assembly == null) {
840                                                 string file = Path.Combine (orig_version_path, Driver.OutputFile);
841                                                 orig_sec_assembly = Assembly.LoadFile (file);
842                                         }
843
844                                         orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
845                                         if (orig_assembly_type == null) {
846                                                 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' was not found in previous version of assembly");
847                                                 return;
848                                         }
849                                 }
850                         }
851
852                         SecurityAttribute sa;
853                         // For all non-selfreferencing security attributes we can avoid all hacks
854                         if (orig_assembly_type == null) {
855                                 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
856
857                                 if (prop_info_arr != null) {
858                                         for (int i = 0; i < prop_info_arr.Length; ++i) {
859                                                 PropertyInfo pi = prop_info_arr [i];
860                                                 pi.SetValue (sa, prop_values_arr [i], null);
861                                         }
862                                 }
863                         } else {
864                                 // HACK: All security attributes have same ctor syntax
865                                 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
866
867                                 // All types are from newly created assembly but for invocation with old one we need to convert them
868                                 if (prop_info_arr != null) {
869                                         for (int i = 0; i < prop_info_arr.Length; ++i) {
870                                                 PropertyInfo emited_pi = prop_info_arr [i];
871                                                 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
872
873                                                 object old_instance = pi.PropertyType.IsEnum ?
874                                                         System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
875                                                         prop_values_arr [i];
876
877                                                 pi.SetValue (sa, old_instance, null);
878                                         }
879                                 }
880                         }
881
882                         IPermission perm;
883                         perm = sa.CreatePermission ();
884                         SecurityAction action = GetSecurityActionValue ();
885
886                         // IS is correct because for corlib we are using an instance from old corlib
887                         if (!(perm is System.Security.CodeAccessPermission)) {
888                                 switch (action) {
889                                         case SecurityAction.Demand:
890                                                 action = (SecurityAction)13;
891                                                 break;
892                                         case SecurityAction.LinkDemand:
893                                                 action = (SecurityAction)14;
894                                                 break;
895                                         case SecurityAction.InheritanceDemand:
896                                                 action = (SecurityAction)15;
897                                                 break;
898                                 }
899                         }
900
901                         PermissionSet ps = (PermissionSet)permissions [action];
902                         if (ps == null) {
903                                 if (sa is PermissionSetAttribute)
904                                         ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
905                                 else
906                                         ps = new PermissionSet (PermissionState.None);
907
908                                 permissions.Add (action, ps);
909                         } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
910                                 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
911                                 permissions [action] = ps;
912                         }
913                         ps.AddPermission (perm);
914                 }
915
916                 object GetValue (object value)
917                 {
918                         if (value is EnumConstant)
919                                 return ((EnumConstant) value).GetValue ();
920                         else
921                                 return value;                           
922                 }
923
924                 object GetPropertyValue (string name)
925                 {
926                         if (prop_info_arr == null)
927                                 return null;
928
929                         for (int i = 0; i < prop_info_arr.Length; ++i) {
930                                 if (prop_info_arr [i].Name == name)
931                                         return prop_values_arr [i];
932                         }
933
934                         return null;
935                 }
936
937                 object GetFieldValue (string name)
938                 {
939                         int i;
940                         if (field_info_arr == null)
941                                 return null;
942                         i = 0;
943                         foreach (FieldInfo fi in field_info_arr) {
944                                 if (fi.Name == name)
945                                         return GetValue (field_values_arr [i]);
946                                 i++;
947                         }
948                         return null;
949                 }
950
951                 //
952                 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
953                 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
954                 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
955                 //
956                 public UnmanagedMarshal GetMarshal (Attributable attr)
957                 {
958                         UnmanagedType UnmanagedType;
959                         if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
960                                 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
961                         else
962                                 UnmanagedType = (UnmanagedType) pos_values [0];
963
964                         object value = GetFieldValue ("SizeParamIndex");
965                         if (value != null && UnmanagedType != UnmanagedType.LPArray) {
966                                 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
967                                 return null;
968                         }
969
970                         object o = GetFieldValue ("ArraySubType");
971                         UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
972
973                         switch (UnmanagedType) {
974                         case UnmanagedType.CustomMarshaler: {
975                                 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
976                                         BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
977                                 if (define_custom == null) {
978                                         Report.RuntimeMissingSupport (Location, "set marshal info");
979                                         return null;
980                                 }
981                                 
982                                 object [] args = new object [4];
983                                 args [0] = GetFieldValue ("MarshalTypeRef");
984                                 args [1] = GetFieldValue ("MarshalCookie");
985                                 args [2] = GetFieldValue ("MarshalType");
986                                 args [3] = Guid.Empty;
987                                 return (UnmanagedMarshal) define_custom.Invoke (null, args);
988                         }
989                         case UnmanagedType.LPArray: {
990                                 object size_const = GetFieldValue ("SizeConst");
991                                 object size_param_index = GetFieldValue ("SizeParamIndex");
992
993                                 if ((size_const != null) || (size_param_index != null)) {
994                                         MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
995                                                 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
996                                         if (define_array == null) {
997                                                 Report.RuntimeMissingSupport (Location, "set marshal info");
998                                                 return null;
999                                         }
1000                                 
1001                                         object [] args = new object [3];
1002                                         args [0] = array_sub_type;
1003                                         args [1] = size_const == null ? -1 : size_const;
1004                                         args [2] = size_param_index == null ? -1 : size_param_index;
1005                                         return (UnmanagedMarshal) define_array.Invoke (null, args);
1006                                 }
1007                                 else
1008                                         return UnmanagedMarshal.DefineLPArray (array_sub_type);
1009                         }
1010                         case UnmanagedType.SafeArray:
1011                                 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1012
1013                         case UnmanagedType.ByValArray:
1014                                 FieldMember fm = attr as FieldMember;
1015                                 if (fm == null) {
1016                                         Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1017                                         return null;
1018                                 }
1019                                 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1020
1021                         case UnmanagedType.ByValTStr:
1022                                 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1023
1024                         default:
1025                                 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1026                         }
1027                 }
1028
1029                 public CharSet GetCharSetValue ()
1030                 {
1031                         return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1032                 }
1033
1034                 public MethodImplOptions GetMethodImplOptions ()
1035                 {
1036                         if (pos_values [0].GetType () != typeof (MethodImplOptions))
1037                                 return (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values [0]);
1038                         return (MethodImplOptions)pos_values [0];
1039                 }
1040
1041                 public LayoutKind GetLayoutKindValue ()
1042                 {
1043                         if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1044                                 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1045
1046                         return (LayoutKind)pos_values [0];
1047                 }
1048
1049                 /// <summary>
1050                 /// Emit attribute for Attributable symbol
1051                 /// </summary>
1052                 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
1053                 {
1054                         CustomAttributeBuilder cb = Resolve (ec);
1055                         if (cb == null)
1056                                 return;
1057
1058                         AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
1059                         if ((usage_attr.ValidOn & Target) == 0) {
1060                                 Report.Error (592, Location, "Attribute `{0}' is not valid on this declaration type. It is valid on `{1}' declarations only",
1061                                         GetSignatureForError (), GetValidTargets ());
1062                                 return;
1063                         }
1064
1065                         try {
1066                                 ias.ApplyAttributeBuilder (this, cb);
1067                         }
1068                         catch (Exception e) {
1069                                 Error_AttributeEmitError (e.Message);
1070                                 return;
1071                         }
1072
1073                         if (!usage_attr.AllowMultiple) {
1074                                 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
1075                                 if (emitted_targets == null) {
1076                                         emitted_targets = new ArrayList ();
1077                                         emitted_attr.Add (Type, emitted_targets);
1078                                 } else if (emitted_targets.Contains (Target)) {
1079                                         Report.Error (579, Location, "Duplicate `{0}' attribute", GetSignatureForError ());
1080                                         return;
1081                                 }
1082                                 emitted_targets.Add (Target);
1083                         }
1084
1085                         if (!RootContext.VerifyClsCompliance)
1086                                 return;
1087
1088                         // Here we are testing attribute arguments for array usage (error 3016)
1089                         if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
1090                                 if (Arguments == null)
1091                                         return;
1092
1093                                 ArrayList pos_args = (ArrayList) Arguments [0];
1094                                 if (pos_args != null) {
1095                                         foreach (Argument arg in pos_args) { 
1096                                                 // Type is undefined (was error 246)
1097                                                 if (arg.Type == null)
1098                                                         return;
1099
1100                                                 if (arg.Type.IsArray) {
1101                                                         Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1102                                                         return;
1103                                                 }
1104                                         }
1105                                 }
1106                         
1107                                 if (Arguments.Count < 2)
1108                                         return;
1109                         
1110                                 ArrayList named_args = (ArrayList) Arguments [1];
1111                                 foreach (DictionaryEntry de in named_args) {
1112                                         Argument arg  = (Argument) de.Value;
1113
1114                                         // Type is undefined (was error 246)
1115                                         if (arg.Type == null)
1116                                                 return;
1117
1118                                         if (arg.Type.IsArray) {
1119                                                 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1120                                                 return;
1121                                         }
1122                                 }
1123                         }
1124                 }
1125                 
1126                 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1127                                                           MethodAttributes flags, Type ret_type, Type [] param_types)
1128                 {
1129                         if (pos_values == null)
1130                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1131                                 // But because a lot of attribute class code must be rewritten will be better to wait...
1132                                 Resolve (ec);
1133
1134                         if (resolve_error)
1135                                 return null;
1136                         
1137                         string dll_name = (string)pos_values [0];
1138
1139                         // Default settings
1140                         CallingConvention cc = CallingConvention.Winapi;
1141                         CharSet charset = CodeGen.Module.DefaultCharSet;
1142                         bool preserve_sig = true;
1143                         string entry_point = name;
1144                         bool best_fit_mapping = false;
1145                         bool throw_on_unmappable = false;
1146                         bool exact_spelling = false;
1147                         bool set_last_error = false;
1148
1149                         bool best_fit_mapping_set = false;
1150                         bool throw_on_unmappable_set = false;
1151                         bool exact_spelling_set = false;
1152                         bool set_last_error_set = false;
1153
1154                         MethodInfo set_best_fit = null;
1155                         MethodInfo set_throw_on = null;
1156                         MethodInfo set_exact_spelling = null;
1157                         MethodInfo set_set_last_error = null;
1158
1159                         if (field_info_arr != null) {
1160
1161                                 for (int i = 0; i < field_info_arr.Length; i++) {
1162                                         switch (field_info_arr [i].Name) {
1163                                                 case "BestFitMapping":
1164                                                         best_fit_mapping = (bool) field_values_arr [i];
1165                                                         best_fit_mapping_set = true;
1166                                                         break;
1167                                                 case "CallingConvention":
1168                                                         cc = (CallingConvention) field_values_arr [i];
1169                                                         break;
1170                                                 case "CharSet":
1171                                                         charset = (CharSet) field_values_arr [i];
1172                                                         break;
1173                                                 case "EntryPoint":
1174                                                         entry_point = (string) field_values_arr [i];
1175                                                         break;
1176                                                 case "ExactSpelling":
1177                                                         exact_spelling = (bool) field_values_arr [i];
1178                                                         exact_spelling_set = true;
1179                                                         break;
1180                                                 case "PreserveSig":
1181                                                         preserve_sig = (bool) field_values_arr [i];
1182                                                         break;
1183                                                 case "SetLastError":
1184                                                         set_last_error = (bool) field_values_arr [i];
1185                                                         set_last_error_set = true;
1186                                                         break;
1187                                                 case "ThrowOnUnmappableChar":
1188                                                         throw_on_unmappable = (bool) field_values_arr [i];
1189                                                         throw_on_unmappable_set = true;
1190                                                         break;
1191                                                 default: 
1192                                                         throw new InternalErrorException (field_info_arr [i].ToString ());
1193                                         }
1194                                 }
1195                         }
1196
1197                         if (throw_on_unmappable_set || best_fit_mapping_set || exact_spelling_set || set_last_error_set) {
1198                                 set_best_fit = typeof (MethodBuilder).GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1199                                 set_throw_on = typeof (MethodBuilder).GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1200                                 set_exact_spelling = typeof (MethodBuilder).GetMethod ("set_ExactSpelling", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1201                                 set_set_last_error = typeof (MethodBuilder).GetMethod ("set_SetLastError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1202
1203                                 if ((set_best_fit == null) || (set_throw_on == null) || (set_exact_spelling == null) || (set_set_last_error == null)) {
1204                                         Report.Error (-1, Location,
1205                                                                   "The ThrowOnUnmappableChar, BestFitMapping, SetLastError, and ExactSpelling attributes can only be emitted when running on the mono runtime.");
1206                                         return null;
1207                                 }
1208                         }
1209
1210                         try {
1211                                 MethodBuilder mb = builder.DefinePInvokeMethod (
1212                                         name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1213                                         CallingConventions.Standard, ret_type, param_types, cc, charset);
1214
1215                                 if (preserve_sig)
1216                                         mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1217
1218                                 if (throw_on_unmappable_set)
1219                                         set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1220                                 if (best_fit_mapping_set)
1221                                         set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1222                                 if (exact_spelling_set)
1223                                         set_exact_spelling.Invoke  (mb, 0, null, new object [] { exact_spelling }, null);
1224                                 if (set_last_error_set)
1225                                         set_set_last_error.Invoke  (mb, 0, null, new object [] { set_last_error }, null);
1226                         
1227                                 return mb;
1228                         }
1229                         catch (ArgumentException e) {
1230                                 Error_AttributeEmitError (e.Message);
1231                                 return null;
1232                         }
1233                 }
1234
1235                 private Expression GetValue () 
1236                 {
1237                         if ((Arguments == null) || (Arguments.Count < 1))
1238                                 return null;
1239                         ArrayList al = (ArrayList) Arguments [0];
1240                         if ((al == null) || (al.Count < 1))
1241                                 return null;
1242                         Argument arg = (Argument) al [0];
1243                         if ((arg == null) || (arg.Expr == null))
1244                                 return null;
1245                         return arg.Expr;
1246                 }
1247
1248                 public string GetString () 
1249                 {
1250                         Expression e = GetValue ();
1251                         if (e is StringLiteral)
1252                                 return (e as StringLiteral).Value;
1253                         return null;
1254                 }
1255
1256                 public bool GetBoolean () 
1257                 {
1258                         Expression e = GetValue ();
1259                         if (e is BoolLiteral)
1260                                 return (e as BoolLiteral).Value;
1261                         return false;
1262                 }
1263         }
1264         
1265
1266         /// <summary>
1267         /// For global attributes (assembly, module) we need special handling.
1268         /// Attributes can be located in the several files
1269         /// </summary>
1270         public class GlobalAttribute: Attribute
1271         {
1272                 public readonly NamespaceEntry ns;
1273
1274                 public GlobalAttribute (TypeContainer container, string target, 
1275                                         Expression left_expr, string identifier, ArrayList args, Location loc, bool nameEscaped):
1276                         base (target, left_expr, identifier, args, loc, nameEscaped)
1277                 {
1278                         ns = container.NamespaceEntry;
1279                 }
1280
1281                 void Enter ()
1282                 {
1283                         // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1284                         // each time a new file is parsed.  However, we need to use the NamespaceEntry
1285                         // in effect where the attribute was used.  Since code elsewhere cannot assume
1286                         // that the NamespaceEntry is right, just overwrite it.
1287                         //
1288                         // Precondition: RootContext.Tree.Types == null
1289
1290                         if (RootContext.Tree.Types.NamespaceEntry != null)
1291                                 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1292
1293                         RootContext.Tree.Types.NamespaceEntry = ns;
1294                 }
1295
1296                 void Leave ()
1297                 {
1298                         RootContext.Tree.Types.NamespaceEntry = null;
1299                 }
1300
1301                 protected override FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec, bool silent)
1302                 {
1303                         try {
1304                                 Enter ();
1305                                 return base.ResolveAsTypeStep (expr, ec, silent);
1306                         }
1307                         finally {
1308                                 Leave ();
1309                         }
1310                 }
1311
1312
1313                 protected override FullNamedExpression ResolveAsTypeTerminal (Expression expr, EmitContext ec, bool silent)
1314                 {
1315                         try {
1316                                 Enter ();
1317                                 return base.ResolveAsTypeTerminal (expr, ec, silent);
1318                         }
1319                         finally {
1320                                 Leave ();
1321                         }
1322                 }
1323
1324                 protected override ConstructorInfo ResolveArguments (EmitContext ec)
1325                 {
1326                         try {
1327                                 Enter ();
1328                                 return base.ResolveArguments (ec);
1329                         }
1330                         finally {
1331                                 Leave ();
1332                         }
1333                 }
1334         }
1335
1336         public class Attributes {
1337                 public ArrayList Attrs;
1338
1339                 public Attributes (Attribute a)
1340                 {
1341                         Attrs = new ArrayList ();
1342                         Attrs.Add (a);
1343                 }
1344
1345                 public Attributes (ArrayList attrs)
1346                 {
1347                         Attrs = attrs;
1348                 }
1349
1350                 public void AddAttributes (ArrayList attrs)
1351                 {
1352                         Attrs.AddRange (attrs);
1353                 }
1354
1355                 /// <summary>
1356                 /// Checks whether attribute target is valid for the current element
1357                 /// </summary>
1358                 public bool CheckTargets (Attributable member)
1359                 {
1360                         string[] valid_targets = member.ValidAttributeTargets;
1361                         foreach (Attribute a in Attrs) {
1362                                 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1363                                         a.Target = member.AttributeTargets;
1364                                         continue;
1365                                 }
1366
1367                                 // TODO: we can skip the first item
1368                                 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1369                                         switch (a.ExplicitTarget) {
1370                                                 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1371                                                 case "param": a.Target = AttributeTargets.Parameter; continue;
1372                                                 case "field": a.Target = AttributeTargets.Field; continue;
1373                                                 case "method": a.Target = AttributeTargets.Method; continue;
1374                                                 case "property": a.Target = AttributeTargets.Property; continue;
1375                                         }
1376                                         throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1377                                 }
1378
1379                                 StringBuilder sb = new StringBuilder ();
1380                                 foreach (string s in valid_targets) {
1381                                         sb.Append (s);
1382                                         sb.Append (", ");
1383                                 }
1384                                 sb.Remove (sb.Length - 2, 2);
1385                                 Report.Error (657, a.Location, "`{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are `{1}'", a.ExplicitTarget, sb.ToString ());
1386                                 return false;
1387                         }
1388                         return true;
1389                 }
1390
1391                 public Attribute Search (Type t, EmitContext ec)
1392                 {
1393                         foreach (Attribute a in Attrs) {
1394                                 if (a.ResolveType (ec) == t)
1395                                         return a;
1396                         }
1397                         return null;
1398                 }
1399
1400                 /// <summary>
1401                 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1402                 /// </summary>
1403                 public Attribute[] SearchMulti (Type t, EmitContext ec)
1404                 {
1405                         ArrayList ar = null;
1406
1407                         foreach (Attribute a in Attrs) {
1408                                 if (a.ResolveType (ec) == t) {
1409                                         if (ar == null)
1410                                                 ar = new ArrayList ();
1411                                         ar.Add (a);
1412                                 }
1413                         }
1414
1415                         return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1416                 }
1417
1418                 public void Emit (EmitContext ec, Attributable ias)
1419                 {
1420                         CheckTargets (ias);
1421
1422                         ListDictionary ld = new ListDictionary ();
1423
1424                         foreach (Attribute a in Attrs)
1425                                 a.Emit (ec, ias, ld);
1426                 }
1427
1428                 public bool Contains (Type t, EmitContext ec)
1429                 {
1430                         return Search (t, ec) != null;
1431                 }
1432         }
1433
1434         /// <summary>
1435         /// Helper class for attribute verification routine.
1436         /// </summary>
1437         sealed class AttributeTester
1438         {
1439                 static PtrHashtable analyzed_types = new PtrHashtable ();
1440                 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1441                 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1442                 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1443
1444 #if NET_2_0
1445                 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1446 #endif
1447
1448                 static object TRUE = new object ();
1449                 static object FALSE = new object ();
1450
1451                 private AttributeTester ()
1452                 {
1453                 }
1454
1455                 public enum Result {
1456                         Ok,
1457                         RefOutArrayError,
1458                         ArrayArrayError
1459                 }
1460
1461                 /// <summary>
1462                 /// Returns true if parameters of two compared methods are CLS-Compliant.
1463                 /// It tests differing only in ref or out, or in array rank.
1464                 /// </summary>
1465                 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b) 
1466                 {
1467                         if (types_a == null || types_b == null)
1468                                 return Result.Ok;
1469
1470                         if (types_a.Length != types_b.Length)
1471                                 return Result.Ok;
1472
1473                         Result result = Result.Ok;
1474                         for (int i = 0; i < types_b.Length; ++i) {
1475                                 Type aType = types_a [i];
1476                                 Type bType = types_b [i];
1477
1478                                 if (aType.IsArray && bType.IsArray) {
1479                                         Type a_el_type = aType.GetElementType ();
1480                                         Type b_el_type = bType.GetElementType ();
1481                                         if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1482                                                 result = Result.RefOutArrayError;
1483                                                 continue;
1484                                         }
1485
1486                                         if (a_el_type.IsArray || b_el_type.IsArray) {
1487                                                 result = Result.ArrayArrayError;
1488                                                 continue;
1489                                         }
1490                                 }
1491
1492                                 Type aBaseType = aType;
1493                                 bool is_either_ref_or_out = false;
1494
1495                                 if (aType.IsByRef || aType.IsPointer) {
1496                                         aBaseType = aType.GetElementType ();
1497                                         is_either_ref_or_out = true;
1498                                 }
1499
1500                                 Type bBaseType = bType;
1501                                 if (bType.IsByRef || bType.IsPointer) 
1502                                 {
1503                                         bBaseType = bType.GetElementType ();
1504                                         is_either_ref_or_out = !is_either_ref_or_out;
1505                                 }
1506
1507                                 if (aBaseType != bBaseType)
1508                                         return Result.Ok;
1509
1510                                 if (is_either_ref_or_out)
1511                                         result = Result.RefOutArrayError;
1512                         }
1513                         return result;
1514                 }
1515
1516                 /// <summary>
1517                 /// Goes through all parameters and test if they are CLS-Compliant.
1518                 /// </summary>
1519                 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1520                 {
1521                         if (fixedParameters == null)
1522                                 return true;
1523
1524                         foreach (Parameter arg in fixedParameters) {
1525                                 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1526                                         Report.Error (3001, loc, "Argument type `{0}' is not CLS-compliant", arg.GetSignatureForError ());
1527                                         return false;
1528                                 }
1529                         }
1530                         return true;
1531                 }
1532
1533
1534                 /// <summary>
1535                 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1536                 /// </summary>
1537                 public static bool IsClsCompliant (Type type) 
1538                 {
1539                         if (type == null)
1540                                 return true;
1541
1542                         object type_compliance = analyzed_types[type];
1543                         if (type_compliance != null)
1544                                 return type_compliance == TRUE;
1545
1546                         if (type.IsPointer) {
1547                                 analyzed_types.Add (type, null);
1548                                 return false;
1549                         }
1550
1551                         bool result;
1552                         if (type.IsArray || type.IsByRef)       {
1553                                 result = IsClsCompliant (TypeManager.GetElementType (type));
1554                         } else {
1555                                 result = AnalyzeTypeCompliance (type);
1556                         }
1557                         analyzed_types.Add (type, result ? TRUE : FALSE);
1558                         return result;
1559                 }        
1560         
1561                 /// <summary>
1562                 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1563                 /// </summary>
1564                 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1565                 {
1566                         FieldBase fb = TypeManager.GetField (fi);
1567                         if (fb != null) {
1568                                 return fb as IFixedBuffer;
1569                         }
1570
1571 #if NET_2_0
1572                         object o = fixed_buffer_cache [fi];
1573                         if (o == null) {
1574                                 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1575                                         fixed_buffer_cache.Add (fi, FALSE);
1576                                         return null;
1577                                 }
1578                                 
1579                                 IFixedBuffer iff = new FixedFieldExternal (fi);
1580                                 fixed_buffer_cache.Add (fi, iff);
1581                                 return iff;
1582                         }
1583
1584                         if (o == FALSE)
1585                                 return null;
1586
1587                         return (IFixedBuffer)o;
1588 #else
1589                         return null;
1590 #endif
1591                 }
1592
1593                 public static void VerifyModulesClsCompliance ()
1594                 {
1595                         Module[] modules = TypeManager.Modules;
1596                         if (modules == null)
1597                                 return;
1598
1599                         // The first module is generated assembly
1600                         for (int i = 1; i < modules.Length; ++i) {
1601                                 Module module = modules [i];
1602                                 if (!IsClsCompliant (module)) {
1603                                         Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1604                                         return;
1605                                 }
1606                         }
1607                 }
1608
1609                 public static Type GetImportedIgnoreCaseClsType (string name)
1610                 {
1611                         foreach (Assembly a in TypeManager.GetAssemblies ()) {
1612                                 Type t = a.GetType (name, false, true);
1613                                 if (t == null)
1614                                         continue;
1615
1616                                 if (IsClsCompliant (t))
1617                                         return t;
1618                         }
1619                         return null;
1620                 }
1621
1622                 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider) 
1623                 {
1624                         object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1625                         if (CompliantAttribute.Length == 0)
1626                                 return false;
1627
1628                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1629                 }
1630
1631                 static bool AnalyzeTypeCompliance (Type type)
1632                 {
1633                         DeclSpace ds = TypeManager.LookupDeclSpace (type);
1634                         if (ds != null) {
1635                                 return ds.IsClsCompliaceRequired (ds.Parent);
1636                         }
1637
1638                         object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1639                         if (CompliantAttribute.Length == 0) 
1640                                 return IsClsCompliant (type.Assembly);
1641
1642                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1643                 }
1644
1645                 /// <summary>
1646                 /// Returns instance of ObsoleteAttribute when type is obsolete
1647                 /// </summary>
1648                 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1649                 {
1650                         object type_obsolete = analyzed_types_obsolete [type];
1651                         if (type_obsolete == FALSE)
1652                                 return null;
1653
1654                         if (type_obsolete != null)
1655                                 return (ObsoleteAttribute)type_obsolete;
1656
1657                         ObsoleteAttribute result = null;
1658                         if (type.IsByRef || type.IsArray || type.IsPointer) {
1659                                 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1660                         } else {
1661                                 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1662
1663                                 // Type is external, we can get attribute directly
1664                                 if (type_ds == null) {
1665                                         object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1666                                         if (attribute.Length == 1)
1667                                                 result = (ObsoleteAttribute)attribute [0];
1668                                 } else {
1669                                         result = type_ds.GetObsoleteAttribute ();
1670                                 }
1671                         }
1672
1673                         analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1674                         return result;
1675                 }
1676
1677                 /// <summary>
1678                 /// Returns instance of ObsoleteAttribute when method is obsolete
1679                 /// </summary>
1680                 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1681                 {
1682                         IMethodData mc = TypeManager.GetMethod (mb);
1683                         if (mc != null) 
1684                                 return mc.GetObsoleteAttribute ();
1685
1686                         // compiler generated methods are not registered by AddMethod
1687                         if (mb.DeclaringType is TypeBuilder)
1688                                 return null;
1689
1690                         if (mb.IsSpecialName) {
1691                                 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1692                                 if (pi != null) {
1693                                         // FIXME: This is buggy as properties from this assembly are included as well
1694                                         return null;
1695                                         //return GetMemberObsoleteAttribute (pi);
1696                                 }
1697                         }
1698
1699                         return GetMemberObsoleteAttribute (mb);
1700                 }
1701
1702                 /// <summary>
1703                 /// Returns instance of ObsoleteAttribute when member is obsolete
1704                 /// </summary>
1705                 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1706                 {
1707                         object type_obsolete = analyzed_member_obsolete [mi];
1708                         if (type_obsolete == FALSE)
1709                                 return null;
1710
1711                         if (type_obsolete != null)
1712                                 return (ObsoleteAttribute)type_obsolete;
1713
1714                         ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1715                         analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1716                         return oa;
1717                 }
1718
1719                 /// <summary>
1720                 /// Common method for Obsolete error/warning reporting.
1721                 /// </summary>
1722                 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1723                 {
1724                         if (oa.IsError) {
1725                                 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1726                                 return;
1727                         }
1728
1729                         if (oa.Message == null) {
1730                                 Report.Warning (612, loc, "`{0}' is obsolete", member);
1731                                 return;
1732                         }
1733                         if (RootContext.WarningLevel >= 2)
1734                                 Report.Warning (618, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1735                 }
1736
1737                 public static bool IsConditionalMethodExcluded (MethodBase mb)
1738                 {
1739                         object excluded = analyzed_method_excluded [mb];
1740                         if (excluded != null)
1741                                 return excluded == TRUE ? true : false;
1742                         
1743                         ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1744                         if (attrs.Length == 0) {
1745                                 analyzed_method_excluded.Add (mb, FALSE);
1746                                 return false;
1747                         }
1748
1749                         foreach (ConditionalAttribute a in attrs) {
1750                                 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1751                                         analyzed_method_excluded.Add (mb, FALSE);
1752                                         return false;
1753                                 }
1754                         }
1755                         analyzed_method_excluded.Add (mb, TRUE);
1756                         return true;
1757                 }
1758
1759                 /// <summary>
1760                 /// Analyzes class whether it has attribute which has ConditionalAttribute
1761                 /// and its condition is not defined.
1762                 /// </summary>
1763                 public static bool IsAttributeExcluded (Type type)
1764                 {
1765                         if (!type.IsClass)
1766                                 return false;
1767
1768                         Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1769
1770                         // TODO: add caching
1771                         // TODO: merge all Type bases attribute caching to one cache to save memory
1772                         if (class_decl == null) {
1773                                 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1774                                 foreach (ConditionalAttribute ca in attributes) {
1775                                         if (RootContext.AllDefines.Contains (ca.ConditionString))
1776                                                 return false;
1777                                 }
1778                                 return attributes.Length > 0;
1779                         }
1780
1781                         return class_decl.IsExcluded ();
1782                 }
1783         }
1784 }