Java Code Examples for org.codehaus.groovy.ast.expr.BinaryExpression#getRightExpression()

The following examples show how to use org.codehaus.groovy.ast.expr.BinaryExpression#getRightExpression() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypeInferenceVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBinaryExpression(BinaryExpression expression) {
    if (!leafReached) {
        // have a look at assignment and try to get type from its right side
        Expression leftExpression = expression.getLeftExpression();
        if (leftExpression instanceof VariableExpression) {
            if (expression.getOperation().isA(Types.EQUAL) && sameVariableName(leaf, leftExpression)) {
                Expression rightExpression = expression.getRightExpression();
                if (rightExpression instanceof ConstantExpression
                        && !rightExpression.getText().equals("null")) { // NOI18N
                    guessedType = ((ConstantExpression) rightExpression).getType();
                } else if (rightExpression instanceof ConstructorCallExpression) {
                    guessedType = ClassHelper.make(((ConstructorCallExpression) rightExpression).getType().getName());
                } else if (rightExpression instanceof MethodCallExpression) {
                    guessedType = MethodInference.findCallerType(rightExpression, path, doc, cursorOffset);
                } else if (rightExpression instanceof StaticMethodCallExpression) {
                    guessedType = MethodInference.findCallerType(rightExpression, path, doc, cursorOffset);
                }
            }
        }
    }
    super.visitBinaryExpression(expression);
}
 
Example 2
Source File: BinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected boolean doPrimitiveCompare(final ClassNode leftType, final ClassNode rightType, final BinaryExpression binExp) {
    Expression leftExp = binExp.getLeftExpression();
    Expression rightExp = binExp.getRightExpression();
    int operation = binExp.getOperation().getType();

    int operationType = getOperandConversionType(leftType,rightType);
    BinaryExpressionWriter bew = binExpWriter[operationType];

    if (!bew.write(operation, true)) return false;

    AsmClassGenerator acg = controller.getAcg();
    OperandStack os = controller.getOperandStack();
    leftExp.visit(acg);
    os.doGroovyCast(bew.getNormalOpResultType());
    rightExp.visit(acg);
    os.doGroovyCast(bew.getNormalOpResultType());
    bew.write(operation, false);

    return true;
}
 
Example 3
Source File: FinalVariableAnalyzer.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBinaryExpression(final BinaryExpression expression) {
    boolean assignment = StaticTypeCheckingSupport.isAssignment(expression.getOperation().getType());
    boolean isDeclaration = expression instanceof DeclarationExpression;
    Expression leftExpression = expression.getLeftExpression();
    Expression rightExpression = expression.getRightExpression();
    if (isDeclaration) {
        recordFinalVars(leftExpression);
    }
    // visit RHS first for expressions like a = b = 0
    inAssignmentRHS = assignment;
    rightExpression.visit(this);
    inAssignmentRHS = false;
    leftExpression.visit(this);
    if (assignment) {
        recordAssignments(expression, isDeclaration, leftExpression, rightExpression);
    }
}
 
Example 4
Source File: NAryOperationRewriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Expression transformBinaryExpression(final BinaryExpression exp) {
    final int op = exp.getOperation().getType();
    int token = TokenUtil.removeAssignment(op);
    if (token == op) {
        // no transform needed
        return super.transform(exp);
    }
    BinaryExpression operation = new BinaryExpression(
            exp.getLeftExpression(),
            Token.newSymbol(token, -1, -1),
            exp.getRightExpression()
    );
    operation.setSourcePosition(exp);
    BinaryExpression result = new BinaryExpression(
            exp.getLeftExpression(),
            Token.newSymbol(EQUAL, -1, -1),
            operation
    );
    result.setSourcePosition(exp);
    return result;
}
 
Example 5
Source File: BinaryExpressionTransformer.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static Expression transformDeclarationExpression(final BinaryExpression bin) {
    Expression leftExpression = bin.getLeftExpression();
    if (leftExpression instanceof VariableExpression) {
        if (ClassHelper.char_TYPE.equals(((VariableExpression) leftExpression).getOriginType())) {
            Expression rightExpression = bin.getRightExpression();
            Character c = tryCharConstant(rightExpression);
            if (c != null) {
                Expression ce = constX(c, true);
                ce.setSourcePosition(rightExpression);
                bin.setRightExpression(ce);
                return bin;
            }
        }
    }
    return null;
}
 
