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