1/*
2 * Javassist, a Java-bytecode translator toolkit.
3 * Copyright (C) 1999-2007 Shigeru Chiba. All Rights Reserved.
4 *
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License.  Alternatively, the contents of this file may be used under
8 * the terms of the GNU Lesser General Public License Version 2.1 or later.
9 *
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
13 * License.
14 */
15
16package javassist.compiler.ast;
17
18import javassist.compiler.CompileError;
19import javassist.compiler.TokenId;
20
21/**
22 * Double constant.
23 */
24public class DoubleConst extends ASTree {
25    protected double value;
26    protected int type;
27
28    public DoubleConst(double v, int tokenId) { value = v; type = tokenId; }
29
30    public double get() { return value; }
31
32    public void set(double v) { value = v; }
33
34    /* Returns DoubleConstant or FloatConstant
35     */
36    public int getType() { return type; }
37
38    public String toString() { return Double.toString(value); }
39
40    public void accept(Visitor v) throws CompileError {
41        v.atDoubleConst(this);
42    }
43
44    public ASTree compute(int op, ASTree right) {
45        if (right instanceof IntConst)
46            return compute0(op, (IntConst)right);
47        else if (right instanceof DoubleConst)
48            return compute0(op, (DoubleConst)right);
49        else
50            return null;
51    }
52
53    private DoubleConst compute0(int op, DoubleConst right) {
54        int newType;
55        if (this.type == TokenId.DoubleConstant
56            || right.type == TokenId.DoubleConstant)
57            newType = TokenId.DoubleConstant;
58        else
59            newType = TokenId.FloatConstant;
60
61        return compute(op, this.value, right.value, newType);
62    }
63
64    private DoubleConst compute0(int op, IntConst right) {
65        return compute(op, this.value, (double)right.value, this.type);
66    }
67
68    private static DoubleConst compute(int op, double value1, double value2,
69                                       int newType)
70    {
71        double newValue;
72        switch (op) {
73        case '+' :
74            newValue = value1 + value2;
75            break;
76        case '-' :
77            newValue = value1 - value2;
78            break;
79        case '*' :
80            newValue = value1 * value2;
81            break;
82        case '/' :
83            newValue = value1 / value2;
84            break;
85        case '%' :
86            newValue = value1 % value2;
87            break;
88        default :
89            return null;
90        }
91
92        return new DoubleConst(newValue, newType);
93    }
94}
95