2009-05-22 Zoltan Varga <vargaz@gmail.com>
[mcs.git] / mcs / const.cs
blob23b6418793354098ee13f7e940a753afdfa833b0
1 //
2 // const.cs: Constant declarations.
3 //
4 // Author:
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
7 //
8 // Copyright 2001-2003 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
12 namespace Mono.CSharp {
14 using System;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections;
19 public interface IConstant
21 void CheckObsoleteness (Location loc);
22 bool ResolveValue ();
23 Constant CreateConstantReference (Location loc);
26 public class Const : FieldBase, IConstant {
27 protected Constant value;
28 bool in_transit;
29 bool resolved;
30 bool define_called;
32 public const int AllowedModifiers =
33 Modifiers.NEW |
34 Modifiers.PUBLIC |
35 Modifiers.PROTECTED |
36 Modifiers.INTERNAL |
37 Modifiers.PRIVATE;
39 public Const (DeclSpace parent, FullNamedExpression type, string name,
40 Expression expr, int mod_flags, Attributes attrs, Location loc)
41 : base (parent, type, mod_flags, AllowedModifiers,
42 new MemberName (name, loc), attrs)
44 initializer = expr;
45 ModFlags |= Modifiers.STATIC;
48 protected override bool CheckBase ()
50 // Constant.Define can be called when the parent type hasn't yet been populated
51 // and it's base types need not have been populated. So, we defer this check
52 // to the second time Define () is called on this member.
53 if (Parent.PartialContainer.BaseCache == null)
54 return true;
55 return base.CheckBase ();
58 /// <summary>
59 /// Defines the constant in the @parent
60 /// </summary>
61 public override bool Define ()
63 // Because constant define can be called from other class
64 if (define_called) {
65 CheckBase ();
66 return FieldBuilder != null;
69 define_called = true;
71 if (!base.Define ())
72 return false;
74 Type ttype = MemberType;
75 if (!IsConstantTypeValid (ttype)) {
76 Error_InvalidConstantType (ttype, Location);
79 // If the constant is private then we don't need any field the
80 // value is already inlined and cannot be referenced
81 //if ((ModFlags & Modifiers.PRIVATE) != 0 && RootContext.Optimize)
82 // return true;
84 FieldAttributes field_attr = FieldAttributes.Static | Modifiers.FieldAttr (ModFlags);
85 // Decimals cannot be emitted into the constant blob. So, convert to 'readonly'.
86 if (ttype == TypeManager.decimal_type) {
87 field_attr |= FieldAttributes.InitOnly;
88 } else {
89 field_attr |= FieldAttributes.Literal;
92 FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType, field_attr);
93 TypeManager.RegisterConstant (FieldBuilder, this);
94 Parent.MemberCache.AddMember (FieldBuilder, this);
96 if ((field_attr & FieldAttributes.InitOnly) != 0)
97 Parent.PartialContainer.RegisterFieldForInitialization (this,
98 new FieldInitializer (FieldBuilder, initializer, this));
100 return true;
103 public static bool IsConstantTypeValid (Type t)
105 if (TypeManager.IsBuiltinOrEnum (t))
106 return true;
108 if (TypeManager.IsGenericParameter (t) || t.IsPointer)
109 return false;
111 return TypeManager.IsReferenceType (t);
114 /// <summary>
115 /// Emits the field value by evaluating the expression
116 /// </summary>
117 public override void Emit ()
119 if (!ResolveValue ())
120 return;
122 if (FieldBuilder == null)
123 return;
125 if (value.Type == TypeManager.decimal_type) {
126 EmitDecimalConstant ();
127 } else{
128 FieldBuilder.SetConstant (value.GetTypedValue ());
131 base.Emit ();
134 void EmitDecimalConstant ()
136 PredefinedAttribute pa = PredefinedAttributes.Get.DecimalConstant;
137 if (pa.Constructor == null &&
138 !pa.ResolveConstructor (Location, TypeManager.byte_type, TypeManager.byte_type,
139 TypeManager.uint32_type, TypeManager.uint32_type, TypeManager.uint32_type))
140 return;
142 Decimal d = (Decimal) value.GetValue ();
143 int [] bits = Decimal.GetBits (d);
144 object [] args = new object [] {
145 (byte) (bits [3] >> 16),
146 (byte) (bits [3] >> 31),
147 (uint) bits [2], (uint) bits [1], (uint) bits [0]
150 CustomAttributeBuilder cab = new CustomAttributeBuilder (pa.Constructor, args);
151 FieldBuilder.SetCustomAttribute (cab);
154 public static void Error_ExpressionMustBeConstant (Location loc, string e_name)
156 Report.Error (133, loc, "The expression being assigned to `{0}' must be constant", e_name);
159 public static void Error_CyclicDeclaration (MemberCore mc)
161 Report.Error (110, mc.Location, "The evaluation of the constant value for `{0}' involves a circular definition",
162 mc.GetSignatureForError ());
165 public static void Error_ConstantCanBeInitializedWithNullOnly (Type type, Location loc, string name)
167 Report.Error (134, loc, "A constant `{0}' of reference type `{1}' can only be initialized with null",
168 name, TypeManager.CSharpName (type));
171 public static void Error_InvalidConstantType (Type t, Location loc)
173 if (TypeManager.IsGenericParameter (t)) {
174 Report.Error (1959, loc,
175 "Type parameter `{0}' cannot be declared const", TypeManager.CSharpName (t));
176 } else {
177 Report.Error (283, loc,
178 "The type `{0}' cannot be declared const", TypeManager.CSharpName (t));
182 #region IConstant Members
184 public bool ResolveValue ()
186 if (resolved)
187 return value != null;
189 SetMemberIsUsed ();
190 if (in_transit) {
191 Error_CyclicDeclaration (this);
192 // Suppress cyclic errors
193 value = New.Constantify (MemberType);
194 resolved = true;
195 return false;
198 in_transit = true;
199 // TODO: IResolveContext here
200 EmitContext ec = new EmitContext (
201 this, Parent, Location, null, MemberType, ModFlags);
202 ec.InEnumContext = this is EnumMember;
203 ec.IsAnonymousMethodAllowed = false;
204 value = DoResolveValue (ec);
205 in_transit = false;
206 resolved = true;
207 return value != null;
210 protected virtual Constant DoResolveValue (EmitContext ec)
212 Constant value = initializer.ResolveAsConstant (ec, this);
213 if (value == null)
214 return null;
216 Constant c = value.ConvertImplicitly (MemberType);
217 if (c == null) {
218 if (TypeManager.IsReferenceType (MemberType))
219 Error_ConstantCanBeInitializedWithNullOnly (MemberType, Location, GetSignatureForError ());
220 else
221 value.Error_ValueCannotBeConverted (ec, Location, MemberType, false);
224 return c;
227 public virtual Constant CreateConstantReference (Location loc)
229 if (value == null)
230 return null;
232 return Constant.CreateConstant (value.Type, value.GetValue(), loc);
235 #endregion
238 public class ExternalConstant : IConstant
240 FieldInfo fi;
241 object value;
243 public ExternalConstant (FieldInfo fi)
245 this.fi = fi;
248 private ExternalConstant (FieldInfo fi, object value):
249 this (fi)
251 this.value = value;
255 // Decimal constants cannot be encoded in the constant blob, and thus are marked
256 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
257 // DecimalConstantAttribute metadata.
259 public static IConstant CreateDecimal (FieldInfo fi)
261 if (fi is FieldBuilder)
262 return null;
264 PredefinedAttribute pa = PredefinedAttributes.Get.DecimalConstant;
265 if (!pa.IsDefined)
266 return null;
268 object[] attrs = fi.GetCustomAttributes (pa.Type, false);
269 if (attrs.Length != 1)
270 return null;
272 IConstant ic = new ExternalConstant (fi,
273 ((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
275 return ic;
278 #region IConstant Members
280 public void CheckObsoleteness (Location loc)
282 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
283 if (oa == null) {
284 return;
287 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), loc);
290 public bool ResolveValue ()
292 if (value != null)
293 return true;
295 value = fi.GetValue (fi);
296 return true;
299 public Constant CreateConstantReference (Location loc)
301 return Constant.CreateConstant (TypeManager.TypeToCoreType (fi.FieldType), value, loc);
304 #endregion