2 // constant.cs: Constant expressions and constant folding.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
11 namespace Mono.CSharp {
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Collections;
19 public class Constant : Expression {
21 public readonly string Name;
22 public Expression Expr;
23 public readonly string ConstantType;
24 public Attributes OptAttributes;
29 FieldBuilder FieldBuilder;
31 public const int AllowedModifiers =
38 public Constant (string constant_type, string name, Expression expr, int mod_flags,
39 Attributes attrs, Location loc)
41 this.ConstantType = constant_type;
44 this.mod_flags = Modifiers.Check (AllowedModifiers, mod_flags, Modifiers.PRIVATE);
46 OptAttributes = attrs;
49 public FieldAttributes FieldAttr {
51 return FieldAttributes.Literal | FieldAttributes.Static |
52 Modifiers.FieldAttr (mod_flags) ;
62 public override Expression DoResolve (EmitContext ec)
68 public override void Emit (EmitContext ec)
70 throw new Exception ("Unimplemented");
74 /// Defines the constant in the @parent
76 public void Define (TypeContainer parent)
78 type = parent.LookupType (ConstantType, true);
83 if (!TypeManager.IsBuiltinType (type) && (!type.IsSubclassOf (TypeManager.enum_type))) {
84 Report.Error (-3, "Constant type is not valid (only system types are allowed)");
88 FieldBuilder = parent.TypeBuilder.DefineField (Name, type, FieldAttr);
93 /// Emits the field value by evaluating the expression
95 public void EmitConstant (TypeContainer parent)
97 if (FieldBuilder == null)
100 EmitContext ec = new EmitContext (parent, null, type, ModFlags);
102 Expr = Expression.Reduce (ec, Expr);
104 if (!(Expr is Literal)) {
105 Report.Error (150, Location, "A constant value is expected");
109 object val = ((Literal) Expr).GetValue ();
111 FieldBuilder.SetConstant (val);
113 TypeManager.RegisterField (FieldBuilder, val);