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