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