Example 6
Source File: InstanceOfVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBinaryExpression(BinaryExpression expression) {
    if (expression.getOperation().isA(Types.INSTANCEOF_OPERATOR) &&
            expression.getRightExpression() instanceof ClassExpression) {
        ClassNode referenceType = expression.getRightExpression().getType();

        if (ClassHelper.isPrimitiveType(referenceType)) {
            addTypeError(expression.getRightExpression(), "primitive type " + referenceType.getName());
        } else {
            while (referenceType.isArray()) {
                referenceType = referenceType.getComponentType();
            }

            if (referenceType.isGenericsPlaceHolder()) {
                addTypeError(expression.getRightExpression(), "type parameter " + referenceType.getUnresolvedName() +
                    ". Use its erasure " + referenceType.getNameWithoutPackage() + " instead since further generic type information will be erased at runtime");
            } else if (referenceType.getGenericsTypes() != null) {
                // TODO: Cannot perform instanceof check against parameterized type Class<Type>. Use the form Class<?> instead since further eneric type information will be erased at runtime
            }
        }
    }
    super.visitBinaryExpression(expression);
}
 
Example 7
Source File: SqlWhereVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void visitBinaryExpression(BinaryExpression expression) {
    Expression left = expression.getLeftExpression();
    Expression right = expression.getRightExpression();
    boolean leaf = (right instanceof ConstantExpression || left instanceof ConstantExpression);

    if (!leaf) buffer.append("(");
    left.visit(this);
    buffer.append(" ");

    Token token = expression.getOperation();
    buffer.append(tokenAsSql(token));

    buffer.append(" ");
    right.visit(this);
    if (!leaf) buffer.append(")");
}
 
Example 8
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void visitBinaryExpression(BinaryExpression expression) {
    if (expression.getOperation().getType() == Types.LEFT_SQUARE_BRACKET &&
            expression.getRightExpression() instanceof MapEntryExpression) {
        addError("You tried to use a map entry for an index operation, this is not allowed. " +
                "Maybe something should be set in parentheses or a comma is missing?",
                expression.getRightExpression());
    }
    super.visitBinaryExpression(expression);

    if (Types.isAssignment(expression.getOperation().getType())) {
        checkFinalFieldAccess(expression.getLeftExpression());
        checkSuperOrThisOnLHS(expression.getLeftExpression());
    }
}
 
Example 9
Source File: GroovyClassFilterTransformer.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Expression transformBinaryExpression(String checkedOperation, BinaryExpression be)
{
	Expression leftExpression = be.getLeftExpression();
	Expression rightExpression = be.getRightExpression();
	if (allowed(leftExpression.getType()) && allowed(rightExpression.getType()))
	{
		Expression transformedLeft = transform(leftExpression);
		Expression transformedRight = transform(rightExpression);
		if (transformedLeft.equals(leftExpression) 
				&& transformedRight.equals(rightExpression))
		{
			if (log.isDebugEnabled())
			{
				log.debug("allowed binary expression " + be);
			}
			return be;
		}
		
		BinaryExpression transformedExpression = new BinaryExpression(
				transformedLeft, be.getOperation(), transformedRight);
		if (log.isDebugEnabled())
		{
			log.debug("transformed binary expression " + transformedExpression);
		}
		return transformedExpression;
	}
	
	return super.transformBinaryExpression(checkedOperation, be);
}
 
