org.codehaus.groovy.syntax.Types Java Examples

The following examples show how to use org.codehaus.groovy.syntax.Types. 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: ScopeVisitor.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void visitBinaryExpression(BinaryExpression expression) {
    Token operation = expression.getOperation();
    if (operation.isA(Types.LEFT_SHIFT) && expression.getLeftExpression() instanceof VariableExpression && expression.getRightExpression() instanceof ClosureExpression) {
        addCreator(scope, (VariableExpression) expression.getLeftExpression(), (ClosureExpression) expression.getRightExpression());
    } else if (operation.isA(Types.ASSIGN)) {
        if (expression.getLeftExpression() instanceof VariableExpression) {
            addCreator(scope, (VariableExpression) expression.getLeftExpression(), expression.getRightExpression());
        } else if (expression.getLeftExpression() instanceof PropertyExpression) {
            addCreator(scope, (PropertyExpression) expression.getLeftExpression(), expression.getRightExpression());
        } else {
            super.visitBinaryExpression(expression);
        }
    } else {
        super.visitBinaryExpression(expression);
    }
}
 
Example #2
Source File: VariableFinderVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBinaryExpression(BinaryExpression expression) {
    // if we are in the same block we check position, if it occurs after
    // current position we ignore it
    if (blocks.isEmpty()
            && expression.getLineNumber() >= 0 && expression.getColumnNumber() >= 0
            && path.getLineNumber() >= 0 && path.getColumnNumber() >= 0
            && (expression.getLineNumber() > path.getLineNumber()
            || (expression.getLineNumber() == path.getLineNumber() && expression.getColumnNumber() >= path.getColumnNumber()))) {
        return;
    }

    Expression leftExpression = expression.getLeftExpression();
    if (leftExpression instanceof VariableExpression) {
        if (expression.getOperation().isA(Types.EQUAL)) {
            VariableExpression variableExpression = (VariableExpression) leftExpression;
            if (variableExpression.getAccessedVariable() != null) {
                String name = variableExpression.getAccessedVariable().getName();
                if (!variables.containsKey(name)) {
                    variables.put(name, variableExpression.getAccessedVariable());
                }
            }
        }
    }
    super.visitBinaryExpression(expression);
}
 
Example #3
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 #4
Source File: RuleVisitor.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void visitClosureExpression(ClosureExpression expression) {
    if (inputs == null) {
        inputs = ImmutableListMultimap.builder();
        try {
            accessVariable = new VariableExpression(ACCESS_HOLDER_FIELD, ACCESS_API_TYPE);

            super.visitClosureExpression(expression);

            BlockStatement code = (BlockStatement) expression.getCode();
            code.setNodeMetaData(AST_NODE_METADATA_INPUTS_KEY, inputs.build());
            accessVariable.setClosureSharedVariable(true);
            StaticMethodCallExpression getAccessCall = new StaticMethodCallExpression(CONTEXTUAL_INPUT_TYPE, GET_ACCESS, ArgumentListExpression.EMPTY_ARGUMENTS);
            DeclarationExpression variableDeclaration = new DeclarationExpression(accessVariable, new Token(Types.ASSIGN, "=", -1, -1), getAccessCall);
            code.getStatements().add(0, new ExpressionStatement(variableDeclaration));
            code.getVariableScope().putDeclaredVariable(accessVariable);
        } finally {
            inputs = null;
        }
    } else {
        expression.getVariableScope().putReferencedLocalVariable(accessVariable);
        super.visitClosureExpression(expression);
    }
}
 
