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