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