Example #5
Source File: TryWithResourcesASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private CatchStatement createCatchBlockForOuterNewTryCatchStatement(String primaryExcName) {
    // { ... }
    BlockStatement blockStatement = new BlockStatement();
    String tExcName = this.genTExcName();

    // #primaryExc = #t;
    ExpressionStatement primaryExcAssignStatement =
            new ExpressionStatement(
                    new BinaryExpression(
                            new VariableExpression(primaryExcName),
                            newSymbol(Types.ASSIGN, -1, -1),
                            new VariableExpression(tExcName)));
    astBuilder.appendStatementsToBlockStatement(blockStatement, primaryExcAssignStatement);

    // throw #t;
    ThrowStatement throwTExcStatement = new ThrowStatement(new VariableExpression(tExcName));
    astBuilder.appendStatementsToBlockStatement(blockStatement, throwTExcStatement);

    // Throwable #t
    Parameter tExcParameter = new Parameter(ClassHelper.make(Throwable.class), tExcName);

    return new CatchStatement(tExcParameter, blockStatement);
}
 
Example #6
Source File: ScopeVisitor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void visitBinaryExpression(BinaryExpression expression) {
    Token operation = expression.getOperation();
    if (operation.isA(Types.LEFT_SHIFT) && expression.getLeftExpression() instanceof VariableExpression && expression.getRightExpression() instanceof ClosureExpression) {
        addCreator(scope, (VariableExpression) expression.getLeftExpression(), (ClosureExpression) expression.getRightExpression());
    } else if (operation.isA(Types.ASSIGN)) {
        if (expression.getLeftExpression() instanceof VariableExpression) {
            addCreator(scope, (VariableExpression) expression.getLeftExpression(), expression.getRightExpression());
        } else if (expression.getLeftExpression() instanceof PropertyExpression) {
            addCreator(scope, (PropertyExpression) expression.getLeftExpression(), expression.getRightExpression());
        } else {
            super.visitBinaryExpression(expression);
        }
    } else {
        super.visitBinaryExpression(expression);
    }
}
 
Example #7
Source File: RuleVisitor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void visitClosureExpression(ClosureExpression expression) {
    if (inputs == null) {
        inputs = ImmutableListMultimap.builder();
        try {
            accessVariable = new VariableExpression(ACCESS_HOLDER_FIELD, ACCESS_API_TYPE);

            super.visitClosureExpression(expression);

            BlockStatement code = (BlockStatement) expression.getCode();
            code.setNodeMetaData(AST_NODE_METADATA_INPUTS_KEY, inputs.build());
            accessVariable.setClosureSharedVariable(true);
            StaticMethodCallExpression getAccessCall = new StaticMethodCallExpression(CONTEXTUAL_INPUT_TYPE, GET_ACCESS, ArgumentListExpression.EMPTY_ARGUMENTS);
            DeclarationExpression variableDeclaration = new DeclarationExpression(accessVariable, new Token(Types.ASSIGN, "=", -1, -1), getAccessCall);
            code.getStatements().add(0, new ExpressionStatement(variableDeclaration));
            code.getVariableScope().putDeclaredVariable(accessVariable);
        } finally {
            inputs = null;
        }
    } else {
        expression.getVariableScope().putReferencedLocalVariable(accessVariable);
        super.visitClosureExpression(expression);
    }
}
 
Example #8
Source File: StaticImportVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected Expression transformBinaryExpression(BinaryExpression be) {
    int type = be.getOperation().getType();
    boolean oldInLeftExpression;
    Expression right = transform(be.getRightExpression());
    be.setRightExpression(right);
    Expression left;
    if (type == Types.EQUAL && be.getLeftExpression() instanceof VariableExpression) {
        oldInLeftExpression = inLeftExpression;
        inLeftExpression = true;
        left = transform(be.getLeftExpression());
        inLeftExpression = oldInLeftExpression;
        if (left instanceof StaticMethodCallExpression) {
            StaticMethodCallExpression smce = (StaticMethodCallExpression) left;
            StaticMethodCallExpression result = new StaticMethodCallExpression(smce.getOwnerType(), smce.getMethod(), right);
            setSourcePosition(result, be);
            return result;
        }
    } else {
        left = transform(be.getLeftExpression());
    }
    be.setLeftExpression(left);
    return be;
}
 
