2008-02-16 Ivan N. Zlatev <contact@i-nz.net>
[mono.git] / mcs / mcs / const.cs
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 // (C) 2001 Ximian, Inc.
9 //
10 //
11
12 namespace Mono.CSharp {
13
14         using System;
15         using System.Reflection;
16         using System.Reflection.Emit;
17         using System.Collections;
18
19         public interface IConstant
20         {
21                 void CheckObsoleteness (Location loc);
22                 bool ResolveValue ();
23                 Constant CreateConstantReference (Location loc);
24         }
25
26         public class Const : FieldBase, IConstant {
27                 protected Constant value;
28                 bool in_transit;
29                 bool resolved;
30                 bool define_called;
31
32                 public const int AllowedModifiers =
33                         Modifiers.NEW |
34                         Modifiers.PUBLIC |
35                         Modifiers.PROTECTED |
36                         Modifiers.INTERNAL |
37                         Modifiers.PRIVATE;
38
39                 public Const (DeclSpace parent, Expression constant_type, string name,
40                               Expression expr, int mod_flags, Attributes attrs, Location loc)
41                         : base (parent, constant_type, mod_flags, AllowedModifiers,
42                                 new MemberName (name, loc), attrs)
43                 {
44                         initializer = expr;
45                         ModFlags |= Modifiers.STATIC;
46                 }
47
48                 protected override bool CheckBase ()
49                 {
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 ();
56                 }
57
58                 /// <summary>
59                 ///   Defines the constant in the @parent
60                 /// </summary>
61                 public override bool Define ()
62                 {
63                         // Because constant define can be called from other class
64                         if (define_called) {
65                                 CheckBase ();
66                                 return FieldBuilder != null;
67                         }
68
69                         define_called = true;
70
71                         if (!base.Define ())
72                                 return false;
73
74                         Type ttype = MemberType;
75                         if (!IsConstantTypeValid (ttype)) {
76                                 Error_InvalidConstantType (ttype, Location);
77                                 return false;
78                         }
79
80                         // If the constant is private then we don't need any field the
81                         // value is already inlined and cannot be referenced
82                         //if ((ModFlags & Modifiers.PRIVATE) != 0 && RootContext.Optimize)
83                         //      return true;
84
85                         while (ttype.IsArray)
86                                 ttype = TypeManager.GetElementType (ttype);
87
88                         FieldAttributes field_attr = FieldAttributes.Static | Modifiers.FieldAttr (ModFlags);
89                         // Decimals cannot be emitted into the constant blob.  So, convert to 'readonly'.
90                         if (ttype == TypeManager.decimal_type) {
91                                 field_attr |= FieldAttributes.InitOnly;
92                         } else {
93                                 field_attr |= FieldAttributes.Literal;
94                         }
95
96                         FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType, field_attr);
97                         TypeManager.RegisterConstant (FieldBuilder, this);
98                         Parent.MemberCache.AddMember (FieldBuilder, this);
99
100                         if (ttype == TypeManager.decimal_type)
101                                 Parent.PartialContainer.RegisterFieldForInitialization (this,
102                                         new FieldInitializer (FieldBuilder, initializer));
103
104                         return true;
105                 }
106
107                 public static bool IsConstantTypeValid (Type t)
108                 {
109                         if (TypeManager.IsBuiltinOrEnum (t))
110                                 return true;
111
112                         if (t.IsPointer || t.IsValueType)
113                                 return false;
114                         
115                         if (TypeManager.IsGenericParameter (t))
116                                 return false;
117
118                         return true;
119                 }
120
121                 /// <summary>
122                 ///  Emits the field value by evaluating the expression
123                 /// </summary>
124                 public override void Emit ()
125                 {
126                         if (!ResolveValue ())
127                                 return;
128
129                         if (FieldBuilder == null)
130                                 return;
131
132                         if (value.Type == TypeManager.decimal_type) {
133                                 Decimal d = ((DecimalConstant)value).Value;
134                                 int[] bits = Decimal.GetBits (d);
135                                 object[] args = new object[] { (byte)(bits [3] >> 16), (byte)(bits [3] >> 31), (uint)bits [2], (uint)bits [1], (uint)bits [0] };
136                                 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.decimal_constant_attribute_ctor, args);
137                                 FieldBuilder.SetCustomAttribute (cab);
138                         }
139                         else{
140                                 FieldBuilder.SetConstant (value.GetTypedValue ());
141                         }
142
143                         base.Emit ();
144                 }
145
146                 public static void Error_ExpressionMustBeConstant (Location loc, string e_name)
147                 {
148                         Report.Error (133, loc, "The expression being assigned to `{0}' must be constant", e_name);
149                 }
150
151                 public static void Error_CyclicDeclaration (MemberCore mc)
152                 {
153                         Report.Error (110, mc.Location, "The evaluation of the constant value for `{0}' involves a circular definition",
154                                 mc.GetSignatureForError ());
155                 }
156
157                 public static void Error_ConstantCanBeInitializedWithNullOnly (Location loc, string name)
158                 {
159                         Report.Error (134, loc, "`{0}': the constant of reference type other than string can only be initialized with null",
160                                 name);
161                 }
162
163                 public static void Error_InvalidConstantType (Type t, Location loc)
164                 {
165                         Report.Error (283, loc, "The type `{0}' cannot be declared const", TypeManager.CSharpName (t));
166                 }
167
168                 #region IConstant Members
169
170                 public bool ResolveValue ()
171                 {
172                         if (resolved)
173                                 return value != null;
174
175                         SetMemberIsUsed ();
176                         if (in_transit) {
177                                 Error_CyclicDeclaration (this);
178                                 // Suppress cyclic errors
179                                 value = New.Constantify (MemberType);
180                                 resolved = true;
181                                 return false;
182                         }
183
184                         in_transit = true;
185                         // TODO: IResolveContext here
186                         EmitContext ec = new EmitContext (
187                                 this, Parent, Location, null, MemberType, ModFlags);
188                         ec.InEnumContext = this is EnumMember;
189                         ec.IsAnonymousMethodAllowed = false;
190                         value = DoResolveValue (ec);
191                         in_transit = false;
192                         resolved = true;
193                         return value != null;
194                 }
195
196                 protected virtual Constant DoResolveValue (EmitContext ec)
197                 {
198                         Constant value = initializer.ResolveAsConstant (ec, this);
199                         if (value == null)
200                                 return null;
201
202                         Constant c = value.ConvertImplicitly (MemberType);
203                         if (c == null) {
204                                 if (!MemberType.IsValueType && MemberType != TypeManager.string_type && !value.IsDefaultValue)
205                                         Error_ConstantCanBeInitializedWithNullOnly (Location, GetSignatureForError ());
206                                 else
207                                         value.Error_ValueCannotBeConverted (null, Location, MemberType, false);
208                         }
209
210                         return c;
211                 }
212
213                 public virtual Constant CreateConstantReference (Location loc)
214                 {
215                         if (value == null)
216                                 return null;
217
218                         return Constant.CreateConstant (value.Type, value.GetValue(), loc);
219                 }
220
221                 #endregion
222         }
223
224         public class ExternalConstant : IConstant
225         {
226                 FieldInfo fi;
227                 object value;
228
229                 public ExternalConstant (FieldInfo fi)
230                 {
231                         this.fi = fi;
232                 }
233
234                 private ExternalConstant (FieldInfo fi, object value):
235                         this (fi)
236                 {
237                         this.value = value;
238                 }
239
240                 //
241                 // Decimal constants cannot be encoded in the constant blob, and thus are marked
242                 // as IsInitOnly ('readonly' in C# parlance).  We get its value from the 
243                 // DecimalConstantAttribute metadata.
244                 //
245                 public static IConstant CreateDecimal (FieldInfo fi)
246                 {
247                         if (fi is FieldBuilder)
248                                 return null;
249                         
250                         object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
251                         if (attrs.Length != 1)
252                                 return null;
253
254                         IConstant ic = new ExternalConstant (fi,
255                                 ((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
256
257                         return ic;
258                 }
259
260                 #region IConstant Members
261
262                 public void CheckObsoleteness (Location loc)
263                 {
264                         ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
265                         if (oa == null) {
266                                 return;
267                         }
268
269                         AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), loc);
270                 }
271
272                 public bool ResolveValue ()
273                 {
274                         if (value != null)
275                                 return true;
276
277                         value = fi.GetValue (fi);
278                         return true;
279                 }
280
281                 public Constant CreateConstantReference (Location loc)
282                 {
283                         return Constant.CreateConstant (fi.FieldType, value, loc);
284                 }
285
286                 #endregion
287         }
288
289 }