SwitchNode.java revision 1068:34ef988d5959
1/*
2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package jdk.nashorn.internal.ir;
27
28import java.util.ArrayList;
29import java.util.Collections;
30import java.util.List;
31import jdk.nashorn.internal.codegen.Label;
32import jdk.nashorn.internal.ir.annotations.Immutable;
33import jdk.nashorn.internal.ir.visitor.NodeVisitor;
34
35/**
36 * IR representation of a SWITCH statement.
37 */
38@Immutable
39public final class SwitchNode extends BreakableStatement {
40    private static final long serialVersionUID = 1L;
41
42    /** Switch expression. */
43    private final Expression expression;
44
45    /** Switch cases. */
46    private final List<CaseNode> cases;
47
48    /** Switch default index. */
49    private final int defaultCaseIndex;
50
51    /** Tag symbol. */
52    private Symbol tag;
53
54    /**
55     * Constructor
56     *
57     * @param lineNumber  lineNumber
58     * @param token       token
59     * @param finish      finish
60     * @param expression  switch expression
61     * @param cases       cases
62     * @param defaultCase the default case node - null if none, otherwise has to be present in cases list
63     */
64    public SwitchNode(final int lineNumber, final long token, final int finish, final Expression expression, final List<CaseNode> cases, final CaseNode defaultCase) {
65        super(lineNumber, token, finish, new Label("switch_break"));
66        this.expression       = expression;
67        this.cases            = cases;
68        this.defaultCaseIndex = defaultCase == null ? -1 : cases.indexOf(defaultCase);
69    }
70
71    private SwitchNode(final SwitchNode switchNode, final Expression expression, final List<CaseNode> cases,
72            final int defaultCaseIndex, final LocalVariableConversion conversion) {
73        super(switchNode, conversion);
74        this.expression       = expression;
75        this.cases            = cases;
76        this.defaultCaseIndex = defaultCaseIndex;
77        this.tag              = switchNode.getTag(); //TODO are symbols inhereted as references?
78    }
79
80    @Override
81    public Node ensureUniqueLabels(final LexicalContext lc) {
82        final List<CaseNode> newCases = new ArrayList<>();
83        for (final CaseNode caseNode : cases) {
84            newCases.add(new CaseNode(caseNode, caseNode.getTest(), caseNode.getBody(), caseNode.getLocalVariableConversion()));
85        }
86        return Node.replaceInLexicalContext(lc, this, new SwitchNode(this, expression, newCases, defaultCaseIndex, conversion));
87    }
88
89    @Override
90    public boolean isTerminal() {
91        //there must be a default case, and that including all other cases must terminate
92        if (!cases.isEmpty() && defaultCaseIndex != -1) {
93            for (final CaseNode caseNode : cases) {
94                if (!caseNode.isTerminal()) {
95                    return false;
96                }
97            }
98            return true;
99        }
100        return false;
101
102    }
103
104    @Override
105    public Node accept(final LexicalContext lc, final NodeVisitor<? extends LexicalContext> visitor) {
106        if (visitor.enterSwitchNode(this)) {
107            return visitor.leaveSwitchNode(
108                setExpression(lc, (Expression)expression.accept(visitor)).
109                setCases(lc, Node.accept(visitor, cases), defaultCaseIndex));
110        }
111
112        return this;
113    }
114
115    @Override
116    public void toString(final StringBuilder sb, final boolean printType) {
117        sb.append("switch (");
118        expression.toString(sb, printType);
119        sb.append(')');
120    }
121
122    /**
123     * Return the case node that is default case
124     * @return default case or null if none
125     */
126    public CaseNode getDefaultCase() {
127        return defaultCaseIndex == -1 ? null : cases.get(defaultCaseIndex);
128    }
129
130    /**
131     * Get the cases in this switch
132     * @return a list of case nodes
133     */
134    public List<CaseNode> getCases() {
135        return Collections.unmodifiableList(cases);
136    }
137
138    /**
139     * Replace case nodes with new list. the cases have to be the same
140     * and the default case index the same. This is typically used
141     * by NodeVisitors who perform operations on every case node
142     * @param lc    lexical context
143     * @param cases list of cases
144     * @return new switch node or same if no state was changed
145     */
146    public SwitchNode setCases(final LexicalContext lc, final List<CaseNode> cases) {
147        return setCases(lc, cases, defaultCaseIndex);
148    }
149
150    private SwitchNode setCases(final LexicalContext lc, final List<CaseNode> cases, final int defaultCaseIndex) {
151        if (this.cases == cases) {
152            return this;
153        }
154        return Node.replaceInLexicalContext(lc, this, new SwitchNode(this, expression, cases, defaultCaseIndex, conversion));
155    }
156
157    /**
158     * Set or reset the list of cases in this switch
159     * @param lc lexical context
160     * @param cases a list of cases, case nodes
161     * @param defaultCase a case in the list that is the default - must be in the list or class will assert
162     * @return new switch node or same if no state was changed
163     */
164    public SwitchNode setCases(final LexicalContext lc, final List<CaseNode> cases, final CaseNode defaultCase) {
165        return setCases(lc, cases, defaultCase == null ? -1 : cases.indexOf(defaultCase));
166    }
167
168    /**
169     * Return the expression to switch on
170     * @return switch expression
171     */
172    public Expression getExpression() {
173        return expression;
174    }
175
176    /**
177     * Set or reset the expression to switch on
178     * @param lc lexical context
179     * @param expression switch expression
180     * @return new switch node or same if no state was changed
181     */
182    public SwitchNode setExpression(final LexicalContext lc, final Expression expression) {
183        if (this.expression == expression) {
184            return this;
185        }
186        return Node.replaceInLexicalContext(lc, this, new SwitchNode(this, expression, cases, defaultCaseIndex, conversion));
187    }
188
189    /**
190     * Get the tag symbol for this switch. The tag symbol is where
191     * the switch expression result is stored
192     * @return tag symbol
193     */
194    public Symbol getTag() {
195        return tag;
196    }
197
198    /**
199     * Set the tag symbol for this switch. The tag symbol is where
200     * the switch expression result is stored
201     * @param tag a symbol
202     */
203    public void setTag(final Symbol tag) {
204        this.tag = tag;
205    }
206
207    /**
208     * Returns true if all cases of this switch statement are 32-bit signed integer constants.
209     * @return true if all cases of this switch statement are 32-bit signed integer constants.
210     */
211    public boolean isInteger() {
212        for (final CaseNode caseNode : cases) {
213            final Expression test = caseNode.getTest();
214            if (test != null && !isIntegerLiteral(test)) {
215                return false;
216            }
217        }
218        return true;
219    }
220
221    @Override
222    JoinPredecessor setLocalVariableConversionChanged(final LexicalContext lc, final LocalVariableConversion conversion) {
223        return Node.replaceInLexicalContext(lc, this, new SwitchNode(this, expression, cases, defaultCaseIndex, conversion));
224    }
225
226    private static boolean isIntegerLiteral(final Expression expr) {
227        return expr instanceof LiteralNode && ((LiteralNode<?>)expr).getValue() instanceof Integer;
228    }
229}
230