Example #9
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 #10
Source File: InnerClassVisitorHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected static void setPropertySetterDispatcher(BlockStatement block, Expression thiz, Parameter[] parameters) {
    List<ConstantExpression> gStringStrings = new ArrayList<ConstantExpression>();
    gStringStrings.add(new ConstantExpression(""));
    gStringStrings.add(new ConstantExpression(""));
    List<Expression> gStringValues = new ArrayList<Expression>();
    gStringValues.add(new VariableExpression(parameters[0]));
    block.addStatement(
            new ExpressionStatement(
                    new BinaryExpression(
                            new PropertyExpression(
                                    thiz,
                                    new GStringExpression("$name", gStringStrings, gStringValues)
                            ),
                            Token.newSymbol(Types.ASSIGN, -1, -1),
                            new VariableExpression(parameters[1])
                    )
            )
    );
}
 
Example #11
Source File: BinaryExpressionTransformer.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static BinaryExpression tryOptimizeCharComparison(final Expression left, final Expression right, final BinaryExpression bin) {
    int op = bin.getOperation().getType();
    if (StaticTypeCheckingSupport.isCompareToBoolean(op) || op == Types.COMPARE_EQUAL || op == Types.COMPARE_NOT_EQUAL) {
        Character cLeft = tryCharConstant(left);
        Character cRight = tryCharConstant(right);
        if (cLeft != null || cRight != null) {
            Expression oLeft = (cLeft == null ? left : constX(cLeft, true));
            oLeft.setSourcePosition(left);
            Expression oRight = (cRight == null ? right : constX(cRight, true));
            oRight.setSourcePosition(right);
            bin.setLeftExpression(oLeft);
            bin.setRightExpression(oRight);
            return bin;
        }
    }
    return null;
}
 
Example #12
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private TernaryExpression createStaticReceiver(final Expression receiver) {
    return new TernaryExpression(
            new BooleanExpression(new BinaryExpression(
                    receiver,
                    Token.newSymbol(Types.KEYWORD_INSTANCEOF, -1, -1),
                    new ClassExpression(ClassHelper.CLASS_Type)
            )),
            receiver,
            new MethodCallExpression(createFieldHelperReceiver(), "getClass", ArgumentListExpression.EMPTY_ARGUMENTS)
    );
}
 
Example #13
Source File: ValidationCodeVisitorSupport.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visitBinaryExpression(final BinaryExpression expression) {
    if (expression.getOperation() != null && expression.getOperation().isA(Types.ASSIGNMENT_OPERATOR)) {
        final org.codehaus.groovy.ast.expr.Expression leftExpression = expression.getLeftExpression();
        if (dependenciesName.contains(leftExpression.getText())) {
            errorStatus.add(context.createFailureStatus(Messages.bind(
                    Messages.invalidDependencyAssignement, leftExpression.getText())));

        }
    }
    super.visitBinaryExpression(expression);
}
 
Example #14
Source File: BinaryExpression.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an assignment expression in which the specified expression
 * is written into the specified variable name.
 */

public static BinaryExpression newAssignmentExpression(Variable variable, Expression rhs) {
    VariableExpression lhs = new VariableExpression(variable);
    Token operator = Token.newPlaceholder(Types.ASSIGN);

    return new BinaryExpression(lhs, operator, rhs);
}
 
Example #15
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 #16
Source File: VariableScopeVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitBinaryExpression(final BinaryExpression expression) {
    super.visitBinaryExpression(expression);

    if (Types.isAssignment(expression.getOperation().getType())) {
        checkFinalFieldAccess(expression.getLeftExpression());
    }
}
 
Example #17
Source File: OptimizingStatementWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Optimizes "Z = X/Y" with Z being int or long style.
 *
 * @returns null if the optimization cannot be applied, otherwise it will return the new target type
 */
