001/*
002 * Copyright 2002-2019 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.expression.spel.ast;
018
019import java.math.BigDecimal;
020import java.math.BigInteger;
021
022import org.springframework.asm.MethodVisitor;
023import org.springframework.expression.EvaluationException;
024import org.springframework.expression.Operation;
025import org.springframework.expression.TypedValue;
026import org.springframework.expression.spel.CodeFlow;
027import org.springframework.expression.spel.ExpressionState;
028import org.springframework.util.Assert;
029import org.springframework.util.NumberUtils;
030
031/**
032 * Implements the {@code multiply} operator.
033 *
034 * <p>Conversions and promotions are handled as defined in
035 * <a href="https://java.sun.com/docs/books/jls/third_edition/html/conversions.html">Section 5.6.2 of the
036 * Java Language Specification</a>, with the addiction of {@code BigDecimal}/{@code BigInteger} management:
037 *
038 * <p>If any of the operands is of a reference type, unboxing conversion (Section 5.1.8)
039 * is performed. Then:<br>
040 * If either operand is of type {@code BigDecimal}, the other is converted to {@code BigDecimal}.<br>
041 * If either operand is of type double, the other is converted to double.<br>
042 * Otherwise, if either operand is of type float, the other is converted to float.<br>
043 * If either operand is of type {@code BigInteger}, the other is converted to {@code BigInteger}.<br>
044 * Otherwise, if either operand is of type long, the other is converted to long.<br>
045 * Otherwise, both operands are converted to type int.
046 *
047 * @author Andy Clement
048 * @author Juergen Hoeller
049 * @author Sam Brannen
050 * @author Giovanni Dall'Oglio Risso
051 * @since 3.0
052 */
053public class OpMultiply extends Operator {
054
055        public OpMultiply(int startPos, int endPos, SpelNodeImpl... operands) {
056                super("*", startPos, endPos, operands);
057        }
058
059
060        /**
061         * Implements the {@code multiply} operator directly here for certain types
062         * of supported operands and otherwise delegates to any registered overloader
063         * for types not supported here.
064         * <p>Supported operand types:
065         * <ul>
066         * <li>numbers
067         * <li>String and int ('abc' * 2 == 'abcabc')
068         * </ul>
069         */
070        @Override
071        public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
072                Object leftOperand = getLeftOperand().getValueInternal(state).getValue();
073                Object rightOperand = getRightOperand().getValueInternal(state).getValue();
074
075                if (leftOperand instanceof Number && rightOperand instanceof Number) {
076                        Number leftNumber = (Number) leftOperand;
077                        Number rightNumber = (Number) rightOperand;
078
079                        if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) {
080                                BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
081                                BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class);
082                                return new TypedValue(leftBigDecimal.multiply(rightBigDecimal));
083                        }
084                        else if (leftNumber instanceof Double || rightNumber instanceof Double) {
085                                this.exitTypeDescriptor = "D";
086                                return new TypedValue(leftNumber.doubleValue() * rightNumber.doubleValue());
087                        }
088                        else if (leftNumber instanceof Float || rightNumber instanceof Float) {
089                                this.exitTypeDescriptor = "F";
090                                return new TypedValue(leftNumber.floatValue() * rightNumber.floatValue());
091                        }
092                        else if (leftNumber instanceof BigInteger || rightNumber instanceof BigInteger) {
093                                BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class);
094                                BigInteger rightBigInteger = NumberUtils.convertNumberToTargetClass(rightNumber, BigInteger.class);
095                                return new TypedValue(leftBigInteger.multiply(rightBigInteger));
096                        }
097                        else if (leftNumber instanceof Long || rightNumber instanceof Long) {
098                                this.exitTypeDescriptor = "J";
099                                return new TypedValue(leftNumber.longValue() * rightNumber.longValue());
100                        }
101                        else if (CodeFlow.isIntegerForNumericOp(leftNumber) || CodeFlow.isIntegerForNumericOp(rightNumber)) {
102                                this.exitTypeDescriptor = "I";
103                                return new TypedValue(leftNumber.intValue() * rightNumber.intValue());
104                        }
105                        else {
106                                // Unknown Number subtypes -> best guess is double multiplication
107                                return new TypedValue(leftNumber.doubleValue() * rightNumber.doubleValue());
108                        }
109                }
110
111                if (leftOperand instanceof String && rightOperand instanceof Integer) {
112                        int repeats = (Integer) rightOperand;
113                        StringBuilder result = new StringBuilder();
114                        for (int i = 0; i < repeats; i++) {
115                                result.append(leftOperand);
116                        }
117                        return new TypedValue(result.toString());
118                }
119
120                return state.operate(Operation.MULTIPLY, leftOperand, rightOperand);
121        }
122
123        @Override
124        public boolean isCompilable() {
125                if (!getLeftOperand().isCompilable()) {
126                        return false;
127                }
128                if (this.children.length > 1) {
129                        if (!getRightOperand().isCompilable()) {
130                                return false;
131                        }
132                }
133                return (this.exitTypeDescriptor != null);
134        }
135
136        @Override
137        public void generateCode(MethodVisitor mv, CodeFlow cf) {
138                getLeftOperand().generateCode(mv, cf);
139                String leftDesc = getLeftOperand().exitTypeDescriptor;
140                String exitDesc = this.exitTypeDescriptor;
141                Assert.state(exitDesc != null, "No exit type descriptor");
142                char targetDesc = exitDesc.charAt(0);
143                CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, leftDesc, targetDesc);
144                if (this.children.length > 1) {
145                        cf.enterCompilationScope();
146                        getRightOperand().generateCode(mv, cf);
147                        String rightDesc = getRightOperand().exitTypeDescriptor;
148                        cf.exitCompilationScope();
149                        CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc);
150                        switch (targetDesc) {
151                                case 'I':
152                                        mv.visitInsn(IMUL);
153                                        break;
154                                case 'J':
155                                        mv.visitInsn(LMUL);
156                                        break;
157                                case 'F':
158                                        mv.visitInsn(FMUL);
159                                        break;
160                                case 'D':
161                                        mv.visitInsn(DMUL);
162                                        break;
163                                default:
164                                        throw new IllegalStateException(
165                                                        "Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
166                        }
167                }
168                cf.pushDescriptor(this.exitTypeDescriptor);
169        }
170
171}