In gmcs:
[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), 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                 static 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                 public object GetParameterDefaultValue ()
1077                 {
1078                         return pos_values [0];
1079                 }
1080
1081                 /// <summary>
1082                 /// Emit attribute for Attributable symbol
1083                 /// </summary>
1084                 public void Emit (ListDictionary allEmitted)
1085                 {
1086                         CustomAttributeBuilder cb = Resolve ();
1087                         if (cb == null)
1088                                 return;
1089
1090                         AttributeUsageAttribute usage_attr = GetAttributeUsage ();
1091                         if ((usage_attr.ValidOn & Target) == 0) {
1092                                 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1093                                               "It is valid on `{1}' declarations only",
1094                                         GetSignatureForError (), GetValidTargets ());
1095                                 return;
1096                         }
1097
1098                         try {
1099                                 owner.ApplyAttributeBuilder (this, cb);
1100                         }
1101                         catch (Exception e) {
1102                                 Error_AttributeEmitError (e.Message);
1103                                 return;
1104                         }
1105
1106                         if (!usage_attr.AllowMultiple && allEmitted != null) {
1107                                 if (allEmitted.Contains (this)) {
1108                                         ArrayList a = allEmitted [this] as ArrayList;
1109                                         if (a == null) {
1110                                                 a = new ArrayList (2);
1111                                                 allEmitted [this] = a;
1112                                         }
1113                                         a.Add (this);
1114                                 } else {
1115                                         allEmitted.Add (this, null);
1116                                 }
1117                         }
1118
1119                         if (!RootContext.VerifyClsCompliance)
1120                                 return;
1121
1122                         // Here we are testing attribute arguments for array usage (error 3016)
1123                         if (owner.IsClsComplianceRequired ()) {
1124                                 if (PosArguments != null) {
1125                                         foreach (Argument arg in PosArguments) { 
1126                                                 // Type is undefined (was error 246)
1127                                                 if (arg.Type == null)
1128                                                         return;
1129
1130                                                 if (arg.Type.IsArray) {
1131                                                         Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1132                                                         return;
1133                                                 }
1134                                         }
1135                                 }
1136                         
1137                                 if (NamedArguments == null)
1138                                         return;
1139                         
1140                                 foreach (DictionaryEntry de in NamedArguments) {
1141                                         Argument arg  = (Argument) de.Value;
1142
1143                                         // Type is undefined (was error 246)
1144                                         if (arg.Type == null)
1145                                                 return;
1146
1147                                         if (arg.Type.IsArray) {
1148                                                 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1149                                                 return;
1150                                         }
1151                                 }
1152                         }
1153                 }
1154                 
1155                 public MethodBuilder DefinePInvokeMethod (TypeBuilder builder, string name,
1156                                                           MethodAttributes flags, Type ret_type, Type [] param_types)
1157                 {
1158                         if (pos_values == null)
1159                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1160                                 // But because a lot of attribute class code must be rewritten will be better to wait...
1161                                 Resolve ();
1162
1163                         if (resolve_error)
1164                                 return null;
1165                         
1166                         string dll_name = (string)pos_values [0];
1167
1168                         // Default settings
1169                         CallingConvention cc = CallingConvention.Winapi;
1170                         CharSet charset = CodeGen.Module.DefaultCharSet;
1171                         bool preserve_sig = true;
1172                         string entry_point = name;
1173                         bool best_fit_mapping = false;
1174                         bool throw_on_unmappable = false;
1175                         bool exact_spelling = false;
1176                         bool set_last_error = false;
1177
1178                         bool best_fit_mapping_set = false;
1179                         bool throw_on_unmappable_set = false;
1180                         bool exact_spelling_set = false;
1181                         bool set_last_error_set = false;
1182
1183                         MethodInfo set_best_fit = null;
1184                         MethodInfo set_throw_on = null;
1185                         MethodInfo set_exact_spelling = null;
1186                         MethodInfo set_set_last_error = null;
1187
1188                         if (field_info_arr != null) {
1189                                 
1190                                 for (int i = 0; i < field_info_arr.Length; i++) {
1191                                         switch (field_info_arr [i].Name) {
1192                                         case "BestFitMapping":
1193                                                 best_fit_mapping = (bool) field_values_arr [i];
1194                                                 best_fit_mapping_set = true;
1195                                                 break;
1196                                         case "CallingConvention":
1197                                                 cc = (CallingConvention) field_values_arr [i];
1198                                                 break;
1199                                         case "CharSet":
1200                                                 charset = (CharSet) field_values_arr [i];
1201                                                 break;
1202                                         case "EntryPoint":
1203                                                 entry_point = (string) field_values_arr [i];
1204                                                 break;
1205                                         case "ExactSpelling":
1206                                                 exact_spelling = (bool) field_values_arr [i];
1207                                                 exact_spelling_set = true;
1208                                                 break;
1209                                         case "PreserveSig":
1210                                                 preserve_sig = (bool) field_values_arr [i];
1211                                                 break;
1212                                         case "SetLastError":
1213                                                 set_last_error = (bool) field_values_arr [i];
1214                                                 set_last_error_set = true;
1215                                                 break;
1216                                         case "ThrowOnUnmappableChar":
1217                                                 throw_on_unmappable = (bool) field_values_arr [i];
1218                                                 throw_on_unmappable_set = true;
1219                                                 break;
1220                                         default: 
1221                                                 throw new InternalErrorException (field_info_arr [i].ToString ());
1222                                         }
1223                                 }
1224                         }
1225                         
1226                         if (throw_on_unmappable_set || best_fit_mapping_set || exact_spelling_set || set_last_error_set) {
1227                                 set_best_fit = typeof (MethodBuilder).
1228                                         GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1229                                 set_throw_on = typeof (MethodBuilder).
1230                                         GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1231                                 set_exact_spelling = typeof (MethodBuilder).
1232                                         GetMethod ("set_ExactSpelling", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1233                                 set_set_last_error = typeof (MethodBuilder).
1234                                         GetMethod ("set_SetLastError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1235
1236                                 if ((set_best_fit == null) || (set_throw_on == null) ||
1237                                     (set_exact_spelling == null) || (set_set_last_error == null)) {
1238                                         Report.Error (-1, Location,
1239                                                                   "The ThrowOnUnmappableChar, BestFitMapping, SetLastError, " +
1240                                                       "and ExactSpelling attributes can only be emitted when running on the mono runtime.");
1241                                         return null;
1242                                 }
1243                         }
1244
1245                         try {
1246                                 MethodBuilder mb = builder.DefinePInvokeMethod (
1247                                         name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1248                                         CallingConventions.Standard, ret_type, param_types, cc, charset);
1249
1250                                 if (preserve_sig)
1251                                         mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1252
1253                                 if (throw_on_unmappable_set)
1254                                         set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1255                                 if (best_fit_mapping_set)
1256                                         set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1257                                 if (exact_spelling_set)
1258                                         set_exact_spelling.Invoke  (mb, 0, null, new object [] { exact_spelling }, null);
1259                                 if (set_last_error_set)
1260                                         set_set_last_error.Invoke  (mb, 0, null, new object [] { set_last_error }, null);
1261                         
1262                                 return mb;
1263                         }
1264                         catch (ArgumentException e) {
1265                                 Error_AttributeEmitError (e.Message);
1266                                 return null;
1267                         }
1268                 }
1269
1270                 private Expression GetValue () 
1271                 {
1272                         if (PosArguments == null || PosArguments.Count < 1)
1273                                 return null;
1274
1275                         return ((Argument) PosArguments [0]).Expr;
1276                 }
1277
1278                 public string GetString () 
1279                 {
1280                         Expression e = GetValue ();
1281                         if (e is StringLiteral)
1282                                 return (e as StringLiteral).Value;
1283                         return null;
1284                 }
1285
1286                 public bool GetBoolean () 
1287                 {
1288                         Expression e = GetValue ();
1289                         if (e is BoolLiteral)
1290                                 return (e as BoolLiteral).Value;
1291                         return false;
1292                 }
1293         }
1294         
1295
1296         /// <summary>
1297         /// For global attributes (assembly, module) we need special handling.
1298         /// Attributes can be located in the several files
1299         /// </summary>
1300         public class GlobalAttribute : Attribute
1301         {
1302                 public readonly NamespaceEntry ns;
1303
1304                 public GlobalAttribute (NamespaceEntry ns, string target, 
1305                                         Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped):
1306                         base (target, left_expr, identifier, args, loc, nameEscaped)
1307                 {
1308                         this.ns = ns;
1309                 }
1310
1311                 void Enter ()
1312                 {
1313                         // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1314                         // each time a new file is parsed.  However, we need to use the NamespaceEntry
1315                         // in effect where the attribute was used.  Since code elsewhere cannot assume
1316                         // that the NamespaceEntry is right, just overwrite it.
1317                         //
1318                         // Precondition: RootContext.Tree.Types == null
1319
1320                         if (RootContext.Tree.Types.NamespaceEntry != null)
1321                                 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1322
1323                         RootContext.Tree.Types.NamespaceEntry = ns;
1324                 }
1325
1326                 void Leave ()
1327                 {
1328                         RootContext.Tree.Types.NamespaceEntry = null;
1329                 }
1330
1331                 protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
1332                 {
1333                         try {
1334                                 Enter ();
1335                                 return base.ResolveAsTypeTerminal (expr, ec, silent);
1336                         }
1337                         finally {
1338                                 Leave ();
1339                         }
1340                 }
1341
1342                 protected override ConstructorInfo ResolveConstructor (EmitContext ec)
1343                 {
1344                         try {
1345                                 Enter ();
1346                                 return base.ResolveConstructor (ec);
1347                         }
1348                         finally {
1349                                 Leave ();
1350                         }
1351                 }
1352
1353                 protected override bool ResolveNamedArguments (EmitContext ec)
1354                 {
1355                         try {
1356                                 Enter ();
1357                                 return base.ResolveNamedArguments (ec);
1358                         }
1359                         finally {
1360                                 Leave ();
1361                         }
1362                 }
1363         }
1364
1365         public class Attributes {
1366                 public readonly ArrayList Attrs;
1367
1368                 public Attributes (Attribute a)
1369                 {
1370                         Attrs = new ArrayList ();
1371                         Attrs.Add (a);
1372                 }
1373
1374                 public Attributes (ArrayList attrs)
1375                 {
1376                         Attrs = attrs;
1377                 }
1378
1379                 public void AddAttributes (ArrayList attrs)
1380                 {
1381                         Attrs.AddRange (attrs);
1382                 }
1383
1384                 public void AttachTo (Attributable attributable)
1385                 {
1386                         foreach (Attribute a in Attrs)
1387                                 a.AttachTo (attributable);
1388                 }
1389
1390                 /// <summary>
1391                 /// Checks whether attribute target is valid for the current element
1392                 /// </summary>
1393                 public bool CheckTargets ()
1394                 {
1395                         foreach (Attribute a in Attrs) {
1396                                 if (!a.CheckTarget ())
1397                                         return false;
1398                         }
1399                         return true;
1400                 }
1401
1402                 public Attribute Search (Type t)
1403                 {
1404                         foreach (Attribute a in Attrs) {
1405                                 if (a.ResolveType () == t)
1406                                         return a;
1407                         }
1408                         return null;
1409                 }
1410
1411                 /// <summary>
1412                 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1413                 /// </summary>
1414                 public Attribute[] SearchMulti (Type t)
1415                 {
1416                         ArrayList ar = null;
1417
1418                         foreach (Attribute a in Attrs) {
1419                                 if (a.ResolveType () == t) {
1420                                         if (ar == null)
1421                                                 ar = new ArrayList ();
1422                                         ar.Add (a);
1423                                 }
1424                         }
1425
1426                         return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1427                 }
1428
1429                 public void Emit ()
1430                 {
1431                         CheckTargets ();
1432
1433                         ListDictionary ld = Attrs.Count > 1 ? new ListDictionary () : null;
1434
1435                         foreach (Attribute a in Attrs)
1436                                 a.Emit (ld);
1437
1438                         if (ld == null || ld.Count == 0)
1439                                 return;
1440
1441                         foreach (DictionaryEntry d in ld) {
1442                                 if (d.Value == null)
1443                                         continue;
1444
1445                                 foreach (Attribute collision in (ArrayList)d.Value)
1446                                         Report.SymbolRelatedToPreviousError (collision.Location, "");
1447
1448                                 Attribute a = (Attribute)d.Key;
1449                                 Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times", a.GetSignatureForError ());
1450                         }
1451                 }
1452
1453                 public bool Contains (Type t)
1454                 {
1455                         return Search (t) != null;
1456                 }
1457         }
1458
1459         /// <summary>
1460         /// Helper class for attribute verification routine.
1461         /// </summary>
1462         sealed class AttributeTester
1463         {
1464                 static PtrHashtable analyzed_types = new PtrHashtable ();
1465                 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1466                 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1467                 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1468
1469 #if NET_2_0
1470                 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1471 #endif
1472
1473                 static object TRUE = new object ();
1474                 static object FALSE = new object ();
1475
1476                 private AttributeTester ()
1477                 {
1478                 }
1479
1480                 public enum Result {
1481                         Ok,
1482                         RefOutArrayError,
1483                         ArrayArrayError
1484                 }
1485
1486                 /// <summary>
1487                 /// Returns true if parameters of two compared methods are CLS-Compliant.
1488                 /// It tests differing only in ref or out, or in array rank.
1489                 /// </summary>
1490                 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b) 
1491                 {
1492                         if (types_a == null || types_b == null)
1493                                 return Result.Ok;
1494
1495                         if (types_a.Length != types_b.Length)
1496                                 return Result.Ok;
1497
1498                         Result result = Result.Ok;
1499                         for (int i = 0; i < types_b.Length; ++i) {
1500                                 Type aType = types_a [i];
1501                                 Type bType = types_b [i];
1502
1503                                 if (aType.IsArray && bType.IsArray) {
1504                                         Type a_el_type = aType.GetElementType ();
1505                                         Type b_el_type = bType.GetElementType ();
1506                                         if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1507                                                 result = Result.RefOutArrayError;
1508                                                 continue;
1509                                         }
1510
1511                                         if (a_el_type.IsArray || b_el_type.IsArray) {
1512                                                 result = Result.ArrayArrayError;
1513                                                 continue;
1514                                         }
1515                                 }
1516
1517                                 Type aBaseType = aType;
1518                                 bool is_either_ref_or_out = false;
1519
1520                                 if (aType.IsByRef || aType.IsPointer) {
1521                                         aBaseType = aType.GetElementType ();
1522                                         is_either_ref_or_out = true;
1523                                 }
1524
1525                                 Type bBaseType = bType;
1526                                 if (bType.IsByRef || bType.IsPointer) 
1527                                 {
1528                                         bBaseType = bType.GetElementType ();
1529                                         is_either_ref_or_out = !is_either_ref_or_out;
1530                                 }
1531
1532                                 if (aBaseType != bBaseType)
1533                                         return Result.Ok;
1534
1535                                 if (is_either_ref_or_out)
1536                                         result = Result.RefOutArrayError;
1537                         }
1538                         return result;
1539                 }
1540
1541                 /// <summary>
1542                 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1543                 /// </summary>
1544                 public static bool IsClsCompliant (Type type) 
1545                 {
1546                         if (type == null)
1547                                 return true;
1548
1549                         object type_compliance = analyzed_types[type];
1550                         if (type_compliance != null)
1551                                 return type_compliance == TRUE;
1552
1553                         if (type.IsPointer) {
1554                                 analyzed_types.Add (type, null);
1555                                 return false;
1556                         }
1557
1558                         bool result;
1559                         if (type.IsArray || type.IsByRef)       {
1560                                 result = IsClsCompliant (TypeManager.GetElementType (type));
1561                         } else {
1562                                 result = AnalyzeTypeCompliance (type);
1563                         }
1564                         analyzed_types.Add (type, result ? TRUE : FALSE);
1565                         return result;
1566                 }        
1567         
1568                 /// <summary>
1569                 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1570                 /// </summary>
1571                 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1572                 {
1573                         FieldBase fb = TypeManager.GetField (fi);
1574                         if (fb != null) {
1575                                 return fb as IFixedBuffer;
1576                         }
1577
1578 #if NET_2_0
1579                         object o = fixed_buffer_cache [fi];
1580                         if (o == null) {
1581                                 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1582                                         fixed_buffer_cache.Add (fi, FALSE);
1583                                         return null;
1584                                 }
1585                                 
1586                                 IFixedBuffer iff = new FixedFieldExternal (fi);
1587                                 fixed_buffer_cache.Add (fi, iff);
1588                                 return iff;
1589                         }
1590
1591                         if (o == FALSE)
1592                                 return null;
1593
1594                         return (IFixedBuffer)o;
1595 #else
1596                         return null;
1597 #endif
1598                 }
1599
1600                 public static void VerifyModulesClsCompliance ()
1601                 {
1602                         Module[] modules = RootNamespace.Global.Modules;
1603                         if (modules == null)
1604                                 return;
1605
1606                         // The first module is generated assembly
1607                         for (int i = 1; i < modules.Length; ++i) {
1608                                 Module module = modules [i];
1609                                 if (!IsClsCompliant (module)) {
1610                                         Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
1611                                                       "to match the assembly", module.Name);
1612                                         return;
1613                                 }
1614                         }
1615                 }
1616
1617                 public static Type GetImportedIgnoreCaseClsType (string name)
1618                 {
1619                         foreach (Assembly a in RootNamespace.Global.Assemblies) {
1620                                 Type t = a.GetType (name, false, true);
1621                                 if (t == null)
1622                                         continue;
1623
1624                                 if (IsClsCompliant (t))
1625                                         return t;
1626                         }
1627                         return null;
1628                 }
1629
1630                 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider) 
1631                 {
1632                         object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1633                         if (CompliantAttribute.Length == 0)
1634                                 return false;
1635
1636                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1637                 }
1638
1639                 static bool AnalyzeTypeCompliance (Type type)
1640                 {
1641                         DeclSpace ds = TypeManager.LookupDeclSpace (type);
1642                         if (ds != null) {
1643                                 return ds.IsClsComplianceRequired ();
1644                         }
1645
1646                         object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1647                         if (CompliantAttribute.Length == 0) 
1648                                 return IsClsCompliant (type.Assembly);
1649
1650                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1651                 }
1652
1653                 /// <summary>
1654                 /// Returns instance of ObsoleteAttribute when type is obsolete
1655                 /// </summary>
1656                 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1657                 {
1658                         object type_obsolete = analyzed_types_obsolete [type];
1659                         if (type_obsolete == FALSE)
1660                                 return null;
1661
1662                         if (type_obsolete != null)
1663                                 return (ObsoleteAttribute)type_obsolete;
1664
1665                         ObsoleteAttribute result = null;
1666                         if (type.IsByRef || type.IsArray || type.IsPointer) {
1667                                 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1668                         } else {
1669                                 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1670
1671                                 // Type is external, we can get attribute directly
1672                                 if (type_ds == null) {
1673                                         object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1674                                         if (attribute.Length == 1)
1675                                                 result = (ObsoleteAttribute)attribute [0];
1676                                 } else {
1677                                         // Is null during corlib bootstrap
1678                                         if (TypeManager.obsolete_attribute_type != null)
1679                                                 result = type_ds.GetObsoleteAttribute ();
1680                                 }
1681                         }
1682
1683                         // Cannot use .Add because of corlib bootstrap
1684                         analyzed_types_obsolete [type] = result == null ? FALSE : result;
1685                         return result;
1686                 }
1687
1688                 /// <summary>
1689                 /// Returns instance of ObsoleteAttribute when method is obsolete
1690                 /// </summary>
1691                 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1692                 {
1693                         IMethodData mc = TypeManager.GetMethod (mb);
1694                         if (mc != null) 
1695                                 return mc.GetObsoleteAttribute ();
1696
1697                         // compiler generated methods are not registered by AddMethod
1698                         if (mb.DeclaringType is TypeBuilder)
1699                                 return null;
1700
1701                         if (mb.IsSpecialName) {
1702                                 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1703                                 if (pi != null) {
1704                                         // FIXME: This is buggy as properties from this assembly are included as well
1705                                         return null;
1706                                         //return GetMemberObsoleteAttribute (pi);
1707                                 }
1708                         }
1709
1710                         return GetMemberObsoleteAttribute (mb);
1711                 }
1712
1713                 /// <summary>
1714                 /// Returns instance of ObsoleteAttribute when member is obsolete
1715                 /// </summary>
1716                 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1717                 {
1718                         object type_obsolete = analyzed_member_obsolete [mi];
1719                         if (type_obsolete == FALSE)
1720                                 return null;
1721
1722                         if (type_obsolete != null)
1723                                 return (ObsoleteAttribute)type_obsolete;
1724
1725                         ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false)
1726                                 as ObsoleteAttribute;
1727                         analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1728                         return oa;
1729                 }
1730
1731                 /// <summary>
1732                 /// Common method for Obsolete error/warning reporting.
1733                 /// </summary>
1734                 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1735                 {
1736                         if (oa.IsError) {
1737                                 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1738                                 return;
1739                         }
1740
1741                         if (oa.Message == null) {
1742                                 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1743                                 return;
1744                         }
1745                         Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1746                 }
1747
1748                 public static bool IsConditionalMethodExcluded (MethodBase mb)
1749                 {
1750                         object excluded = analyzed_method_excluded [mb];
1751                         if (excluded != null)
1752                                 return excluded == TRUE ? true : false;
1753                         
1754                         ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true)
1755                                 as ConditionalAttribute[];
1756                         if (attrs.Length == 0) {
1757                                 analyzed_method_excluded.Add (mb, FALSE);
1758                                 return false;
1759                         }
1760
1761                         foreach (ConditionalAttribute a in attrs) {
1762                                 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1763                                         analyzed_method_excluded.Add (mb, FALSE);
1764                                         return false;
1765                                 }
1766                         }
1767                         analyzed_method_excluded.Add (mb, TRUE);
1768                         return true;
1769                 }
1770
1771                 /// <summary>
1772                 /// Analyzes class whether it has attribute which has ConditionalAttribute
1773                 /// and its condition is not defined.
1774                 /// </summary>
1775                 public static bool IsAttributeExcluded (Type type)
1776                 {
1777                         if (!type.IsClass)
1778                                 return false;
1779
1780                         Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1781
1782                         // TODO: add caching
1783                         // TODO: merge all Type bases attribute caching to one cache to save memory
1784                         if (class_decl == null) {
1785                                 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1786                                 foreach (ConditionalAttribute ca in attributes) {
1787                                         if (RootContext.AllDefines.Contains (ca.ConditionString))
1788                                                 return false;
1789                                 }
1790                                 return attributes.Length > 0;
1791                         }
1792
1793                         return class_decl.IsExcluded ();
1794                 }
1795
1796                 public static Type GetCoClassAttribute (Type type)
1797                 {
1798                         TypeContainer tc = TypeManager.LookupInterface (type);
1799                         if (tc == null) {
1800                                 object[] o = type.GetCustomAttributes (TypeManager.coclass_attr_type, false);
1801                                 if (o.Length < 1)
1802                                         return null;
1803                                 return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
1804                         }
1805
1806                         if (tc.OptAttributes == null)
1807                                 return null;
1808
1809                         Attribute a = tc.OptAttributes.Search (TypeManager.coclass_attr_type);
1810                         if (a == null)
1811                                 return null;
1812
1813                         return a.GetCoClassAttributeValue ();
1814                 }
1815         }
1816 }