private ClassNode optimizeDivWithIntOrLongTarget(final Expression rhs, final ClassNode assignmentTartgetType) {
    if (!(rhs instanceof BinaryExpression)) return null;
    BinaryExpression binExp = (BinaryExpression) rhs;
    int op = binExp.getOperation().getType();
    if (op != Types.DIVIDE && op != Types.DIVIDE_EQUAL) return null;

    ClassNode originalResultType = typeChooser.resolveType(binExp, node);
    if (!originalResultType.equals(BigDecimal_TYPE)
            || !(isLongCategory(assignmentTartgetType) || isFloatingCategory(assignmentTartgetType))) {
        return null;
    }

    ClassNode leftType = typeChooser.resolveType(binExp.getLeftExpression(), node);
    if (!isLongCategory(leftType)) return null;
    ClassNode rightType = typeChooser.resolveType(binExp.getRightExpression(), node);
    if (!isLongCategory(rightType)) return null;

    ClassNode target;
    if (isIntCategory(leftType) && isIntCategory(rightType)) {
        target = int_TYPE;
    } else if (isLongCategory(leftType) && isLongCategory(rightType)) {
        target = long_TYPE;
    } else if (isDoubleCategory(leftType) && isDoubleCategory(rightType)) {
        target = double_TYPE;
    } else {
        return null;
    }
    addMeta(rhs).type = target;
    opt.chainInvolvedType(target);
    return target;
}
 
Example #18
Source File: TraitComposer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Statement createSuperFallback(MethodNode forwarderMethod, ClassNode returnType) {
    ArgumentListExpression args = new ArgumentListExpression();
    Parameter[] forwarderMethodParameters = forwarderMethod.getParameters();
    for (final Parameter forwarderMethodParameter : forwarderMethodParameters) {
        args.addExpression(new VariableExpression(forwarderMethodParameter));
    }
    BinaryExpression instanceOfExpr = new BinaryExpression(new VariableExpression("this"), Token.newSymbol(Types.KEYWORD_INSTANCEOF, -1, -1), new ClassExpression(Traits.GENERATED_PROXY_CLASSNODE));
    MethodCallExpression superCall = new MethodCallExpression(
            new VariableExpression("super"),
            forwarderMethod.getName(),
            args
    );
    superCall.setImplicitThis(false);
    CastExpression proxyReceiver = new CastExpression(Traits.GENERATED_PROXY_CLASSNODE, new VariableExpression("this"));
    MethodCallExpression getProxy = new MethodCallExpression(proxyReceiver, "getProxyTarget", ArgumentListExpression.EMPTY_ARGUMENTS);
    getProxy.setImplicitThis(true);
    StaticMethodCallExpression proxyCall = new StaticMethodCallExpression(
            ClassHelper.make(InvokerHelper.class),
            "invokeMethod",
            new ArgumentListExpression(getProxy, new ConstantExpression(forwarderMethod.getName()), new ArrayExpression(ClassHelper.OBJECT_TYPE, args.getExpressions()))
    );
    IfStatement stmt = new IfStatement(
            new BooleanExpression(instanceOfExpr),
            new ExpressionStatement(new CastExpression(returnType,proxyCall)),
            new ExpressionStatement(superCall)
    );
    return stmt;
}
 
Example #19
Source File: SqlWhereVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected String tokenAsSql(Token token) {
    switch (token.getType()) {
        case Types.COMPARE_EQUAL:
            return "=";
        case Types.LOGICAL_AND:
            return "and";
        case Types.LOGICAL_OR:
            return "or";
        default:
            return token.getText();
    }
}
 
