2005-12-23 Miguel de Icaza <miguel@novell.com>
[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 Value { get; }
24         }
25
26         public class Const : FieldMember, IConstant {
27                 Constant value;
28                 bool in_transit;
29
30                 public const int AllowedModifiers =
31                         Modifiers.NEW |
32                         Modifiers.PUBLIC |
33                         Modifiers.PROTECTED |
34                         Modifiers.INTERNAL |
35                         Modifiers.PRIVATE;
36
37                 public Const (TypeContainer parent, Expression constant_type, string name,
38                               Expression expr, int mod_flags, Attributes attrs, Location loc)
39                         : base (parent, constant_type, mod_flags, AllowedModifiers,
40                                 new MemberName (name, loc), attrs)
41                 {
42                         initializer = expr;
43                         ModFlags |= Modifiers.STATIC;
44                 }
45
46                 protected override bool CheckBase ()
47                 {
48                         // Constant.Define can be called when the parent type hasn't yet been populated
49                         // and it's base types need not have been populated.  So, we defer this check
50                         // to the second time Define () is called on this member.
51                         if (Parent.BaseCache == null)
52                                 return true;
53                         return base.CheckBase ();
54                 }
55
56                 /// <summary>
57                 ///   Defines the constant in the @parent
58                 /// </summary>
59                 public override bool Define ()
60                 {
61                         // Make Define () idempotent, but ensure that the error check happens.
62                         if (FieldBuilder != null)
63                                 return base.CheckBase ();
64
65                         if (!base.Define ())
66                                 return false;
67
68                         Type ttype = MemberType;
69                         while (ttype.IsArray)
70                             ttype = TypeManager.GetElementType (ttype);
71
72                         FieldAttributes field_attr = FieldAttributes.Static | Modifiers.FieldAttr (ModFlags);
73                         // Decimals cannot be emitted into the constant blob.  So, convert to 'readonly'.
74                         if (ttype == TypeManager.decimal_type) {
75                                 field_attr |= FieldAttributes.InitOnly;
76                                 Parent.RegisterFieldForInitialization (this);
77                         }
78                         else {
79                                 field_attr |= FieldAttributes.Literal;
80                         }
81
82                         FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType, field_attr);
83
84                         TypeManager.RegisterConstant (FieldBuilder, this);
85
86                         return true;
87                 }
88                 
89                 /// <summary>
90                 ///  Emits the field value by evaluating the expression
91                 /// </summary>
92                 public override void Emit ()
93                 {
94                         if (!ResolveValue ())
95                                 return;
96
97                         if (value.Type == TypeManager.decimal_type) {
98                                 Decimal d = ((DecimalConstant)value).Value;
99                                 int[] bits = Decimal.GetBits (d);
100                                 object[] args = new object[] { (byte)(bits [3] >> 16), (byte)(bits [3] >> 31), (uint)bits [2], (uint)bits [1], (uint)bits [0] };
101                                 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.decimal_constant_attribute_ctor, args);
102                                 FieldBuilder.SetCustomAttribute (cab);
103                         }
104                         else{
105                                 FieldBuilder.SetConstant (value.GetTypedValue ());
106                         }
107
108                         base.Emit ();
109                 }
110
111                 public static void Error_ExpressionMustBeConstant (Location loc, string e_name)
112                 {
113                         Report.Error (133, loc, "The expression being assigned to `{0}' must be constant", e_name);
114                 }
115
116                 public static void Error_CyclicDeclaration (MemberCore mc)
117                 {
118                         Report.Error (110, mc.Location, "The evaluation of the constant value for `{0}' involves a circular definition",
119                                 mc.GetSignatureForError ());
120                 }
121
122                 #region IConstant Members
123
124                 public bool ResolveValue ()
125                 {
126                         if (value != null)
127                                 return true;
128
129                         SetMemberIsUsed ();
130                         if (in_transit) {
131                                 Error_CyclicDeclaration (this);
132                                 // Suppress cyclic errors
133                                 value = New.Constantify (MemberType);
134                                 return false;
135                         }
136
137                         in_transit = true;
138                         EmitContext ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
139                         value = initializer.ResolveAsConstant (ec, this);
140                         in_transit = false;
141
142                         if (value == null)
143                                 return false;
144
145                         value = value.ToType (MemberType, Location);
146                         if (value == null)
147                                 return false;
148
149                         if (!MemberType.IsValueType && MemberType != TypeManager.string_type && !value.IsDefaultValue) {
150                                 Report.Error (134, Location, "`{0}': A const of reference other than string can only be initialized with null",
151                                         GetSignatureForError ());
152                                 return false;
153                         }
154
155                         return true;
156                 }
157
158                 public Constant Value {
159                         get {
160                                 return value;
161                         }
162                 }
163
164                 #endregion
165         }
166
167         public class ExternalConstant : IConstant
168         {
169                 FieldInfo fi;
170                 Constant value;
171
172                 public ExternalConstant (FieldInfo fi)
173                 {
174                         this.fi = fi;
175                 }
176
177                 private ExternalConstant (FieldInfo fi, Constant value):
178                         this (fi)
179                 {
180                         this.value = value;
181                 }
182
183                 //
184                 // Decimal constants cannot be encoded in the constant blob, and thus are marked
185                 // as IsInitOnly ('readonly' in C# parlance).  We get its value from the 
186                 // DecimalConstantAttribute metadata.
187                 //
188                 public static IConstant CreateDecimal (FieldInfo fi)
189                 {
190                         if (fi is FieldBuilder)
191                                 return null;
192                         
193                         object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
194                         if (attrs.Length != 1)
195                                 return null;
196
197                         IConstant ic = new ExternalConstant (fi,
198                                 new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value, Location.Null));
199
200                         return ic;
201                 }
202
203                 #region IConstant Members
204
205                 public void CheckObsoleteness (Location loc)
206                 {
207                         ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
208                         if (oa == null) {
209                                 return;
210                         }
211
212                         AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), loc);
213                 }
214
215                 public bool ResolveValue ()
216                 {
217                         if (value != null)
218                                 return true;
219
220                         if (fi.DeclaringType.IsEnum) {
221                                 value = Expression.Constantify (fi.GetValue (fi), TypeManager.EnumToUnderlying (fi.FieldType));
222                                 value = new EnumConstant (value, fi.DeclaringType);
223                                 return true;
224                         }
225
226                         value = Expression.Constantify (fi.GetValue (fi), fi.FieldType);
227                         return true;
228                 }
229
230                 public Constant Value {
231                         get {
232                                 return value;
233                         }
234                 }
235
236                 #endregion
237         }
238
239 }