Milestone-Patch #80.
[mono.git] / mcs / gmcs / 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 (DeclSpace 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.PartialContainer.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.PartialContainer.RegisterFieldForInitialization (this);
77                         } else {
78                                 field_attr |= FieldAttributes.Literal;
79                         }
80
81                         FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType, field_attr);
82
83                         TypeManager.RegisterConstant (FieldBuilder, this);
84
85                         return true;
86                 }
87                 
88                 /// <summary>
89                 ///  Emits the field value by evaluating the expression
90                 /// </summary>
91                 public override void Emit ()
92                 {
93                         if (!ResolveValue ())
94                                 return;
95
96                         if (value.Type == TypeManager.decimal_type) {
97                                 Decimal d = ((DecimalConstant)value).Value;
98                                 int[] bits = Decimal.GetBits (d);
99                                 object[] args = new object[] { (byte)(bits [3] >> 16), (byte)(bits [3] >> 31), (uint)bits [2], (uint)bits [1], (uint)bits [0] };
100                                 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.decimal_constant_attribute_ctor, args);
101                                 FieldBuilder.SetCustomAttribute (cab);
102                         }
103                         else{
104                                 FieldBuilder.SetConstant (value.GetTypedValue ());
105                         }
106
107                         base.Emit ();
108                 }
109
110                 public static void Error_ExpressionMustBeConstant (Type constantType, Location loc, string e_name)
111                 {
112                         if (constantType != null && TypeManager.IsValueType (constantType) &&
113                                 !TypeManager.IsBuiltinOrEnum (constantType)) {
114                                 Report.Error (283, loc, "The type `{0}' cannot be declared const", TypeManager.CSharpName (constantType));
115                                 return;
116                         }
117                         Report.Error (133, loc, "The expression being assigned to `{0}' must be constant", e_name);
118                 }
119
120                 public static void Error_CyclicDeclaration (MemberCore mc)
121                 {
122                         Report.Error (110, mc.Location, "The evaluation of the constant value for `{0}' involves a circular definition",
123                                 mc.GetSignatureForError ());
124                 }
125
126                 public static void Error_ConstantCanBeInitializedWithNullOnly (Location loc, string name)
127                 {
128                         Report.Error (134, loc, "`{0}': the constant of reference type other than string can only be initialized with null",
129                                 name);
130                 }
131
132                 #region IConstant Members
133
134                 public bool ResolveValue ()
135                 {
136                         if (value != null)
137                                 return true;
138
139                         SetMemberIsUsed ();
140                         if (in_transit) {
141                                 Error_CyclicDeclaration (this);
142                                 // Suppress cyclic errors
143                                 value = New.Constantify (MemberType);
144                                 return false;
145                         }
146
147                         in_transit = true;
148                         // TODO: IResolveContext here
149                         EmitContext ec = new EmitContext (this, Parent, Location, null, MemberType, ModFlags);
150                         value = initializer.ResolveAsConstant (ec, this);
151                         in_transit = false;
152
153                         if (value == null)
154                                 return false;
155
156                         value = value.ToType (MemberType, Location);
157                         if (value == null)
158                                 return false;
159
160                         if (!MemberType.IsValueType && MemberType != TypeManager.string_type && !value.IsDefaultValue) {
161                                 Error_ConstantCanBeInitializedWithNullOnly (Location, GetSignatureForError ());
162                                 return false;
163                         }
164
165                         return true;
166                 }
167
168                 public Constant Value {
169                         get {
170                                 return value;
171                         }
172                 }
173
174                 #endregion
175         }
176
177         public class ExternalConstant : IConstant
178         {
179                 FieldInfo fi;
180                 Constant value;
181
182                 public ExternalConstant (FieldInfo fi)
183                 {
184                         this.fi = fi;
185                 }
186
187                 private ExternalConstant (FieldInfo fi, Constant value):
188                         this (fi)
189                 {
190                         this.value = value;
191                 }
192
193                 //
194                 // Decimal constants cannot be encoded in the constant blob, and thus are marked
195                 // as IsInitOnly ('readonly' in C# parlance).  We get its value from the 
196                 // DecimalConstantAttribute metadata.
197                 //
198                 public static IConstant CreateDecimal (FieldInfo fi)
199                 {
200                         if (fi is FieldBuilder)
201                                 return null;
202                         
203                         object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
204                         if (attrs.Length != 1)
205                                 return null;
206
207                         IConstant ic = new ExternalConstant (fi,
208                                 new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value, Location.Null));
209
210                         return ic;
211                 }
212
213                 #region IConstant Members
214
215                 public void CheckObsoleteness (Location loc)
216                 {
217                         ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
218                         if (oa == null) {
219                                 return;
220                         }
221
222                         AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), loc);
223                 }
224
225                 public bool ResolveValue ()
226                 {
227                         if (value != null)
228                                 return true;
229
230                         if (fi.DeclaringType.IsEnum) {
231                                 value = Expression.Constantify (fi.GetValue (fi), TypeManager.EnumToUnderlying (fi.FieldType));
232                                 value = new EnumConstant (value, fi.DeclaringType);
233                                 return true;
234                         }
235
236                         value = Expression.Constantify (fi.GetValue (fi), fi.FieldType);
237                         return true;
238                 }
239
240                 public Constant Value {
241                         get {
242                                 return value;
243                         }
244                 }
245
246                 #endregion
247         }
248
249 }