Example #20
Source File: TryWithResourcesASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private BlockStatement createFinallyBlockForNewTryCatchStatement(String primaryExcName, String firstResourceIdentifierName) {
    BlockStatement finallyBlock = new BlockStatement();

    // primaryExc != null
    BooleanExpression conditionExpression =
            new BooleanExpression(
                    new BinaryExpression(
                            new VariableExpression(primaryExcName),
                            newSymbol(Types.COMPARE_NOT_EQUAL, -1, -1),
                            new ConstantExpression(null)));

    // try-catch statement
    TryCatchStatement newTryCatchStatement =
            new TryCatchStatement(
                    astBuilder.createBlockStatement(this.createCloseResourceStatement(firstResourceIdentifierName)), // { Identifier?.close(); }
                    EmptyStatement.INSTANCE);


    String suppressedExcName = this.genSuppressedExcName();
    newTryCatchStatement.addCatch(
            // catch (Throwable #suppressedExc) { .. }
            new CatchStatement(
                    new Parameter(ClassHelper.make(Throwable.class), suppressedExcName),
                    astBuilder.createBlockStatement(this.createAddSuppressedStatement(primaryExcName, suppressedExcName)) // #primaryExc.addSuppressed(#suppressedExc);
            )
    );

    // if (#primaryExc != null) { ... }
    IfStatement ifStatement =
            new IfStatement(
                    conditionExpression,
                    newTryCatchStatement,
                    this.createCloseResourceStatement(firstResourceIdentifierName) // Identifier?.close();
            );
    astBuilder.appendStatementsToBlockStatement(finallyBlock, ifStatement);

    return astBuilder.createBlockStatement(finallyBlock);
}
 
Example #21
Source File: BinaryExpression.java    From groovy with Apache License 2.0 4 votes vote down vote up
public String getText() {
    if (operation.getType() == Types.LEFT_SQUARE_BRACKET) {
        return leftExpression.getText() + (safe ? "?" : "") + "[" + rightExpression.getText() + "]";
    }
    return "(" + leftExpression.getText() + " " + operation.getText() + " " + rightExpression.getText() + ")";
}
 
Example #22
Source File: SuperCallTraitTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
private Expression transformBinaryExpression(final BinaryExpression exp) {
    Expression trn = super.transform(exp);
    if (trn instanceof BinaryExpression) {
        BinaryExpression bin = (BinaryExpression) trn;
        Expression leftExpression = bin.getLeftExpression();
        if (bin.getOperation().getType() == Types.EQUAL && leftExpression instanceof PropertyExpression) {
            ClassNode traitReceiver = null;
            PropertyExpression leftPropertyExpression = (PropertyExpression) leftExpression;
            if (isTraitSuperPropertyExpression(leftPropertyExpression.getObjectExpression())) {
                PropertyExpression pexp = (PropertyExpression) leftPropertyExpression.getObjectExpression();
                traitReceiver = pexp.getObjectExpression().getType();
            }
            if (traitReceiver!=null) {
                // A.super.foo = ...
                TraitHelpersTuple helpers = Traits.findHelpers(traitReceiver);
                ClassNode helper = helpers.getHelper();
                String setterName = MetaProperty.getSetterName(leftPropertyExpression.getPropertyAsString());
                List<MethodNode> methods = helper.getMethods(setterName);
                for (MethodNode method : methods) {
                    Parameter[] parameters = method.getParameters();
                    if (parameters.length==2 && parameters[0].getType().equals(traitReceiver)) {
                        ArgumentListExpression args = new ArgumentListExpression(
                                new VariableExpression("this"),
                                transform(exp.getRightExpression())
                        );
                        MethodCallExpression setterCall = new MethodCallExpression(
                                new ClassExpression(helper),
                                setterName,
                                args
                        );
                        setterCall.setMethodTarget(method);
                        setterCall.setImplicitThis(false);
                        return setterCall;
                    }
                }
                return bin;
            }
        }
    }
    return trn;
}
 
Example #23
Source File: CompareIdentityExpression.java    From groovy with Apache License 2.0 4 votes vote down vote up
public CompareIdentityExpression(final Expression leftExpression, final Expression rightExpression) {
    super(leftExpression, new Token(Types.COMPARE_TO, "==", -1, -1), rightExpression);
    this.leftExpression = leftExpression;
    this.rightExpression = rightExpression;
}
 
