2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
13 using System.Diagnostics;
14 using System.Collections;
15 using System.Collections.Specialized;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Runtime.InteropServices;
19 using System.Runtime.CompilerServices;
22 namespace Mono.CSharp {
25 /// Base class for objects that can have Attributes applied to them.
27 public abstract class Attributable {
29 /// Attributes for this type
31 Attributes attributes;
33 public Attributable(Attributes attrs)
36 if (attributes != null)
37 attributes.CheckTargets (ValidAttributeTargets);
40 public Attributes OptAttributes
47 if (attributes != null)
48 attributes.CheckTargets (ValidAttributeTargets);
53 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
55 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
58 /// Returns combination of enabled AttributeTargets
60 public abstract AttributeTargets AttributeTargets { get; }
62 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
65 /// Gets list of valid attribute targets for explicit target declaration.
66 /// The first array item is default target. Don't break this rule.
68 protected abstract string[] ValidAttributeTargets { get; }
71 public class Attribute {
73 public readonly string Name;
74 public readonly ArrayList Arguments;
76 public readonly Location Location;
80 // Is non-null if type is AttributeUsageAttribute
81 AttributeUsageAttribute usage_attribute;
83 public AttributeUsageAttribute UsageAttribute {
85 return usage_attribute;
89 MethodImplOptions ImplOptions;
90 UnmanagedType UnmanagedType;
91 CustomAttributeBuilder cb;
93 // non-null if named args present after Resolve () is called
94 PropertyInfo [] prop_info_arr;
95 FieldInfo [] field_info_arr;
96 object [] field_values_arr;
97 object [] prop_values_arr;
100 static PtrHashtable usage_attr_cache = new PtrHashtable ();
102 public Attribute (string target, string name, ArrayList args, Location loc)
110 void Error_InvalidNamedArgument (string name)
112 Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
113 "argument. Named attribute arguments must be fields which are not " +
114 "readonly, static or const, or properties with a set accessor which "+
118 static void Error_AttributeArgumentNotValid (Location loc)
120 Report.Error (182, loc,
121 "An attribute argument must be a constant expression, typeof " +
122 "expression or array creation expression");
125 static void Error_TypeParameterInAttribute (Location loc)
128 -202, loc, "Can not use a type parameter in an attribute");
131 void Error_AttributeConstructorMismatch ()
133 Report.Error (-6, Location,
134 "Could not find a constructor for this argument list.");
138 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
140 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
142 TypeExpr t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
143 // FIXME: Shouldn't do this for quoted attributes: [@A]
144 TypeExpr t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
146 String err0616 = null;
147 if (t1 != null && ! t1.IsAttribute) {
149 err0616 = "'" + Name + "': is not an attribute class";
151 if (t2 != null && ! t2.IsAttribute) {
153 err0616 = (err0616 != null)
154 ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
155 : "'" + Name + "Attribute': is not an attribute class";
158 if (t1 != null && t2 != null) {
159 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
160 + " use either '@" + Name + "' or '" + Name + "Attribute'");
164 return t1.ResolveType (ec);
166 return t2.ResolveType (ec);
167 if (err0616 != null) {
168 Report.Error (616, Location, err0616);
173 Report.Error (246, Location,
174 "Could not find attribute '" + Name
175 + "' (are you missing a using directive or an assembly reference ?)");
179 public Type ResolveType (EmitContext ec, bool complain)
182 Type = CheckAttributeType (ec, complain);
187 /// Validates the guid string
189 bool ValidateGuid (string guid)
195 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
200 string GetFullMemberName (string member)
202 return Type.FullName + '.' + member;
206 // Given an expression, if the expression is a valid attribute-argument-expression
207 // returns an object that can be used to encode it, or null on failure.
209 public static bool GetAttributeArgumentExpression (Expression e, Location loc, out object result)
212 result = ((Constant) e).GetValue ();
214 } else if (e is TypeOf) {
215 result = ((TypeOf) e).TypeArg;
217 } else if (e is ArrayCreation){
218 result = ((ArrayCreation) e).EncodeAsAttribute ();
221 } else if (e is EmptyCast) {
223 if (((EmptyCast) e).Child is Constant) {
224 result = ((Constant) ((EmptyCast)e).Child).GetValue();
230 Error_AttributeArgumentNotValid (loc);
234 public CustomAttributeBuilder Resolve (EmitContext ec)
239 Type = CheckAttributeType (ec, true);
240 if (oldType == null && Type == null)
242 if (oldType != null && oldType != Type) {
243 Report.Error (-6, Location,
244 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
245 Name, oldType, Type);
249 bool MethodImplAttr = false;
250 bool MarshalAsAttr = false;
251 bool GuidAttr = false;
252 bool usage_attr = false;
254 bool DoCompares = true;
257 // If we are a certain special attribute, we
258 // set the information accordingly
261 if (Type == TypeManager.attribute_usage_type)
263 else if (Type == TypeManager.methodimpl_attr_type)
264 MethodImplAttr = true;
265 else if (Type == TypeManager.marshal_as_attr_type)
266 MarshalAsAttr = true;
267 else if (Type == TypeManager.guid_attr_type)
272 // Now we extract the positional and named arguments
274 ArrayList pos_args = new ArrayList ();
275 ArrayList named_args = new ArrayList ();
276 int pos_arg_count = 0;
278 if (Arguments != null) {
279 pos_args = (ArrayList) Arguments [0];
280 if (pos_args != null)
281 pos_arg_count = pos_args.Count;
282 if (Arguments.Count > 1)
283 named_args = (ArrayList) Arguments [1];
286 pos_values = new object [pos_arg_count];
289 // First process positional arguments
293 for (i = 0; i < pos_arg_count; i++) {
294 Argument a = (Argument) pos_args [i];
297 if (!a.Resolve (ec, Location))
303 if (!GetAttributeArgumentExpression (e, Location, out val))
306 pos_values [i] = val;
309 usage_attribute = new AttributeUsageAttribute ((AttributeTargets) pos_values [0]);
310 else if (MethodImplAttr)
311 this.ImplOptions = (MethodImplOptions) pos_values [0];
314 // we will later check the validity of the type
316 if (pos_values [0] is string){
317 if (!ValidateGuid ((string) pos_values [0]))
321 } else if (MarshalAsAttr)
323 (System.Runtime.InteropServices.UnmanagedType) pos_values [0];
328 // Now process named arguments
331 ArrayList field_infos = null;
332 ArrayList prop_infos = null;
333 ArrayList field_values = null;
334 ArrayList prop_values = null;
336 if (named_args.Count > 0) {
337 field_infos = new ArrayList ();
338 prop_infos = new ArrayList ();
339 field_values = new ArrayList ();
340 prop_values = new ArrayList ();
343 Hashtable seen_names = new Hashtable();
345 for (i = 0; i < named_args.Count; i++) {
346 DictionaryEntry de = (DictionaryEntry) named_args [i];
347 string member_name = (string) de.Key;
348 Argument a = (Argument) de.Value;
351 if (seen_names.Contains(member_name)) {
352 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
355 seen_names.Add(member_name, 1);
357 if (!a.Resolve (ec, Location))
360 Expression member = Expression.MemberLookup (
361 ec, Type, member_name,
362 MemberTypes.Field | MemberTypes.Property,
363 BindingFlags.Public | BindingFlags.Instance,
366 if (member == null) {
367 member = Expression.MemberLookup (ec, Type, member_name,
368 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
371 if (member != null) {
372 Report.Error_T (122, Location, GetFullMemberName (member_name));
377 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
378 Error_InvalidNamedArgument (member_name);
383 if (e is TypeParameterExpr){
384 Error_TypeParameterInAttribute (Location);
388 if (member is PropertyExpr) {
389 PropertyExpr pe = (PropertyExpr) member;
390 PropertyInfo pi = pe.PropertyInfo;
393 Error_InvalidNamedArgument (member_name);
397 Constant c = e as Constant;
399 if (c.Type != pi.PropertyType) {
400 c = Const.ChangeType (Location, c, pi.PropertyType);
405 object o = c.GetValue ();
408 if (usage_attribute != null) {
409 if (member_name == "AllowMultiple")
410 usage_attribute.AllowMultiple = (bool) o;
411 if (member_name == "Inherited")
412 usage_attribute.Inherited = (bool) o;
415 } else if (e is TypeOf) {
416 prop_values.Add (((TypeOf) e).TypeArg);
417 } else if (e is ArrayCreation) {
418 prop_values.Add (((ArrayCreation) e).EncodeAsAttribute());
420 Error_AttributeArgumentNotValid (Location);
426 } else if (member is FieldExpr) {
427 FieldExpr fe = (FieldExpr) member;
428 FieldInfo fi = fe.FieldInfo;
431 Error_InvalidNamedArgument (member_name);
436 // Handle charset here, and set the TypeAttributes
438 Constant c = e as Constant;
440 if (c.Type != fi.FieldType){
441 c = Const.ChangeType (Location, c, fi.FieldType);
446 object value = c.GetValue ();
447 field_values.Add (value);
448 } else if (e is TypeOf) {
449 field_values.Add (((TypeOf) e).TypeArg);
451 Error_AttributeArgumentNotValid (Location);
455 field_infos.Add (fi);
459 Expression mg = Expression.MemberLookup (
460 ec, Type, ".ctor", MemberTypes.Constructor,
461 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
465 Error_AttributeConstructorMismatch ();
469 MethodBase constructor = Invocation.OverloadResolve (
470 ec, (MethodGroupExpr) mg, pos_args, false, Location);
472 if (constructor == null) {
473 Error_AttributeConstructorMismatch ();
478 // Now we perform some checks on the positional args as they
479 // cannot be null for a constructor which expects a parameter
483 ParameterData pd = Invocation.GetParameterData (constructor);
485 int group_in_params_array = Int32.MaxValue;
487 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
488 group_in_params_array = pc-1;
490 for (int j = 0; j < pos_arg_count; ++j) {
491 Argument a = (Argument) pos_args [j];
493 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
494 Error_AttributeArgumentNotValid (Location);
498 if (j < group_in_params_array)
501 if (j == group_in_params_array){
502 object v = pos_values [j];
503 int count = pos_arg_count - j;
505 object [] array = new object [count];
506 pos_values [j] = array;
509 object [] array = (object []) pos_values [group_in_params_array];
511 array [j - group_in_params_array] = pos_values [j];
516 // Adjust the size of the pos_values if it had params
518 if (group_in_params_array != Int32.MaxValue){
519 int argc = group_in_params_array+1;
520 object [] new_pos_values = new object [argc];
522 for (int p = 0; p < argc; p++)
523 new_pos_values [p] = pos_values [p];
524 pos_values = new_pos_values;
528 if (named_args.Count > 0) {
529 prop_info_arr = new PropertyInfo [prop_infos.Count];
530 field_info_arr = new FieldInfo [field_infos.Count];
531 field_values_arr = new object [field_values.Count];
532 prop_values_arr = new object [prop_values.Count];
534 field_infos.CopyTo (field_info_arr, 0);
535 field_values.CopyTo (field_values_arr, 0);
537 prop_values.CopyTo (prop_values_arr, 0);
538 prop_infos.CopyTo (prop_info_arr, 0);
540 cb = new CustomAttributeBuilder (
541 (ConstructorInfo) constructor, pos_values,
542 prop_info_arr, prop_values_arr,
543 field_info_arr, field_values_arr);
546 cb = new CustomAttributeBuilder (
547 (ConstructorInfo) constructor, pos_values);
548 } catch (NullReferenceException) {
550 // Don't know what to do here
553 -101, Location, "NullReferenceException while trying to create attribute." +
554 "Something's wrong!");
555 } catch (Exception e) {
558 // using System.ComponentModel;
559 // [DefaultValue (CollectionChangeAction.Add)]
560 // class X { static void Main () {} }
563 -23, Location, "The compiler can not encode this attribute in .NET due to a bug in the .NET runtime. Try the Mono runtime. The exception was: " + e.Message);
570 /// Get a string containing a list of valid targets for the attribute 'attr'
572 static string GetValidTargets (Attribute attr)
574 StringBuilder sb = new StringBuilder ();
575 AttributeTargets targets = attr.GetAttributeUsage ().ValidOn;
577 if ((targets & AttributeTargets.Assembly) != 0)
578 sb.Append ("'assembly' ");
580 if ((targets & AttributeTargets.Class) != 0)
581 sb.Append ("'class' ");
583 if ((targets & AttributeTargets.Constructor) != 0)
584 sb.Append ("'constructor' ");
586 if ((targets & AttributeTargets.Delegate) != 0)
587 sb.Append ("'delegate' ");
589 if ((targets & AttributeTargets.Enum) != 0)
590 sb.Append ("'enum' ");
592 if ((targets & AttributeTargets.Event) != 0)
593 sb.Append ("'event' ");
595 if ((targets & AttributeTargets.Field) != 0)
596 sb.Append ("'field' ");
598 if ((targets & AttributeTargets.Interface) != 0)
599 sb.Append ("'interface' ");
601 if ((targets & AttributeTargets.Method) != 0)
602 sb.Append ("'method' ");
604 if ((targets & AttributeTargets.Module) != 0)
605 sb.Append ("'module' ");
607 if ((targets & AttributeTargets.Parameter) != 0)
608 sb.Append ("'parameter' ");
610 if ((targets & AttributeTargets.Property) != 0)
611 sb.Append ("'property' ");
613 if ((targets & AttributeTargets.ReturnValue) != 0)
614 sb.Append ("'return' ");
616 if ((targets & AttributeTargets.Struct) != 0)
617 sb.Append ("'struct' ");
619 return sb.ToString ();
623 public static void Error_AttributeNotValidForElement (Attribute a, Location loc)
626 592, loc, "Attribute '" + a.Name +
627 "' is not valid on this declaration type. " +
628 "It is valid on " + GetValidTargets (a) + "declarations only.");
633 /// Returns AttributeUsage attribute for this type
635 public AttributeUsageAttribute GetAttributeUsage ()
637 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
641 Class attr_class = TypeManager.LookupClass (Type);
643 if (attr_class == null) {
644 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
645 ua = (AttributeUsageAttribute)usage_attr [0];
646 usage_attr_cache.Add (Type, ua);
650 return attr_class.AttributeUsage;
655 // This pulls the condition name out of a Conditional attribute
657 public string Conditional_GetConditionName ()
660 // So we have a Conditional, pull the data out.
662 if (Arguments == null || Arguments [0] == null){
663 Error_AttributeConstructorMismatch ();
667 ArrayList pos_args = (ArrayList) Arguments [0];
668 if (pos_args.Count != 1){
669 Error_AttributeConstructorMismatch ();
673 Argument arg = (Argument) pos_args [0];
674 if (!(arg.Expr is StringConstant)){
675 Error_AttributeConstructorMismatch ();
679 return ((StringConstant) arg.Expr).Value;
682 public string IndexerName_GetIndexerName (EmitContext ec)
684 if (Arguments == null || Arguments [0] == null){
685 Error_AttributeConstructorMismatch ();
688 ArrayList pos_args = (ArrayList) Arguments [0];
689 if (pos_args.Count != 1) {
690 Error_AttributeConstructorMismatch ();
694 Argument arg = (Argument) pos_args [0];
695 if (!arg.Resolve (ec, Location))
698 StringConstant sc = arg.Expr as StringConstant;
700 Error_AttributeConstructorMismatch ();
708 /// Creates the instance of ObsoleteAttribute from this attribute instance
710 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
712 if (pos_values == null) {
713 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
715 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
716 // But because a lot of attribute class code must be rewritten will be better to wait...
720 // Some error occurred
721 if (pos_values == null)
724 if (pos_values.Length == 0)
725 return new ObsoleteAttribute ();
727 if (pos_values.Length == 1)
728 return new ObsoleteAttribute ((string)pos_values [0]);
730 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
734 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
735 /// before ApplyAttribute. We need to resolve the arguments.
736 /// This situation occurs when class deps is differs from Emit order.
738 public bool GetClsCompliantAttributeValue (DeclSpace ds)
740 if (pos_values == null) {
741 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
743 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
744 // But because a lot of attribute class code must be rewritten will be better to wait...
748 // Some error occurred
749 if (pos_values [0] == null)
752 return (bool)pos_values [0];
755 public object GetPositionalValue (int i)
757 return (pos_values == null) ? null : pos_values[i];
760 object GetFieldValue (string name)
763 if (field_info_arr == null)
766 foreach (FieldInfo fi in field_info_arr) {
768 return field_values_arr [i];
774 public UnmanagedMarshal GetMarshal ()
776 object o = GetFieldValue ("ArraySubType");
777 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
779 switch (UnmanagedType) {
780 case UnmanagedType.CustomMarshaler:
781 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
782 BindingFlags.Static | BindingFlags.Public);
783 if (define_custom == null)
786 object [] args = new object [4];
787 args [0] = GetFieldValue ("MarshalTypeRef");
788 args [1] = GetFieldValue ("MarshalCookie");
789 args [2] = GetFieldValue ("MarshalType");
790 args [3] = Guid.Empty;
791 return (UnmanagedMarshal) define_custom.Invoke (null, args);
793 case UnmanagedType.LPArray:
794 return UnmanagedMarshal.DefineLPArray (array_sub_type);
796 case UnmanagedType.SafeArray:
797 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
799 case UnmanagedType.ByValArray:
800 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
802 case UnmanagedType.ByValTStr:
803 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
806 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
810 public bool IsInternalCall
812 get { return ImplOptions == MethodImplOptions.InternalCall; }
816 /// Emit attribute for Attributable symbol
818 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
820 CustomAttributeBuilder cb = Resolve (ec);
824 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
825 if ((usage_attr.ValidOn & ias.AttributeTargets) == 0) {
826 Error_AttributeNotValidForElement (this, Location);
830 ias.ApplyAttributeBuilder (this, cb);
832 if (!usage_attr.AllowMultiple && emitted_attr.Contains (Target)) {
833 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
836 emitted_attr [Type] = Target;
838 // Here we are testing attribute arguments for array usage (error 3016)
839 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
840 if (Arguments == null)
843 ArrayList pos_args = (ArrayList) Arguments [0];
844 if (pos_args != null) {
845 foreach (Argument arg in pos_args) {
846 // Type is undefined (was error 246)
847 if (arg.Type == null)
850 if (arg.Type.IsArray) {
851 Report.Error_T (3016, Location);
857 if (Arguments.Count < 2)
860 ArrayList named_args = (ArrayList) Arguments [1];
861 foreach (DictionaryEntry de in named_args) {
862 Argument arg = (Argument) de.Value;
864 // Type is undefined (was error 246)
865 if (arg.Type == null)
868 if (arg.Type.IsArray) {
869 Report.Error_T (3016, Location);
876 public object GetValue (EmitContext ec, Constant c, Type target)
878 if (Convert.ImplicitConversionExists (ec, c, target))
879 return c.GetValue ();
881 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
885 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
886 MethodAttributes flags, Type ret_type, Type [] param_types)
889 // We extract from the attribute the information we need
892 if (Arguments == null) {
893 Console.WriteLine ("Internal error : this is not supposed to happen !");
897 ResolveType (ec, true);
901 ArrayList named_args = new ArrayList ();
903 ArrayList pos_args = (ArrayList) Arguments [0];
904 if (Arguments.Count > 1)
905 named_args = (ArrayList) Arguments [1];
908 string dll_name = null;
910 Argument tmp = (Argument) pos_args [0];
912 if (!tmp.Resolve (ec, Location))
915 if (tmp.Expr is Constant)
916 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
918 Error_AttributeArgumentNotValid (Location);
922 // Now we process the named arguments
923 CallingConvention cc = CallingConvention.Winapi;
924 CharSet charset = CharSet.Ansi;
925 bool preserve_sig = true;
927 bool exact_spelling = false;
929 bool set_last_err = false;
930 string entry_point = null;
932 for (int i = 0; i < named_args.Count; i++) {
934 DictionaryEntry de = (DictionaryEntry) named_args [i];
936 string member_name = (string) de.Key;
937 Argument a = (Argument) de.Value;
939 if (!a.Resolve (ec, Location))
942 Expression member = Expression.MemberLookup (
943 ec, Type, member_name,
944 MemberTypes.Field | MemberTypes.Property,
945 BindingFlags.Public | BindingFlags.Instance,
948 if (member == null || !(member is FieldExpr)) {
949 Error_InvalidNamedArgument (member_name);
953 if (member is FieldExpr) {
954 FieldExpr fe = (FieldExpr) member;
955 FieldInfo fi = fe.FieldInfo;
958 Error_InvalidNamedArgument (member_name);
962 if (a.Expr is Constant) {
963 Constant c = (Constant) a.Expr;
966 if (member_name == "CallingConvention"){
967 object val = GetValue (ec, c, typeof (CallingConvention));
970 cc = (CallingConvention) val;
971 } else if (member_name == "CharSet"){
972 charset = (CharSet) c.GetValue ();
973 } else if (member_name == "EntryPoint")
974 entry_point = (string) c.GetValue ();
975 else if (member_name == "SetLastError")
976 set_last_err = (bool) c.GetValue ();
978 else if (member_name == "ExactSpelling")
979 exact_spelling = (bool) c.GetValue ();
981 else if (member_name == "PreserveSig")
982 preserve_sig = (bool) c.GetValue ();
983 } catch (InvalidCastException){
984 Error_InvalidNamedArgument (member_name);
985 Error_AttributeArgumentNotValid (Location);
988 Error_AttributeArgumentNotValid (Location);
995 if (entry_point == null)
998 charset = (CharSet)((int)charset | 0x40);
1000 MethodBuilder mb = builder.DefinePInvokeMethod (
1001 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1002 CallingConventions.Standard,
1009 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1014 private Expression GetValue ()
1016 if ((Arguments == null) || (Arguments.Count < 1))
1018 ArrayList al = (ArrayList) Arguments [0];
1019 if ((al == null) || (al.Count < 1))
1021 Argument arg = (Argument) al [0];
1022 if ((arg == null) || (arg.Expr == null))
1027 public string GetString ()
1029 Expression e = GetValue ();
1030 if (e is StringLiteral)
1031 return (e as StringLiteral).Value;
1035 public bool GetBoolean ()
1037 Expression e = GetValue ();
1038 if (e is BoolLiteral)
1039 return (e as BoolLiteral).Value;
1046 /// For global attributes (assembly, module) we need special handling.
1047 /// Attributes can be located in the several files
1049 public class GlobalAttribute: Attribute
1051 public readonly NamespaceEntry ns;
1053 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1054 base (target, name, args, loc)
1056 ns = container.NamespaceEntry;
1059 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1061 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1062 if (old == null || old.NS == null || old.NS == Namespace.Root)
1063 ec.DeclSpace.NamespaceEntry = ns;
1064 return base.CheckAttributeType (ec, complain);
1068 public class Attributes {
1069 public ArrayList Attrs;
1071 public Attributes (Attribute a)
1073 Attrs = new ArrayList ();
1077 public Attributes (ArrayList attrs)
1082 public void AddAttributes (ArrayList attrs)
1084 Attrs.AddRange (attrs);
1088 /// Checks whether attribute target is valid for the current element
1090 public void CheckTargets (string[] possible_targets)
1092 foreach (Attribute a in Attrs) {
1093 if (a.Target == null) {
1094 a.Target = possible_targets [0];
1098 if (((IList) possible_targets).Contains (a.Target))
1101 StringBuilder sb = new StringBuilder ();
1102 foreach (string s in possible_targets) {
1106 sb.Remove (sb.Length - 2, 2);
1107 Report.Error_T (657, a.Location, a.Target, sb.ToString ());
1111 private Attribute Search (Type t, EmitContext ec, bool complain)
1113 foreach (Attribute a in Attrs) {
1114 if (a.ResolveType (ec, false) == t)
1120 public Attribute Search (Type t, EmitContext ec)
1122 return Search (t, ec, true);
1125 public void Emit (EmitContext ec, Attributable ias)
1127 ListDictionary ld = new ListDictionary ();
1129 foreach (Attribute a in Attrs)
1130 a.Emit (ec, ias, ld);
1133 public bool Contains (Type t, EmitContext ec)
1135 return Search (t, ec) != null;
1138 public Attribute GetClsCompliantAttribute (EmitContext ec)
1140 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1144 /// Pulls the IndexerName attribute from an Indexer if it exists.
1146 public string ScanForIndexerName (EmitContext ec)
1148 Attribute a = Search (TypeManager.indexer_name_type, ec);
1152 // Remove the attribute from the list
1153 //TODO: It is very close to hack and it can crash here
1156 return a.IndexerName_GetIndexerName (ec);
1162 /// Helper class for attribute verification routine.
1164 sealed class AttributeTester
1166 static PtrHashtable analyzed_types = new PtrHashtable ();
1167 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1169 private AttributeTester ()
1174 /// Returns true if parameters of two compared methods are CLS-Compliant.
1175 /// It tests differing only in ref or out, or in array rank.
1177 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1179 if (types_a == null || types_b == null)
1182 if (types_a.Length != types_b.Length)
1185 for (int i = 0; i < types_b.Length; ++i) {
1186 Type aType = types_a [i];
1187 Type bType = types_b [i];
1189 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1193 Type aBaseType = aType;
1194 bool is_either_ref_or_out = false;
1196 if (aType.IsByRef || aType.IsPointer) {
1197 aBaseType = aType.GetElementType ();
1198 is_either_ref_or_out = true;
1201 Type bBaseType = bType;
1202 if (bType.IsByRef || bType.IsPointer)
1204 bBaseType = bType.GetElementType ();
1205 is_either_ref_or_out = !is_either_ref_or_out;
1208 if (aBaseType != bBaseType)
1211 if (is_either_ref_or_out)
1218 /// Goes through all parameters and test if they are CLS-Compliant.
1220 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1222 if (fixedParameters == null)
1225 foreach (Parameter arg in fixedParameters) {
1226 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1227 Report.Error_T (3001, loc, arg.GetSignatureForError ());
1236 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1238 public static bool IsClsCompliant (Type type)
1243 object type_compliance = analyzed_types[type];
1244 if (type_compliance != null)
1245 return type_compliance == TRUE;
1247 if (type.IsPointer) {
1248 analyzed_types.Add (type, null);
1253 if (type.IsArray || type.IsByRef) {
1254 result = IsClsCompliant (TypeManager.GetElementType (type));
1256 result = AnalyzeTypeCompliance (type);
1258 analyzed_types.Add (type, result ? TRUE : FALSE);
1262 static object TRUE = new object ();
1263 static object FALSE = new object ();
1266 /// Non-hierarchical CLS Compliance analyzer
1268 public static bool IsComplianceRequired (MemberInfo mi, DeclSpace ds)
1270 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
1272 // Type is external, we can get attribute directly
1273 if (temp_ds == null) {
1274 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1275 return (cls_attribute.Length == 1 && ((CLSCompliantAttribute)cls_attribute[0]).IsCompliant);
1279 // Interface doesn't store full name
1280 if (temp_ds is Interface)
1283 tmp_name = String.Concat (temp_ds.Name, ".", mi.Name);
1285 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
1286 return mc.IsClsCompliaceRequired (ds);
1289 public static void VerifyModulesClsCompliance ()
1291 Module[] modules = TypeManager.Modules;
1292 if (modules == null)
1295 // The first module is generated assembly
1296 for (int i = 1; i < modules.Length; ++i) {
1297 Module module = modules [i];
1298 if (!IsClsCompliant (module)) {
1299 Report.Error_T (3013, module.Name);
1305 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1307 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1308 if (CompliantAttribute.Length == 0)
1311 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1314 static bool AnalyzeTypeCompliance (Type type)
1316 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1318 return ds.IsClsCompliaceRequired (ds.Parent);
1321 if (type.IsGenericParameter)
1324 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1325 if (CompliantAttribute.Length == 0)
1326 return IsClsCompliant (type.Assembly);
1328 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1332 /// Returns instance of ObsoleteAttribute when method is obsolete
1334 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1336 IMethodData mc = TypeManager.GetMethod (mb);
1338 return mc.GetObsoleteAttribute ();
1340 // TODO: remove after Constructor will be ready for IMethodData
1341 if (mb.DeclaringType is TypeBuilder)
1344 return GetMemberObsoleteAttribute (mb);
1348 /// Returns instance of ObsoleteAttribute when member is obsolete
1350 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1352 object type_obsolete = analyzed_member_obsolete [mi];
1353 if (type_obsolete == FALSE)
1356 if (type_obsolete != null)
1357 return (ObsoleteAttribute)type_obsolete;
1359 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1360 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1365 /// Common method for Obsolete error/warning reporting.
1367 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1370 Report.Error_T (619, loc, member, oa.Message);
1374 if (oa.Message == null) {
1375 Report.Warning_T (612, loc, member);
1378 Report.Warning_T (618, loc, member, oa.Message);