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