001: /*
002: * The contents of this file are subject to the terms
003: * of the Common Development and Distribution License
004: * (the "License"). You may not use this file except
005: * in compliance with the License.
006: *
007: * You can obtain a copy of the license at
008: * https://jwsdp.dev.java.net/CDDLv1.0.html
009: * See the License for the specific language governing
010: * permissions and limitations under the License.
011: *
012: * When distributing Covered Code, include this CDDL
013: * HEADER in each file and include the License file at
014: * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable,
015: * add the following below this CDDL HEADER, with the
016: * fields enclosed by brackets "[]" replaced with your
017: * own identifying information: Portions Copyright [yyyy]
018: * [name of copyright owner]
019: */
020:
021: package com.sun.codemodel;
022:
023: /**
024: * If statement, with optional else clause
025: */
026:
027: public class JConditional implements JStatement {
028:
029: /**
030: * JExpression to test to determine branching
031: */
032: private JExpression test = null;
033:
034: /**
035: * JBlock of statements for "then" clause
036: */
037: private JBlock _then = new JBlock();
038:
039: /**
040: * JBlock of statements for optional "else" clause
041: */
042: private JBlock _else = null;
043:
044: /**
045: * Constructor
046: *
047: * @param test
048: * JExpression which will determine branching
049: */
050: JConditional(JExpression test) {
051: this .test = test;
052: }
053:
054: /**
055: * Return the block to be excuted by the "then" branch
056: *
057: * @return Then block
058: */
059: public JBlock _then() {
060: return _then;
061: }
062:
063: /**
064: * Create a block to be executed by "else" branch
065: *
066: * @return Newly generated else block
067: */
068: public JBlock _else() {
069: if (_else == null)
070: _else = new JBlock();
071: return _else;
072: }
073:
074: /**
075: * Creates <tt>... else if(...) ...</tt> code.
076: */
077: public JConditional _elseif(JExpression boolExp) {
078: return _else()._if(boolExp);
079: }
080:
081: public void state(JFormatter f) {
082: if (test == JExpr.TRUE) {
083: _then.generateBody(f);
084: return;
085: }
086: if (test == JExpr.FALSE) {
087: _else.generateBody(f);
088: return;
089: }
090:
091: if (JOp.hasTopOp(test)) {
092: f.p("if ").g(test);
093: } else {
094: f.p("if (").g(test).p(')');
095: }
096: f.g(_then);
097: if (_else != null)
098: f.p("else").g(_else);
099: f.nl();
100: }
101: }
|