Example #24
Source File: CompareToNullExpression.java    From groovy with Apache License 2.0 4 votes vote down vote up
public CompareToNullExpression(final Expression objectExpression, final boolean compareToNull) {
    super(objectExpression, new Token(Types.COMPARE_TO, compareToNull ? "==" : "!=", -1, -1), ConstantExpression.NULL);
    this.objectExpression = objectExpression;
    this.equalsNull = compareToNull;
}
 
Example #25
Source File: Verifier.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void addFieldInitialization(List list, List staticList, FieldNode fieldNode,
                                      boolean isEnumClassNode, List initStmtsAfterEnumValuesInit, Set explicitStaticPropsInEnum) {
    Expression expression = fieldNode.getInitialExpression();
    if (expression != null) {
        final FieldExpression fe = new FieldExpression(fieldNode);
        if (fieldNode.getType().equals(ClassHelper.REFERENCE_TYPE) && ((fieldNode.getModifiers() & ACC_SYNTHETIC) != 0)) {
            fe.setUseReferenceDirectly(true);
        }
        ExpressionStatement statement =
                new ExpressionStatement(
                        new BinaryExpression(
                                fe,
                                Token.newSymbol(Types.EQUAL, fieldNode.getLineNumber(), fieldNode.getColumnNumber()),
                                expression));
        if (fieldNode.isStatic()) {
            // GROOVY-3311: pre-defined constants added by groovy compiler for numbers/characters should be
            // initialized first so that code dependent on it does not see their values as empty
            Expression initialValueExpression = fieldNode.getInitialValueExpression();
            Expression transformed = transformInlineConstants(initialValueExpression, fieldNode.getType());
            if (transformed instanceof ConstantExpression) {
                ConstantExpression cexp = (ConstantExpression) transformed;
                cexp = transformToPrimitiveConstantIfPossible(cexp);
                if (fieldNode.isFinal() && ClassHelper.isStaticConstantInitializerType(cexp.getType()) && cexp.getType().equals(fieldNode.getType())) {
                    fieldNode.setInitialValueExpression(transformed);
                    return; // GROOVY-5150: primitive type constants will be initialized directly
                }
                staticList.add(0, statement);
            } else {
                staticList.add(statement);
            }
            fieldNode.setInitialValueExpression(null); // to avoid double initialization in case of several constructors
            /*
             * If it is a statement for an explicitly declared static field inside an enum, store its
             * reference. For enums, they need to be handled differently as such init statements should
             * come after the enum values have been initialized inside <clinit> block. GROOVY-3161.
             */
            if (isEnumClassNode && explicitStaticPropsInEnum.contains(fieldNode.getName())) {
                initStmtsAfterEnumValuesInit.add(statement);
            }
        } else {
            list.add(statement);
        }
    }
}
 
Example #26
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static boolean isAssignment(final int op) {
    return Types.isAssignment(op);
}
 