Example 10
Source File: BinaryExpressionHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void evaluateCompareExpression(final MethodCaller compareMethod, final BinaryExpression expression) {
    ClassNode classNode = controller.getClassNode();
    Expression leftExp = expression.getLeftExpression();
    Expression rightExp = expression.getRightExpression();
    ClassNode leftType = controller.getTypeChooser().resolveType(leftExp, classNode);
    ClassNode rightType = controller.getTypeChooser().resolveType(rightExp, classNode);

    boolean done = false;
    if (ClassHelper.isPrimitiveType(leftType) && ClassHelper.isPrimitiveType(rightType)) {
        BinaryExpressionMultiTypeDispatcher helper = new BinaryExpressionMultiTypeDispatcher(controller);
        done = helper.doPrimitiveCompare(leftType, rightType, expression);
    }
    if (!done) {
        AsmClassGenerator acg = controller.getAcg();
        OperandStack operandStack = controller.getOperandStack();

        leftExp.visit(acg);
        operandStack.box();
        rightExp.visit(acg);
        operandStack.box();

        compareMethod.call(controller.getMethodVisitor());
        ClassNode resType = ClassHelper.boolean_TYPE;
        if (compareMethod == findRegexMethod) {
            resType = ClassHelper.OBJECT_TYPE;
        }
        operandStack.replace(resType, 2);
    }
}
 
Example 11
Source File: BinaryExpressionHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void evaluateArrayAssignmentWithOperator(final String method, final BinaryExpression expression, final BinaryExpression leftBinExpr) {
    // e.g. x[a] += b
    // to avoid loading x and a twice we transform the expression to use
    // ExpressionAsVariableSlot
    // -> subscript=a, receiver=x, receiver[subscript]+b, =, receiver[subscript]
    // -> subscript=a, receiver=x, receiver#getAt(subscript)#plus(b), =, receiver#putAt(subscript)
    // -> subscript=a, receiver=x, receiver#putAt(subscript, receiver#getAt(subscript)#plus(b))
    // the result of x[a] += b is x[a]+b, thus:
    // -> subscript=a, receiver=x, receiver#putAt(subscript, ret=receiver#getAt(subscript)#plus(b)), ret
    ExpressionAsVariableSlot subscript = new ExpressionAsVariableSlot(controller, leftBinExpr.getRightExpression(), "subscript");
    ExpressionAsVariableSlot receiver  = new ExpressionAsVariableSlot(controller, leftBinExpr.getLeftExpression(), "receiver");
    MethodCallExpression getAt = callX(receiver, "getAt", args(subscript));
    MethodCallExpression operation = callX(getAt, method, expression.getRightExpression());
    ExpressionAsVariableSlot ret = new ExpressionAsVariableSlot(controller, operation, "ret");
    MethodCallExpression putAt = callX(receiver, "putAt", args(subscript, ret));

    AsmClassGenerator acg = controller.getAcg();
    putAt.visit(acg);
    OperandStack os = controller.getOperandStack();
    os.pop();
    os.load(ret.getType(), ret.getIndex());

    CompileStack compileStack = controller.getCompileStack();
    compileStack.removeVar(ret.getIndex());
    compileStack.removeVar(subscript.getIndex());
    compileStack.removeVar(receiver.getIndex());
}
 
Example 12
Source File: BinaryExpressionHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void evaluateInstanceof(final BinaryExpression expression) {
    expression.getLeftExpression().visit(controller.getAcg());
    controller.getOperandStack().box();
    Expression rightExp = expression.getRightExpression();
    if (!(rightExp instanceof ClassExpression)) {
        throw new RuntimeException("RHS of the instanceof keyword must be a class name, not: " + rightExp);
    }
    String classInternalName = BytecodeHelper.getClassInternalName(rightExp.getType());
    controller.getMethodVisitor().visitTypeInsn(INSTANCEOF, classInternalName);
    controller.getOperandStack().replace(ClassHelper.boolean_TYPE);
}
 
Example 13
Source File: BinaryExpressionHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
private VariableSlotLoader loadWithSubscript(final Expression expression) {
    AsmClassGenerator acg = controller.getAcg();
    // if we have a BinaryExpression, check if it is with subscription
    if (expression instanceof BinaryExpression) {
        BinaryExpression bexp = (BinaryExpression) expression;
        if (bexp.getOperation().getType() == LEFT_SQUARE_BRACKET) {
            // right expression is the subscript expression
            // we store the result of the subscription on the stack
            Expression subscript = bexp.getRightExpression();
            subscript.visit(acg);
            OperandStack operandStack = controller.getOperandStack();
            ClassNode subscriptType = operandStack.getTopOperand();
            if (subscriptType.isGenericsPlaceHolder() || GenericsUtils.hasPlaceHolders(subscriptType)) {
                subscriptType = controller.getTypeChooser().resolveType(bexp, controller.getClassNode());
            }
            int id = controller.getCompileStack().defineTemporaryVariable("$subscript", subscriptType, true);
            VariableSlotLoader subscriptExpression = new VariableSlotLoader(subscriptType, id, operandStack);
            BinaryExpression rewrite = binX(bexp.getLeftExpression(), bexp.getOperation(), subscriptExpression);
            rewrite.copyNodeMetaData(bexp);
            rewrite.setSourcePosition(bexp);
            rewrite.visit(acg);
            return subscriptExpression;
        }
    }

    // normal loading of expression
    expression.visit(acg);
    return null;
}
 
