2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
14 using System.Diagnostics;
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.InteropServices;
20 using System.Runtime.CompilerServices;
23 namespace Mono.CSharp {
26 /// Base class for objects that can have Attributes applied to them.
28 public abstract class Attributable {
30 /// Attributes for this type
32 Attributes attributes;
34 public Attributable(Attributes attrs)
37 if (attributes != null)
38 attributes.CheckTargets (ValidAttributeTargets);
41 public Attributes OptAttributes
48 if (attributes != null)
49 attributes.CheckTargets (ValidAttributeTargets);
54 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
56 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
59 /// Returns combination of enabled AttributeTargets
61 public abstract AttributeTargets AttributeTargets { get; }
63 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
66 /// Gets list of valid attribute targets for explicit target declaration.
67 /// The first array item is default target. Don't break this rule.
69 protected abstract string[] ValidAttributeTargets { get; }
72 public class Attribute {
74 public readonly string Name;
75 public readonly ArrayList Arguments;
77 public readonly Location Location;
81 // Is non-null if type is AttributeUsageAttribute
82 AttributeUsageAttribute usage_attribute;
84 public AttributeUsageAttribute UsageAttribute {
86 return usage_attribute;
90 MethodImplOptions ImplOptions;
91 UnmanagedType UnmanagedType;
92 CustomAttributeBuilder cb;
94 // non-null if named args present after Resolve () is called
95 PropertyInfo [] prop_info_arr;
96 FieldInfo [] field_info_arr;
97 object [] field_values_arr;
98 object [] prop_values_arr;
101 static PtrHashtable usage_attr_cache = new PtrHashtable ();
103 public Attribute (string target, string name, ArrayList args, Location loc)
111 void Error_InvalidNamedArgument (string name)
113 Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
114 "argument. Named attribute arguments must be fields which are not " +
115 "readonly, static or const, or properties with a set accessor which "+
119 static void Error_AttributeArgumentNotValid (Location loc)
121 Report.Error (182, loc,
122 "An attribute argument must be a constant expression, typeof " +
123 "expression or array creation expression");
126 static void Error_TypeParameterInAttribute (Location loc)
129 -202, loc, "Can not use a type parameter in an attribute");
132 void Error_AttributeConstructorMismatch ()
134 Report.Error (-6, Location,
135 "Could not find a constructor for this argument list.");
139 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
141 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
143 TypeExpr t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
144 // FIXME: Shouldn't do this for quoted attributes: [@A]
145 TypeExpr t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
147 String err0616 = null;
148 if (t1 != null && ! t1.IsAttribute) {
150 err0616 = "'" + Name + "': is not an attribute class";
152 if (t2 != null && ! t2.IsAttribute) {
154 err0616 = (err0616 != null)
155 ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
156 : "'" + Name + "Attribute': is not an attribute class";
159 if (t1 != null && t2 != null) {
160 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
161 + " use either '@" + Name + "' or '" + Name + "Attribute'");
165 return t1.ResolveType (ec);
167 return t2.ResolveType (ec);
168 if (err0616 != null) {
169 Report.Error (616, Location, err0616);
174 Report.Error (246, Location,
175 "Could not find attribute '" + Name
176 + "' (are you missing a using directive or an assembly reference ?)");
180 public Type ResolveType (EmitContext ec, bool complain)
183 Type = CheckAttributeType (ec, complain);
188 /// Validates the guid string
190 bool ValidateGuid (string guid)
196 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
201 string GetFullMemberName (string member)
203 return Type.FullName + '.' + member;
207 // Given an expression, if the expression is a valid attribute-argument-expression
208 // returns an object that can be used to encode it, or null on failure.
210 public static bool GetAttributeArgumentExpression (Expression e, Location loc, out object result)
213 result = ((Constant) e).GetValue ();
215 } else if (e is TypeOf) {
216 result = ((TypeOf) e).TypeArg;
218 } else if (e is ArrayCreation){
219 result = ((ArrayCreation) e).EncodeAsAttribute ();
222 } else if (e is EmptyCast) {
224 if (((EmptyCast) e).Child is Constant) {
225 result = ((Constant) ((EmptyCast)e).Child).GetValue();
231 Error_AttributeArgumentNotValid (loc);
235 public CustomAttributeBuilder Resolve (EmitContext ec)
240 Type = CheckAttributeType (ec, true);
241 if (oldType == null && Type == null)
243 if (oldType != null && oldType != Type) {
244 Report.Error (-6, Location,
245 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
246 Name, oldType, Type);
250 bool MethodImplAttr = false;
251 bool MarshalAsAttr = false;
252 bool GuidAttr = false;
253 bool usage_attr = false;
255 bool DoCompares = true;
258 // If we are a certain special attribute, we
259 // set the information accordingly
262 if (Type == TypeManager.attribute_usage_type)
264 else if (Type == TypeManager.methodimpl_attr_type)
265 MethodImplAttr = true;
266 else if (Type == TypeManager.marshal_as_attr_type)
267 MarshalAsAttr = true;
268 else if (Type == TypeManager.guid_attr_type)
273 // Now we extract the positional and named arguments
275 ArrayList pos_args = new ArrayList ();
276 ArrayList named_args = new ArrayList ();
277 int pos_arg_count = 0;
279 if (Arguments != null) {
280 pos_args = (ArrayList) Arguments [0];
281 if (pos_args != null)
282 pos_arg_count = pos_args.Count;
283 if (Arguments.Count > 1)
284 named_args = (ArrayList) Arguments [1];
287 pos_values = new object [pos_arg_count];
290 // First process positional arguments
294 for (i = 0; i < pos_arg_count; i++) {
295 Argument a = (Argument) pos_args [i];
298 if (!a.Resolve (ec, Location))
304 if (!GetAttributeArgumentExpression (e, Location, out val))
307 pos_values [i] = val;
310 usage_attribute = new AttributeUsageAttribute ((AttributeTargets) pos_values [0]);
311 else if (MethodImplAttr)
312 this.ImplOptions = (MethodImplOptions) pos_values [0];
315 // we will later check the validity of the type
317 if (pos_values [0] is string){
318 if (!ValidateGuid ((string) pos_values [0]))
322 } else if (MarshalAsAttr)
324 (System.Runtime.InteropServices.UnmanagedType) pos_values [0];
329 // Now process named arguments
332 ArrayList field_infos = null;
333 ArrayList prop_infos = null;
334 ArrayList field_values = null;
335 ArrayList prop_values = null;
337 if (named_args.Count > 0) {
338 field_infos = new ArrayList ();
339 prop_infos = new ArrayList ();
340 field_values = new ArrayList ();
341 prop_values = new ArrayList ();
344 Hashtable seen_names = new Hashtable();
346 for (i = 0; i < named_args.Count; i++) {
347 DictionaryEntry de = (DictionaryEntry) named_args [i];
348 string member_name = (string) de.Key;
349 Argument a = (Argument) de.Value;
352 if (seen_names.Contains(member_name)) {
353 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
356 seen_names.Add(member_name, 1);
358 if (!a.Resolve (ec, Location))
361 Expression member = Expression.MemberLookup (
362 ec, Type, member_name,
363 MemberTypes.Field | MemberTypes.Property,
364 BindingFlags.Public | BindingFlags.Instance,
367 if (member == null) {
368 member = Expression.MemberLookup (ec, Type, member_name,
369 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
372 if (member != null) {
373 Report.Error_T (122, Location, GetFullMemberName (member_name));
378 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
379 Error_InvalidNamedArgument (member_name);
384 if (e is TypeParameterExpr){
385 Error_TypeParameterInAttribute (Location);
389 if (member is PropertyExpr) {
390 PropertyExpr pe = (PropertyExpr) member;
391 PropertyInfo pi = pe.PropertyInfo;
394 Error_InvalidNamedArgument (member_name);
398 Constant c = e as Constant;
400 if (c.Type != pi.PropertyType) {
401 c = Const.ChangeType (Location, c, pi.PropertyType);
406 object o = c.GetValue ();
409 if (usage_attribute != null) {
410 if (member_name == "AllowMultiple")
411 usage_attribute.AllowMultiple = (bool) o;
412 if (member_name == "Inherited")
413 usage_attribute.Inherited = (bool) o;
416 } else if (e is TypeOf) {
417 prop_values.Add (((TypeOf) e).TypeArg);
418 } else if (e is ArrayCreation) {
419 prop_values.Add (((ArrayCreation) e).EncodeAsAttribute());
421 Error_AttributeArgumentNotValid (Location);
427 } else if (member is FieldExpr) {
428 FieldExpr fe = (FieldExpr) member;
429 FieldInfo fi = fe.FieldInfo;
432 Error_InvalidNamedArgument (member_name);
437 // Handle charset here, and set the TypeAttributes
439 Constant c = e as Constant;
441 if (c.Type != fi.FieldType){
442 c = Const.ChangeType (Location, c, fi.FieldType);
447 object value = c.GetValue ();
448 field_values.Add (value);
449 } else if (e is TypeOf) {
450 field_values.Add (((TypeOf) e).TypeArg);
452 Error_AttributeArgumentNotValid (Location);
456 field_infos.Add (fi);
460 Expression mg = Expression.MemberLookup (
461 ec, Type, ".ctor", MemberTypes.Constructor,
462 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
466 Error_AttributeConstructorMismatch ();
470 MethodBase constructor = Invocation.OverloadResolve (
471 ec, (MethodGroupExpr) mg, pos_args, false, Location);
473 if (constructor == null) {
474 Error_AttributeConstructorMismatch ();
479 // Now we perform some checks on the positional args as they
480 // cannot be null for a constructor which expects a parameter
484 ParameterData pd = Invocation.GetParameterData (constructor);
486 int group_in_params_array = Int32.MaxValue;
488 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
489 group_in_params_array = pc-1;
491 for (int j = 0; j < pos_arg_count; ++j) {
492 Argument a = (Argument) pos_args [j];
494 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
495 Error_AttributeArgumentNotValid (Location);
499 if (j < group_in_params_array)
502 if (j == group_in_params_array){
503 object v = pos_values [j];
504 int count = pos_arg_count - j;
506 object [] array = new object [count];
507 pos_values [j] = array;
510 object [] array = (object []) pos_values [group_in_params_array];
512 array [j - group_in_params_array] = pos_values [j];
517 // Adjust the size of the pos_values if it had params
519 if (group_in_params_array != Int32.MaxValue){
520 int argc = group_in_params_array+1;
521 object [] new_pos_values = new object [argc];
523 for (int p = 0; p < argc; p++)
524 new_pos_values [p] = pos_values [p];
525 pos_values = new_pos_values;
529 if (named_args.Count > 0) {
530 prop_info_arr = new PropertyInfo [prop_infos.Count];
531 field_info_arr = new FieldInfo [field_infos.Count];
532 field_values_arr = new object [field_values.Count];
533 prop_values_arr = new object [prop_values.Count];
535 field_infos.CopyTo (field_info_arr, 0);
536 field_values.CopyTo (field_values_arr, 0);
538 prop_values.CopyTo (prop_values_arr, 0);
539 prop_infos.CopyTo (prop_info_arr, 0);
541 cb = new CustomAttributeBuilder (
542 (ConstructorInfo) constructor, pos_values,
543 prop_info_arr, prop_values_arr,
544 field_info_arr, field_values_arr);
547 cb = new CustomAttributeBuilder (
548 (ConstructorInfo) constructor, pos_values);
549 } catch (NullReferenceException) {
551 // Don't know what to do here
554 -101, Location, "NullReferenceException while trying to create attribute." +
555 "Something's wrong!");
556 } catch (Exception e) {
559 // using System.ComponentModel;
560 // [DefaultValue (CollectionChangeAction.Add)]
561 // class X { static void Main () {} }
564 -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);
571 /// Get a string containing a list of valid targets for the attribute 'attr'
573 public string GetValidTargets ()
575 StringBuilder sb = new StringBuilder ();
576 AttributeTargets targets = GetAttributeUsage ().ValidOn;
578 if ((targets & AttributeTargets.Assembly) != 0)
579 sb.Append ("'assembly' ");
581 if ((targets & AttributeTargets.Class) != 0)
582 sb.Append ("'class' ");
584 if ((targets & AttributeTargets.Constructor) != 0)
585 sb.Append ("'constructor' ");
587 if ((targets & AttributeTargets.Delegate) != 0)
588 sb.Append ("'delegate' ");
590 if ((targets & AttributeTargets.Enum) != 0)
591 sb.Append ("'enum' ");
593 if ((targets & AttributeTargets.Event) != 0)
594 sb.Append ("'event' ");
596 if ((targets & AttributeTargets.Field) != 0)
597 sb.Append ("'field' ");
599 if ((targets & AttributeTargets.Interface) != 0)
600 sb.Append ("'interface' ");
602 if ((targets & AttributeTargets.Method) != 0)
603 sb.Append ("'method' ");
605 if ((targets & AttributeTargets.Module) != 0)
606 sb.Append ("'module' ");
608 if ((targets & AttributeTargets.Parameter) != 0)
609 sb.Append ("'parameter' ");
611 if ((targets & AttributeTargets.Property) != 0)
612 sb.Append ("'property' ");
614 if ((targets & AttributeTargets.ReturnValue) != 0)
615 sb.Append ("'return' ");
617 if ((targets & AttributeTargets.Struct) != 0)
618 sb.Append ("'struct' ");
620 return sb.ToString ();
625 /// Returns AttributeUsage attribute for this type
627 public AttributeUsageAttribute GetAttributeUsage ()
629 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
633 Class attr_class = TypeManager.LookupClass (Type);
635 if (attr_class == null) {
636 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
637 ua = (AttributeUsageAttribute)usage_attr [0];
638 usage_attr_cache.Add (Type, ua);
642 return attr_class.AttributeUsage;
645 public string IndexerName_GetIndexerName (EmitContext ec)
647 if (Arguments == null || Arguments [0] == null){
648 Error_AttributeConstructorMismatch ();
651 ArrayList pos_args = (ArrayList) Arguments [0];
652 if (pos_args.Count != 1) {
653 Error_AttributeConstructorMismatch ();
657 Argument arg = (Argument) pos_args [0];
658 if (!arg.Resolve (ec, Location))
661 StringConstant sc = arg.Expr as StringConstant;
663 Error_AttributeConstructorMismatch ();
671 /// Returns condition of ConditionalAttribute
673 public string GetConditionalAttributeValue (DeclSpace ds)
675 if (pos_values == null) {
676 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
678 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
679 // But because a lot of attribute class code must be rewritten will be better to wait...
683 // Some error occurred
684 if (pos_values [0] == null)
687 return (string)pos_values [0];
691 /// Creates the instance of ObsoleteAttribute from this attribute instance
693 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
695 if (pos_values == null) {
696 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
698 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
699 // But because a lot of attribute class code must be rewritten will be better to wait...
703 // Some error occurred
704 if (pos_values == null)
707 if (pos_values.Length == 0)
708 return new ObsoleteAttribute ();
710 if (pos_values.Length == 1)
711 return new ObsoleteAttribute ((string)pos_values [0]);
713 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
717 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
718 /// before ApplyAttribute. We need to resolve the arguments.
719 /// This situation occurs when class deps is differs from Emit order.
721 public bool GetClsCompliantAttributeValue (DeclSpace ds)
723 if (pos_values == null) {
724 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
726 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
727 // But because a lot of attribute class code must be rewritten will be better to wait...
731 // Some error occurred
732 if (pos_values [0] == null)
735 return (bool)pos_values [0];
738 public object GetPositionalValue (int i)
740 return (pos_values == null) ? null : pos_values[i];
743 object GetFieldValue (string name)
746 if (field_info_arr == null)
749 foreach (FieldInfo fi in field_info_arr) {
751 return field_values_arr [i];
757 public UnmanagedMarshal GetMarshal ()
759 object o = GetFieldValue ("ArraySubType");
760 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
762 switch (UnmanagedType) {
763 case UnmanagedType.CustomMarshaler:
764 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
765 BindingFlags.Static | BindingFlags.Public);
766 if (define_custom == null)
769 object [] args = new object [4];
770 args [0] = GetFieldValue ("MarshalTypeRef");
771 args [1] = GetFieldValue ("MarshalCookie");
772 args [2] = GetFieldValue ("MarshalType");
773 args [3] = Guid.Empty;
774 return (UnmanagedMarshal) define_custom.Invoke (null, args);
776 case UnmanagedType.LPArray:
777 return UnmanagedMarshal.DefineLPArray (array_sub_type);
779 case UnmanagedType.SafeArray:
780 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
782 case UnmanagedType.ByValArray:
783 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
785 case UnmanagedType.ByValTStr:
786 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
789 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
793 public bool IsInternalCall
795 get { return ImplOptions == MethodImplOptions.InternalCall; }
799 /// Emit attribute for Attributable symbol
801 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
803 CustomAttributeBuilder cb = Resolve (ec);
807 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
808 if ((usage_attr.ValidOn & ias.AttributeTargets) == 0) {
809 // "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.";
810 Report.Error_T (592, Location, Name, GetValidTargets ());
814 ias.ApplyAttributeBuilder (this, cb);
816 if (!usage_attr.AllowMultiple) {
817 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
818 if (emitted_targets == null) {
819 emitted_targets = new ArrayList ();
820 emitted_attr.Add (Type, emitted_targets);
821 } else if (emitted_targets.Contains (Target)) {
822 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
825 emitted_targets.Add (Target);
828 // Here we are testing attribute arguments for array usage (error 3016)
829 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
830 if (Arguments == null)
833 ArrayList pos_args = (ArrayList) Arguments [0];
834 if (pos_args != null) {
835 foreach (Argument arg in pos_args) {
836 // Type is undefined (was error 246)
837 if (arg.Type == null)
840 if (arg.Type.IsArray) {
841 Report.Error_T (3016, Location);
847 if (Arguments.Count < 2)
850 ArrayList named_args = (ArrayList) Arguments [1];
851 foreach (DictionaryEntry de in named_args) {
852 Argument arg = (Argument) de.Value;
854 // Type is undefined (was error 246)
855 if (arg.Type == null)
858 if (arg.Type.IsArray) {
859 Report.Error_T (3016, Location);
866 public object GetValue (EmitContext ec, Constant c, Type target)
868 if (Convert.ImplicitConversionExists (ec, c, target))
869 return c.GetValue ();
871 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
875 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
876 MethodAttributes flags, Type ret_type, Type [] param_types)
879 // We extract from the attribute the information we need
882 if (Arguments == null) {
883 Console.WriteLine ("Internal error : this is not supposed to happen !");
887 ResolveType (ec, true);
891 ArrayList named_args = new ArrayList ();
893 ArrayList pos_args = (ArrayList) Arguments [0];
894 if (Arguments.Count > 1)
895 named_args = (ArrayList) Arguments [1];
898 string dll_name = null;
900 Argument tmp = (Argument) pos_args [0];
902 if (!tmp.Resolve (ec, Location))
905 if (tmp.Expr is Constant)
906 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
908 Error_AttributeArgumentNotValid (Location);
912 // Now we process the named arguments
913 CallingConvention cc = CallingConvention.Winapi;
914 CharSet charset = CharSet.Ansi;
915 bool preserve_sig = true;
917 bool exact_spelling = false;
919 bool set_last_err = false;
920 string entry_point = null;
922 for (int i = 0; i < named_args.Count; i++) {
924 DictionaryEntry de = (DictionaryEntry) named_args [i];
926 string member_name = (string) de.Key;
927 Argument a = (Argument) de.Value;
929 if (!a.Resolve (ec, Location))
932 Expression member = Expression.MemberLookup (
933 ec, Type, member_name,
934 MemberTypes.Field | MemberTypes.Property,
935 BindingFlags.Public | BindingFlags.Instance,
938 if (member == null || !(member is FieldExpr)) {
939 Error_InvalidNamedArgument (member_name);
943 if (member is FieldExpr) {
944 FieldExpr fe = (FieldExpr) member;
945 FieldInfo fi = fe.FieldInfo;
948 Error_InvalidNamedArgument (member_name);
952 if (a.Expr is Constant) {
953 Constant c = (Constant) a.Expr;
956 if (member_name == "CallingConvention"){
957 object val = GetValue (ec, c, typeof (CallingConvention));
960 cc = (CallingConvention) val;
961 } else if (member_name == "CharSet"){
962 charset = (CharSet) c.GetValue ();
963 } else if (member_name == "EntryPoint")
964 entry_point = (string) c.GetValue ();
965 else if (member_name == "SetLastError")
966 set_last_err = (bool) c.GetValue ();
968 else if (member_name == "ExactSpelling")
969 exact_spelling = (bool) c.GetValue ();
971 else if (member_name == "PreserveSig")
972 preserve_sig = (bool) c.GetValue ();
973 } catch (InvalidCastException){
974 Error_InvalidNamedArgument (member_name);
975 Error_AttributeArgumentNotValid (Location);
978 Error_AttributeArgumentNotValid (Location);
985 if (entry_point == null)
988 charset = (CharSet)((int)charset | 0x40);
990 MethodBuilder mb = builder.DefinePInvokeMethod (
991 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
992 CallingConventions.Standard,
999 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1004 private Expression GetValue ()
1006 if ((Arguments == null) || (Arguments.Count < 1))
1008 ArrayList al = (ArrayList) Arguments [0];
1009 if ((al == null) || (al.Count < 1))
1011 Argument arg = (Argument) al [0];
1012 if ((arg == null) || (arg.Expr == null))
1017 public string GetString ()
1019 Expression e = GetValue ();
1020 if (e is StringLiteral)
1021 return (e as StringLiteral).Value;
1025 public bool GetBoolean ()
1027 Expression e = GetValue ();
1028 if (e is BoolLiteral)
1029 return (e as BoolLiteral).Value;
1036 /// For global attributes (assembly, module) we need special handling.
1037 /// Attributes can be located in the several files
1039 public class GlobalAttribute: Attribute
1041 public readonly NamespaceEntry ns;
1043 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1044 base (target, name, args, loc)
1046 ns = container.NamespaceEntry;
1049 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1051 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1052 if (old == null || old.NS == null || old.NS == Namespace.Root)
1053 ec.DeclSpace.NamespaceEntry = ns;
1054 return base.CheckAttributeType (ec, complain);
1058 public class Attributes {
1059 public ArrayList Attrs;
1061 public Attributes (Attribute a)
1063 Attrs = new ArrayList ();
1067 public Attributes (ArrayList attrs)
1072 public void AddAttributes (ArrayList attrs)
1074 Attrs.AddRange (attrs);
1078 /// Checks whether attribute target is valid for the current element
1080 public void CheckTargets (string[] possible_targets)
1082 foreach (Attribute a in Attrs) {
1083 if (a.Target == null) {
1084 a.Target = possible_targets [0];
1088 if (((IList) possible_targets).Contains (a.Target))
1091 StringBuilder sb = new StringBuilder ();
1092 foreach (string s in possible_targets) {
1096 sb.Remove (sb.Length - 2, 2);
1097 Report.Error_T (657, a.Location, a.Target, sb.ToString ());
1101 private Attribute Search (Type t, EmitContext ec, bool complain)
1103 foreach (Attribute a in Attrs) {
1104 if (a.ResolveType (ec, false) == t)
1110 public Attribute Search (Type t, EmitContext ec)
1112 return Search (t, ec, true);
1116 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1118 public Attribute[] SearchMulti (Type t, EmitContext ec)
1120 ArrayList ar = null;
1122 foreach (Attribute a in Attrs) {
1123 if (a.ResolveType (ec, false) == t) {
1125 ar = new ArrayList ();
1130 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1133 public void Emit (EmitContext ec, Attributable ias)
1135 ListDictionary ld = new ListDictionary ();
1137 foreach (Attribute a in Attrs)
1138 a.Emit (ec, ias, ld);
1141 public bool Contains (Type t, EmitContext ec)
1143 return Search (t, ec) != null;
1146 public Attribute GetClsCompliantAttribute (EmitContext ec)
1148 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1152 /// Pulls the IndexerName attribute from an Indexer if it exists.
1154 public string ScanForIndexerName (EmitContext ec)
1156 Attribute a = Search (TypeManager.indexer_name_type, ec);
1160 // Remove the attribute from the list
1161 //TODO: It is very close to hack and it can crash here
1164 return a.IndexerName_GetIndexerName (ec);
1170 /// Helper class for attribute verification routine.
1172 sealed class AttributeTester
1174 static PtrHashtable analyzed_types = new PtrHashtable ();
1175 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1176 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1177 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1179 private AttributeTester ()
1184 /// Returns true if parameters of two compared methods are CLS-Compliant.
1185 /// It tests differing only in ref or out, or in array rank.
1187 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1189 if (types_a == null || types_b == null)
1192 if (types_a.Length != types_b.Length)
1195 for (int i = 0; i < types_b.Length; ++i) {
1196 Type aType = types_a [i];
1197 Type bType = types_b [i];
1199 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1203 Type aBaseType = aType;
1204 bool is_either_ref_or_out = false;
1206 if (aType.IsByRef || aType.IsPointer) {
1207 aBaseType = aType.GetElementType ();
1208 is_either_ref_or_out = true;
1211 Type bBaseType = bType;
1212 if (bType.IsByRef || bType.IsPointer)
1214 bBaseType = bType.GetElementType ();
1215 is_either_ref_or_out = !is_either_ref_or_out;
1218 if (aBaseType != bBaseType)
1221 if (is_either_ref_or_out)
1228 /// Goes through all parameters and test if they are CLS-Compliant.
1230 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1232 if (fixedParameters == null)
1235 foreach (Parameter arg in fixedParameters) {
1236 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1237 Report.Error_T (3001, loc, arg.GetSignatureForError ());
1246 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1248 public static bool IsClsCompliant (Type type)
1253 object type_compliance = analyzed_types[type];
1254 if (type_compliance != null)
1255 return type_compliance == TRUE;
1257 if (type.IsPointer) {
1258 analyzed_types.Add (type, null);
1263 if (type.IsArray || type.IsByRef) {
1264 result = IsClsCompliant (TypeManager.GetElementType (type));
1266 result = AnalyzeTypeCompliance (type);
1268 analyzed_types.Add (type, result ? TRUE : FALSE);
1272 static object TRUE = new object ();
1273 static object FALSE = new object ();
1276 /// Non-hierarchical CLS Compliance analyzer
1278 public static bool IsComplianceRequired (MemberInfo mi, DeclSpace ds)
1280 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
1282 // Type is external, we can get attribute directly
1283 if (temp_ds == null) {
1284 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1285 return (cls_attribute.Length == 1 && ((CLSCompliantAttribute)cls_attribute[0]).IsCompliant);
1289 // Interface doesn't store full name
1290 if (temp_ds is Interface)
1293 tmp_name = String.Concat (temp_ds.Name, ".", mi.Name);
1295 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
1296 return mc.IsClsCompliaceRequired (ds);
1299 public static void VerifyModulesClsCompliance ()
1301 Module[] modules = TypeManager.Modules;
1302 if (modules == null)
1305 // The first module is generated assembly
1306 for (int i = 1; i < modules.Length; ++i) {
1307 Module module = modules [i];
1308 if (!IsClsCompliant (module)) {
1309 Report.Error_T (3013, module.Name);
1315 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1317 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1318 if (CompliantAttribute.Length == 0)
1321 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1324 static bool AnalyzeTypeCompliance (Type type)
1326 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1328 return ds.IsClsCompliaceRequired (ds.Parent);
1331 if (type.IsGenericParameter)
1334 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1335 if (CompliantAttribute.Length == 0)
1336 return IsClsCompliant (type.Assembly);
1338 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1342 /// Returns instance of ObsoleteAttribute when type is obsolete
1344 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1346 object type_obsolete = analyzed_types_obsolete [type];
1347 if (type_obsolete == FALSE)
1350 if (type_obsolete != null)
1351 return (ObsoleteAttribute)type_obsolete;
1353 ObsoleteAttribute result = null;
1354 if (type.IsByRef || type.IsArray || type.IsPointer) {
1355 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1356 } else if (type.IsGenericParameter || type.IsGenericInstance)
1359 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1361 // Type is external, we can get attribute directly
1362 if (type_ds == null) {
1363 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1364 if (attribute.Length == 1)
1365 result = (ObsoleteAttribute)attribute [0];
1367 result = type_ds.GetObsoleteAttribute (type_ds);
1371 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1376 /// Returns instance of ObsoleteAttribute when method is obsolete
1378 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1380 IMethodData mc = TypeManager.GetMethod (mb);
1382 return mc.GetObsoleteAttribute ();
1384 return GetMemberObsoleteAttribute (mb);
1388 /// Returns instance of ObsoleteAttribute when member is obsolete
1390 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1392 object type_obsolete = analyzed_member_obsolete [mi];
1393 if (type_obsolete == FALSE)
1396 if (type_obsolete != null)
1397 return (ObsoleteAttribute)type_obsolete;
1399 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1402 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1403 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1408 /// Common method for Obsolete error/warning reporting.
1410 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1413 Report.Error_T (619, loc, member, oa.Message);
1417 if (oa.Message == null) {
1418 Report.Warning_T (612, loc, member);
1421 Report.Warning_T (618, loc, member, oa.Message);
1424 public static bool IsConditionalMethodExcluded (MethodBase mb)
1426 object excluded = analyzed_method_excluded [mb];
1427 if (excluded != null)
1428 return excluded == TRUE ? true : false;
1430 if (mb.Mono_IsInflatedMethod)
1433 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1434 if (attrs.Length == 0) {
1435 analyzed_method_excluded.Add (mb, FALSE);
1439 foreach (ConditionalAttribute a in attrs) {
1440 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1441 analyzed_method_excluded.Add (mb, FALSE);
1445 analyzed_method_excluded.Add (mb, TRUE);