Example #27
Source File: OptimizingStatementWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitBinaryExpression(final BinaryExpression expression) {
    if (expression.getNodeMetaData(StatementMeta.class) != null) return;
    super.visitBinaryExpression(expression);

    ClassNode leftType = typeChooser.resolveType(expression.getLeftExpression(), node);
    ClassNode rightType = typeChooser.resolveType(expression.getRightExpression(), node);
    ClassNode resultType = null;
    int operation = expression.getOperation().getType();

    if (operation == Types.LEFT_SQUARE_BRACKET && leftType.isArray()) {
        opt.chainShouldOptimize(true);
        resultType = leftType.getComponentType();
    } else {
        switch (operation) {
            case Types.COMPARE_EQUAL:
            case Types.COMPARE_LESS_THAN:
            case Types.COMPARE_LESS_THAN_EQUAL:
            case Types.COMPARE_GREATER_THAN:
            case Types.COMPARE_GREATER_THAN_EQUAL:
            case Types.COMPARE_NOT_EQUAL:
                if (isIntCategory(leftType) && isIntCategory(rightType)) {
                    opt.chainShouldOptimize(true);
                } else if (isLongCategory(leftType) && isLongCategory(rightType)) {
                    opt.chainShouldOptimize(true);
                } else if (isDoubleCategory(leftType) && isDoubleCategory(rightType)) {
                    opt.chainShouldOptimize(true);
                } else {
                    opt.chainCanOptimize(true);
                }
                resultType = boolean_TYPE;
                break;
            case Types.LOGICAL_AND:
            case Types.LOGICAL_AND_EQUAL:
            case Types.LOGICAL_OR:
            case Types.LOGICAL_OR_EQUAL:
                if (boolean_TYPE.equals(leftType) && boolean_TYPE.equals(rightType)) {
                    opt.chainShouldOptimize(true);
                } else {
                    opt.chainCanOptimize(true);
                }
                expression.setType(boolean_TYPE);
                resultType = boolean_TYPE;
                break;
            case Types.DIVIDE:
            case Types.DIVIDE_EQUAL:
                if (isLongCategory(leftType) && isLongCategory(rightType)) {
                    resultType = BigDecimal_TYPE;
                    opt.chainShouldOptimize(true);
                } else if (isBigDecCategory(leftType) && isBigDecCategory(rightType)) {
                    // no optimization for BigDecimal yet
                    //resultType = BigDecimal_TYPE;
                } else if (isDoubleCategory(leftType) && isDoubleCategory(rightType)) {
                    resultType = double_TYPE;
                    opt.chainShouldOptimize(true);
                }
                break;
            case Types.POWER:
            case Types.POWER_EQUAL:
                // TODO: implement
                break;
            case Types.ASSIGN:
                resultType = optimizeDivWithIntOrLongTarget(expression.getRightExpression(), leftType);
                opt.chainCanOptimize(true);
                break;
            default:
                if (isIntCategory(leftType) && isIntCategory(rightType)) {
                    resultType = int_TYPE;
                    opt.chainShouldOptimize(true);
                } else if (isLongCategory(leftType) && isLongCategory(rightType)) {
                    resultType = long_TYPE;
                    opt.chainShouldOptimize(true);
                } else if (isBigDecCategory(leftType) && isBigDecCategory(rightType)) {
                    // no optimization for BigDecimal yet
                    //resultType = BigDecimal_TYPE;
                } else if (isDoubleCategory(leftType) && isDoubleCategory(rightType)) {
                    resultType = double_TYPE;
                    opt.chainShouldOptimize(true);
                }
        }
    }

    if (resultType != null) {
        addMeta(expression).type = resultType;
        opt.chainInvolvedType(resultType);
        opt.chainInvolvedType(rightType);
        opt.chainInvolvedType(leftType);
    }
}
 
Example #28
Source File: SandboxInvoker.java    From groovy-cps with Apache License 2.0 4 votes vote down vote up
public void setProperty(Object lhs, String name, Object value) throws Throwable {
    Checker.checkedSetProperty(lhs,name,false,false, Types.ASSIGN,value);
}
 
Example #29
Source File: SandboxInvoker.java    From groovy-cps with Apache License 2.0 4 votes vote down vote up
public void setAttribute(Object lhs, String name, Object value) throws Throwable {
    Checker.checkedSetAttribute(lhs, name, false, false, Types.ASSIGN, value);
}
 
Example #30
Source File: SandboxInvoker.java    From groovy-cps with Apache License 2.0 4 votes vote down vote up
public void setArray(Object lhs, Object index, Object value) throws Throwable {
    Checker.checkedSetArray(lhs,index,Types.ASSIGN,value);
}