View Javadoc
Minimize
Table

1   /*
2    * Copyright 2003-2007 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.codehaus.groovy.ast.expr;
17  
18  import org.codehaus.groovy.ast.GroovyCodeVisitor;
19  
20  /**
21   * Represents a short ternary expression x ?: y, which is equal 
22   * to 
23   * <pre>
24   * def truePart = x
25   * def booleanPart = truePart as boolean
26   * booleanPart? truePart : y
27   * </pre>
28   * Even if x is no atomic expression, x will be evaluated only 
29   * once. Example:
30   * <pre>
31   * class Foo { 
32   *   def index=0 
33   *   def getX(){ index++; return index }
34   * }
35   * def foo = new Foo()
36   * def result = foo.x ?: "false case" 
37   * assert foo.index == 1
38   * assert result == 1 
39   * <pre>
40   * 
41   * @author <a href="mailto:blackdrag@gmx.org">Jochen Theodorou</a>
42   * @since 1.5
43   */
44  public class ElvisOperatorExpression extends TernaryExpression {
45  
46      public ElvisOperatorExpression(Expression base, Expression falseExpression) {
47          super(getBool(base), base, falseExpression);
48      }
49      
50      private static BooleanExpression getBool(Expression base) {
51         BooleanExpression be = new BooleanExpression(base);
52         be.setSourcePosition(base);
53         return be;
54      }
55  
56      public void visit(GroovyCodeVisitor visitor) {
57          visitor.visitShortTernaryExpression(this);
58      }
59      
60      public Expression transformExpression(ExpressionTransformer transformer) {
61          Expression ret = new ElvisOperatorExpression(
62                  transformer.transform(getTrueExpression()),
63                  transformer.transform(getFalseExpression()));
64          ret.setSourcePosition(this);
65          return ret; 
66      }
67  }