Example 14
Source File: StaticTypesBinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void evaluateEqual(final BinaryExpression expression, final boolean defineVariable) {
    Expression leftExpression = expression.getLeftExpression();
    if (!defineVariable) {
        if (leftExpression instanceof PropertyExpression) {
            PropertyExpression pexp = (PropertyExpression) leftExpression;
            if (makeSetProperty(
                    pexp.getObjectExpression(),
                    pexp.getProperty(),
                    expression.getRightExpression(),
                    pexp.isSafe(),
                    pexp.isSpreadSafe(),
                    pexp.isImplicitThis(),
                    pexp instanceof AttributeExpression)) {
                return;
            }
        }
    } else {
        Expression rightExpression = expression.getRightExpression();
        if (rightExpression instanceof LambdaExpression || rightExpression instanceof MethodReferenceExpression) {
            rightExpression.putNodeMetaData(INFERRED_FUNCTIONAL_INTERFACE_TYPE, leftExpression.getNodeMetaData(INFERRED_TYPE));
        }
    }
    // GROOVY-5620: spread-safe operator on LHS is not supported
    if (leftExpression instanceof PropertyExpression
            && ((PropertyExpression) leftExpression).isSpreadSafe()
            && StaticTypeCheckingSupport.isAssignment(expression.getOperation().getType())) {
        // rewrite it so that it can be statically compiled
        transformSpreadOnLHS(expression);
        return;
    }
    super.evaluateEqual(expression, defineVariable);
}
 
Example 15
Source File: GroovyGradleParser.java    From size-analyzer with Apache License 2.0 5 votes vote down vote up
/** Handles a groovy BinaryExpression such as foo = true, or bar.baz.foo = true. */
@Override
public void visitBinaryExpression(BinaryExpression binaryExpression) {
  if (!methodCallStack.isEmpty()) {
    MethodCallExpression call = Iterables.getLast(methodCallStack);
    String parent = call.getMethodAsString();
    String parentParent = getParentParent();
    Expression leftExpression = binaryExpression.getLeftExpression();
    Expression rightExpression = binaryExpression.getRightExpression();
    if (rightExpression instanceof ConstantExpression
        && (leftExpression instanceof PropertyExpression
            || leftExpression instanceof VariableExpression)) {
      String value = rightExpression.getText();
      String property = "";
      if (leftExpression instanceof PropertyExpression) {
        Expression leftPropertyExpression = ((PropertyExpression) leftExpression).getProperty();
        if (!(leftPropertyExpression instanceof ConstantExpression)) {
          return;
        }
        property = ((ConstantExpression) leftPropertyExpression).getText();
        Expression leftObjectExpression =
            ((PropertyExpression) leftExpression).getObjectExpression();
        parentParent = parent;
        parent = getValidParentString(leftObjectExpression);
        if (leftObjectExpression instanceof PropertyExpression) {
          parentParent =
              getValidParentString(
                  ((PropertyExpression) leftObjectExpression).getObjectExpression());
        }
      } else {
        property = ((VariableExpression) leftExpression).getName();
      }
      checkDslPropertyAssignment(
          property, value, parent, parentParent, binaryExpression.getLineNumber());
    }
  }
  super.visitBinaryExpression(binaryExpression);
}
 
