2004-04-28 Martin Baulig <martin@ximian.com>
[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 (Expression constant_type, string name, Expression expr, int mod_flags,
45                               Attributes attrs, Location loc)
46                         : base (constant_type, mod_flags, AllowedModifiers, name, null, attrs, loc)
47                 {
48                         Expr = expr;
49                 }
50
51                 public FieldAttributes FieldAttr {
52                         get {
53                                 return FieldAttributes.Literal | FieldAttributes.Static |
54                                         Modifiers.FieldAttr (ModFlags) ;
55                         }
56                 }
57
58 #if DEBUG
59                 void dump_tree (Type t)
60                 {
61                         Console.WriteLine ("Dumping hierarchy");
62                         while (t != null){
63                                 Console.WriteLine ("   " + t.FullName + " " +
64                                         (t.GetType ().IsEnum ? "yes" : "no"));
65                                 t = t.BaseType;
66                         }
67                 }
68 #endif
69
70                 /// <summary>
71                 ///   Defines the constant in the @parent
72                 /// </summary>
73                 public override bool Define (TypeContainer parent)
74                 {
75                         type = parent.ResolveType (Type, false, Location);
76
77                         if (type == null)
78                                 return false;
79
80                         const_ec = new EmitContext (parent, Location, null, type, ModFlags);
81
82                         Type ttype = type;
83                         while (ttype.IsArray)
84                             ttype = TypeManager.GetElementType (ttype);
85                         
86                         if (!TypeManager.IsBuiltinType (ttype) &&
87                             (!ttype.IsSubclassOf (TypeManager.enum_type))) {
88                                 Report.Error (
89                                         -3, Location,
90                                         "Constant type is not valid (only system types are allowed)");
91                                 return false;
92                         }
93
94                         Type ptype = parent.TypeBuilder.BaseType;
95
96                         if (ptype != null) {
97                                 MemberList list = TypeContainer.FindMembers (
98                                         ptype, MemberTypes.Field, BindingFlags.Public,
99                                         System.Type.FilterName, Name);
100                                 
101                                 if (list.Count == 0)
102                                         if ((ModFlags & Modifiers.NEW) != 0)
103                                                 WarningNotHiding (parent);
104
105                         } else if ((ModFlags & Modifiers.NEW) != 0)
106                                 WarningNotHiding (parent);
107
108                         FieldBuilder = parent.TypeBuilder.DefineField (Name, type, FieldAttr);
109
110                         TypeManager.RegisterConstant (FieldBuilder, this);
111
112                         return true;
113                 }
114
115                 //
116                 // Changes the type of the constant expression `expr' to the Type `type'
117                 // Returns null on failure.
118                 //
119                 public static Constant ChangeType (Location loc, Constant expr, Type type)
120                 {
121                         bool fail;
122
123                         // from the null type to any reference-type.
124                         if (expr is NullLiteral && !type.IsValueType && !TypeManager.IsEnumType (type))
125                                 return NullLiteral.Null;
126
127                         if (!Convert.ImplicitStandardConversionExists (expr, type)){
128                                 Convert.Error_CannotImplicitConversion (loc, expr.Type, type);
129                                 return null;
130                         }
131                         
132                         object constant_value = TypeManager.ChangeType (expr.GetValue (), type, out fail);
133                         if (fail){
134                                 Convert.Error_CannotImplicitConversion (loc, expr.Type, type);
135                                 
136                                 //
137                                 // We should always catch the error before this is ever
138                                 // reached, by calling Convert.ImplicitStandardConversionExists
139                                 //
140                                 throw new Exception (
141                                                      String.Format ("LookupConstantValue: This should never be reached {0} {1}", expr.Type, type));
142                         }
143
144                         Constant retval;
145                         if (type == TypeManager.int32_type)
146                                 retval = new IntConstant ((int) constant_value);
147                         else if (type == TypeManager.uint32_type)
148                                 retval = new UIntConstant ((uint) constant_value);
149                         else if (type == TypeManager.int64_type)
150                                 retval = new LongConstant ((long) constant_value);
151                         else if (type == TypeManager.uint64_type)
152                                 retval = new ULongConstant ((ulong) constant_value);
153                         else if (type == TypeManager.float_type)
154                                 retval = new FloatConstant ((float) constant_value);
155                         else if (type == TypeManager.double_type)
156                                 retval = new DoubleConstant ((double) constant_value);
157                         else if (type == TypeManager.string_type)
158                                 retval = new StringConstant ((string) constant_value);
159                         else if (type == TypeManager.short_type)
160                                 retval = new ShortConstant ((short) constant_value);
161                         else if (type == TypeManager.ushort_type)
162                                 retval = new UShortConstant ((ushort) constant_value);
163                         else if (type == TypeManager.sbyte_type)
164                                 retval = new SByteConstant ((sbyte) constant_value);
165                         else if (type == TypeManager.byte_type)
166                                 retval = new ByteConstant ((byte) constant_value);
167                         else if (type == TypeManager.char_type)
168                                 retval = new CharConstant ((char) constant_value);
169                         else if (type == TypeManager.bool_type)
170                                 retval = new BoolConstant ((bool) constant_value);
171                         else
172                                 throw new Exception ("LookupConstantValue: Unhandled constant type: " + type);
173                         
174                         return retval;
175                 }
176                 
177                 /// <summary>
178                 ///  Looks up the value of a constant field. Defines it if it hasn't
179                 ///  already been. Similar to LookupEnumValue in spirit.
180                 /// </summary>
181                 public bool LookupConstantValue (out object value)
182                 {
183                         if (resolved) {
184                                 value = ConstantValue;
185                                 return true;
186                         }
187
188                         if (in_transit) {
189                                 Report.Error (110, Location,
190                                               "The evaluation of the constant value for `" +
191                                               Name + "' involves a circular definition.");
192                                 value = null;
193                                 return false;
194                         }
195
196                         in_transit = true;
197                         int errors = Report.Errors;
198
199                         //
200                         // We might have cleared Expr ourselves in a recursive definition
201                         //
202                         if (Expr == null){
203                                 value = null;
204                                 return false;
205                         }
206                         
207                         Expr = Expr.Resolve (const_ec);
208
209                         in_transit = false;
210
211                         if (Expr == null) {
212                                 if (errors == Report.Errors)
213                                         Report.Error (150, Location, "A constant value is expected");
214                                 value = null;
215                                 return false;
216                         }
217
218                         Constant ce = Expr as Constant;
219                         if (ce == null){
220                                 UnCheckedExpr un_expr = Expr as UnCheckedExpr;
221                                 CheckedExpr ch_expr = Expr as CheckedExpr;
222
223                                 if ((un_expr != null) && (un_expr.Expr is Constant))
224                                         Expr = un_expr.Expr;
225                                 else if ((ch_expr != null) && (ch_expr.Expr is Constant))
226                                         Expr = ch_expr.Expr;
227                                 else if (Expr is ArrayCreation) {
228                                         ArrayCreation ac = (ArrayCreation) Expr;
229
230                                         Expr = ac.TurnIntoConstant ();
231                                         if (Expr == null){
232                                                 Report.Error (150, Location, "A constant value is expected");
233                                                 value = null;
234                                                 return false;
235                                         }
236                                 } else {
237                                         if (errors == Report.Errors)
238                                                 Report.Error (150, Location, "A constant value is expected");
239                                         value = null;
240                                         return false;
241                                 }
242                         }
243
244                         if (type != ce.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 (TypeContainer parent)
284                 {
285                         object value;
286                         LookupConstantValue (out value);
287                         base.Emit (parent);
288                 }
289         }
290 }
291
292