2004-08-04 Marek Safar <marek.safar@seznam.cz>
[mono.git] / mcs / mcs / const.cs
1 //
2 // const.cs: Constant declarations.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc.
8 //
9 //
10
11 //
12 // This is needed because the following situation arises:
13 //
14 //     The FieldBuilder is declared with the real type for an enumeration
15 //
16 //     When we attempt to set the value for the constant, the FieldBuilder.SetConstant
17 //     function aborts because it requires its argument to be of the same type
18 //
19
20 namespace Mono.CSharp {
21
22         using System;
23         using System.Reflection;
24         using System.Reflection.Emit;
25         using System.Collections;
26
27         public class Const : FieldBase {
28                 public Expression Expr;
29                 EmitContext const_ec;
30
31                 bool resolved = false;
32                 object ConstantValue = null;
33                 Type type;
34
35                 bool in_transit = false;
36
37                 public const int AllowedModifiers =
38                         Modifiers.NEW |
39                         Modifiers.PUBLIC |
40                         Modifiers.PROTECTED |
41                         Modifiers.INTERNAL |
42                         Modifiers.PRIVATE;
43
44                 public Const (TypeContainer parent, Expression constant_type, string name,
45                               Expression expr, int mod_flags, Attributes attrs, Location loc)
46                         : base (parent, constant_type, mod_flags, AllowedModifiers, name,
47                                 null, attrs, loc)
48                 {
49                         Expr = expr;
50                 }
51
52                 public FieldAttributes FieldAttr {
53                         get {
54                                 return FieldAttributes.Literal | FieldAttributes.Static |
55                                         Modifiers.FieldAttr (ModFlags) ;
56                         }
57                 }
58
59 #if DEBUG
60                 void dump_tree (Type t)
61                 {
62                         Console.WriteLine ("Dumping hierarchy");
63                         while (t != null){
64                                 Console.WriteLine ("   " + t.FullName + " " +
65                                         (t.GetType ().IsEnum ? "yes" : "no"));
66                                 t = t.BaseType;
67                         }
68                 }
69 #endif
70
71                 /// <summary>
72                 ///   Defines the constant in the @parent
73                 /// </summary>
74                 public override bool Define ()
75                 {
76                         type = Parent.ResolveType (Type, false, Location);
77
78                         if (type == null)
79                                 return false;
80
81                         const_ec = new EmitContext (Parent, Location, null, type, ModFlags);
82
83                         Type ttype = type;
84                         while (ttype.IsArray)
85                             ttype = TypeManager.GetElementType (ttype);
86                         
87                         if (!TypeManager.IsBuiltinType (ttype) &&
88                             (!ttype.IsSubclassOf (TypeManager.enum_type))) {
89                                 Report.Error (
90                                         -3, Location,
91                                         "Constant type is not valid (only system types are allowed)");
92                                 return false;
93                         }
94
95                         if (!CheckBase ())
96                                 return false;
97
98                         FieldBuilder = Parent.TypeBuilder.DefineField (Name, type, FieldAttr);
99
100                         TypeManager.RegisterConstant (FieldBuilder, this);
101
102                         return true;
103                 }
104
105                 //
106                 // Changes the type of the constant expression `expr' to the Type `type'
107                 // Returns null on failure.
108                 //
109                 public static Constant ChangeType (Location loc, Constant expr, Type type)
110                 {
111                         if (type == TypeManager.object_type)
112                                 return expr;
113
114                         bool fail;
115
116                         // from the null type to any reference-type.
117                         if (expr is NullLiteral && !type.IsValueType && !TypeManager.IsEnumType (type))
118                                 return NullLiteral.Null;
119
120                         if (!Convert.ImplicitStandardConversionExists (expr, type)){
121                                 Convert.Error_CannotImplicitConversion (loc, expr.Type, type);
122                                 return null;
123                         }
124                         
125                         object constant_value = TypeManager.ChangeType (expr.GetValue (), type, out fail);
126                         if (fail){
127                                 Convert.Error_CannotImplicitConversion (loc, expr.Type, type);
128                                 
129                                 //
130                                 // We should always catch the error before this is ever
131                                 // reached, by calling Convert.ImplicitStandardConversionExists
132                                 //
133                                 throw new Exception (
134                                                      String.Format ("LookupConstantValue: This should never be reached {0} {1}", expr.Type, type));
135                         }
136
137                         Constant retval;
138                         if (type == TypeManager.int32_type)
139                                 retval = new IntConstant ((int) constant_value);
140                         else if (type == TypeManager.uint32_type)
141                                 retval = new UIntConstant ((uint) constant_value);
142                         else if (type == TypeManager.int64_type)
143                                 retval = new LongConstant ((long) constant_value);
144                         else if (type == TypeManager.uint64_type)
145                                 retval = new ULongConstant ((ulong) constant_value);
146                         else if (type == TypeManager.float_type)
147                                 retval = new FloatConstant ((float) constant_value);
148                         else if (type == TypeManager.double_type)
149                                 retval = new DoubleConstant ((double) constant_value);
150                         else if (type == TypeManager.string_type)
151                                 retval = new StringConstant ((string) constant_value);
152                         else if (type == TypeManager.short_type)
153                                 retval = new ShortConstant ((short) constant_value);
154                         else if (type == TypeManager.ushort_type)
155                                 retval = new UShortConstant ((ushort) constant_value);
156                         else if (type == TypeManager.sbyte_type)
157                                 retval = new SByteConstant ((sbyte) constant_value);
158                         else if (type == TypeManager.byte_type)
159                                 retval = new ByteConstant ((byte) constant_value);
160                         else if (type == TypeManager.char_type)
161                                 retval = new CharConstant ((char) constant_value);
162                         else if (type == TypeManager.bool_type)
163                                 retval = new BoolConstant ((bool) constant_value);
164                         else
165                                 throw new Exception ("LookupConstantValue: Unhandled constant type: " + type);
166                         
167                         return retval;
168                 }
169                 
170                 /// <summary>
171                 ///  Looks up the value of a constant field. Defines it if it hasn't
172                 ///  already been. Similar to LookupEnumValue in spirit.
173                 /// </summary>
174                 public bool LookupConstantValue (out object value)
175                 {
176                         if (resolved) {
177                                 value = ConstantValue;
178                                 return true;
179                         }
180
181                         if (in_transit) {
182                                 Report.Error (110, Location,
183                                               "The evaluation of the constant value for `" +
184                                               Name + "' involves a circular definition.");
185                                 value = null;
186                                 return false;
187                         }
188
189                         in_transit = true;
190                         int errors = Report.Errors;
191
192                         //
193                         // We might have cleared Expr ourselves in a recursive definition
194                         //
195                         if (Expr == null){
196                                 value = null;
197                                 return false;
198                         }
199
200                         Expr = Expr.Resolve (const_ec);
201
202                         in_transit = false;
203
204                         if (Expr == null) {
205                                 if (errors == Report.Errors)
206                                         Report.Error (150, Location, "A constant value is expected");
207                                 value = null;
208                                 return false;
209                         }
210
211                         Expression real_expr = Expr;
212
213                         Constant ce = Expr as Constant;
214                         if (ce == null){
215                                 UnCheckedExpr un_expr = Expr as UnCheckedExpr;
216                                 CheckedExpr ch_expr = Expr as CheckedExpr;
217                                 EmptyCast ec_expr = Expr as EmptyCast;
218
219                                 if ((un_expr != null) && (un_expr.Expr is Constant))
220                                         Expr = un_expr.Expr;
221                                 else if ((ch_expr != null) && (ch_expr.Expr is Constant))
222                                         Expr = ch_expr.Expr;
223                                 else if ((ec_expr != null) && (ec_expr.Child is Constant))
224                                         Expr = ec_expr.Child;
225                                 else if (Expr is ArrayCreation) {
226                                         ArrayCreation ac = (ArrayCreation) Expr;
227
228                                         Expr = ac.TurnIntoConstant ();
229                                         if (Expr == null){
230                                                 Report.Error (150, Location, "A constant value is expected");
231                                                 value = null;
232                                                 return false;
233                                         }
234                                 } else {
235                                         if (errors == Report.Errors)
236                                                 Report.Error (150, Location, "A constant value is expected");
237                                         value = null;
238                                         return false;
239                                 }
240
241                                 ce = Expr as Constant;
242                         }
243
244                         if (type != real_expr.Type) {
245                                 ce = ChangeType (Location, ce, type);
246                                 if (ce == null){
247                                         value = null;
248                                         return false;
249                                 }
250                                 Expr = ce;
251                         }
252                         ConstantValue = ce.GetValue ();
253
254                         if (type.IsEnum){
255                                 //
256                                 // This sadly does not work for our user-defined enumerations types ;-(
257                                 //
258                                 try {
259                                         ConstantValue = System.Enum.ToObject (
260                                                 type, ConstantValue);
261                                 } catch (ArgumentException){
262                                         Report.Error (
263                                                 -16, Location,
264                                                 ".NET SDK 1.0 does not permit to create the constant "+
265                                                 " field from a user-defined enumeration");
266                                 }
267                         }
268
269                         FieldBuilder.SetConstant (ConstantValue);
270
271                         if (!TypeManager.RegisterFieldValue (FieldBuilder, ConstantValue))
272                                 throw new Exception ("Cannot register const value");
273
274                         value = ConstantValue;
275                         resolved = true;
276                         return true;
277                 }
278                 
279                 
280                 /// <summary>
281                 ///  Emits the field value by evaluating the expression
282                 /// </summary>
283                 public override void Emit ()
284                 {
285                         object value;
286                         LookupConstantValue (out value);
287
288                         if (OptAttributes != null) {
289                                 OptAttributes.Emit (const_ec, this);
290                         }
291
292                         base.Emit ();
293                 }
294         }
295 }
296
297