Example 16
Source File: BinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected void evaluateCompareExpression(final MethodCaller compareMethod, final BinaryExpression binExp) {
    ClassNode current =  controller.getClassNode();
    TypeChooser typeChooser = controller.getTypeChooser();

    Expression leftExp = binExp.getLeftExpression();
    ClassNode leftType = typeChooser.resolveType(leftExp, current);
    Expression rightExp = binExp.getRightExpression();
    ClassNode rightType = typeChooser.resolveType(rightExp, current);

    if (!doPrimitiveCompare(leftType, rightType, binExp)) {
        super.evaluateCompareExpression(compareMethod, binExp);
    }
}
 
Example 17
Source File: BinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 4 votes vote down vote up
private boolean doAssignmentToArray(final BinaryExpression binExp) {
    if (!isAssignmentToArray(binExp)) return false;
    // we need to handle only assignment to arrays combined with an operation
    // special here. e.g x[a] += b

    int operation = removeAssignment(binExp.getOperation().getType());
    ClassNode current =  controller.getClassNode();

    Expression leftExp = binExp.getLeftExpression();
    ClassNode leftType = controller.getTypeChooser().resolveType(leftExp, current);
    Expression rightExp = binExp.getRightExpression();
    ClassNode rightType = controller.getTypeChooser().resolveType(rightExp, current);

    int operationType = getOperandType(leftType);
    BinaryExpressionWriter bew = binExpWriter[operationType];

    boolean simulationSuccess = bew.arrayGet(LEFT_SQUARE_BRACKET, true);
    simulationSuccess = simulationSuccess && bew.write(operation, true);
    simulationSuccess = simulationSuccess && bew.arraySet(true);
    if (!simulationSuccess) return false;

    AsmClassGenerator acg = controller.getAcg();
    OperandStack operandStack = controller.getOperandStack();
    CompileStack compileStack = controller.getCompileStack();

    // for x[a] += b we have the structure:
    //   x = left(left(binExp))), b = right(binExp), a = right(left(binExp)))
    // for array set we need these values on stack: array, index, right
    // for array get we need these values on stack: array, index
    // to eval the expression we need x[a] = x[a]+b
    // -> arraySet(x,a, x[a]+b)
    // -> arraySet(x,a, arrayGet(x,a,b))
    // --> x,a, x,a, b as operands
    // --> load x, load a, DUP2, call arrayGet, load b, call operation,call arraySet
    // since we cannot DUP2 here easily we will save the subscript and DUP x
    // --> sub=a, load x, DUP, load sub, call arrayGet, load b, call operation, load sub, call arraySet

    BinaryExpression arrayWithSubscript = (BinaryExpression) leftExp;
    Expression subscript = arrayWithSubscript.getRightExpression();

    // load array index: sub=a [load x, DUP, load sub, call arrayGet, load b, call operation, load sub, call arraySet]
    subscript.visit(acg);
    operandStack.doGroovyCast(int_TYPE);
    int subscriptValueId = compileStack.defineTemporaryVariable("$sub", ClassHelper.int_TYPE, true);

    // load array: load x and DUP [load sub, call arrayGet, load b, call operation, load sub, call arraySet]
    arrayWithSubscript.getLeftExpression().visit(acg);
    operandStack.doGroovyCast(leftType.makeArray());
    operandStack.dup();

    // array get: load sub, call arrayGet [load b, call operation, load sub, call arraySet]
    operandStack.load(ClassHelper.int_TYPE, subscriptValueId);
    bew.arrayGet(LEFT_SQUARE_BRACKET, false);
    operandStack.replace(leftType, 2);

    // complete rhs: load b, call operation [load sub, call arraySet]
    binExp.getRightExpression().visit(acg);
    if (! (bew instanceof BinaryObjectExpressionHelper)) {
        // in primopts we convert to the left type for supported binary operations
        operandStack.doGroovyCast(leftType);
    }
    bew.write(operation, false);

    // let us save that value for the return
    operandStack.dup();
    int resultValueId = compileStack.defineTemporaryVariable("$result", rightType, true);

    // array set: load sub, call arraySet []
    operandStack.load(ClassHelper.int_TYPE, subscriptValueId);
    operandStack.swap();
    bew.arraySet(false);
    operandStack.remove(3); // 3 operands, the array, the index and the value!

    // load return value
    operandStack.load(rightType, resultValueId);

    // cleanup
    compileStack.removeVar(resultValueId);
    compileStack.removeVar(subscriptValueId);
    return true;
}