Search in sources :

Example 26 with JCBlock

use of com.sun.tools.javac.tree.JCTree.JCBlock in project ceylon-compiler by ceylon.

the class StatementTransformer method transform.

public JCStatement transform(Tree.TryCatchStatement t) {
    Tree.TryClause tryClause = t.getTryClause();
    at(tryClause);
    JCBlock tryBlock = transform(tryClause.getBlock());
    Tree.ResourceList resList = tryClause.getResourceList();
    if (resList != null) {
        ArrayList<Tree.Resource> resources = new ArrayList<Tree.Resource>(resList.getResources());
        Collections.reverse(resources);
        for (Tree.Resource res : resources) {
            List<JCStatement> stats = List.nil();
            Tree.Expression resExpr;
            String resVarName;
            if (res.getExpression() != null) {
                resExpr = res.getExpression();
                resVarName = naming.newTemp("try");
            } else if (res.getVariable() != null) {
                Tree.Variable var = res.getVariable();
                resExpr = var.getSpecifierExpression().getExpression();
                resVarName = var.getIdentifier().getText();
            } else {
                throw new BugException(res, "missing resource expression");
            }
            boolean isDestroyable = typeFact().getDestroyableType().isSupertypeOf(resExpr.getTypeModel());
            Type resVarType = resExpr.getTypeModel();
            Type resVarExpectedType = isDestroyable ? typeFact().getDestroyableType() : typeFact().getObtainableType();
            // CloseableType $var = resource-expression
            JCExpression expr = expressionGen().transformExpression(resExpr);
            JCExpression javaType = makeJavaType(resVarType);
            JCVariableDecl var = makeVar(FINAL, resVarName, javaType, expr);
            stats = stats.append(var);
            if (!isDestroyable) {
                JCExpression resVar0 = expressionGen().applyErasureAndBoxing(makeUnquotedIdent(resVarName), resVarType, true, BoxingStrategy.BOXED, resVarExpectedType);
                JCMethodInvocation openCall = make().Apply(null, makeQualIdent(resVar0, "obtain"), List.<JCExpression>nil());
                stats = stats.append(make().Exec(openCall));
            }
            // Exception $tpmex = null;
            String innerExTmpVarName = naming.newTemp("ex");
            JCExpression innerExType = makeJavaType(typeFact().getThrowableType(), JT_CATCH);
            JCVariableDecl innerExTmpVar = makeVar(innerExTmpVarName, innerExType, makeNull());
            stats = stats.append(innerExTmpVar);
            // $tmpex = ex;
            List<JCStatement> innerCatchStats = List.nil();
            Name innerCatchVarName = naming.tempName("ex");
            JCAssign exTmpAssign = make().Assign(makeUnquotedIdent(innerExTmpVarName), make().Ident(innerCatchVarName));
            innerCatchStats = innerCatchStats.append(make().Exec(exTmpAssign));
            // throw ex;
            JCThrow innerCatchThrow = make().Throw(make().Ident(innerCatchVarName));
            innerCatchStats = innerCatchStats.append(innerCatchThrow);
            JCBlock innerCatchBlock = make().Block(0, innerCatchStats);
            // $var.close() /// ((Closeable)$var).close()
            JCExpression exarg = makeUnquotedIdent(innerExTmpVarName);
            JCExpression resVar1 = expressionGen().applyErasureAndBoxing(makeUnquotedIdent(resVarName), resVarType, true, BoxingStrategy.BOXED, resVarExpectedType);
            JCMethodInvocation closeCall = make().Apply(null, makeQualIdent(resVar1, isDestroyable ? "destroy" : "release"), List.<JCExpression>of(exarg));
            JCBlock closeTryBlock = make().Block(0, List.<JCStatement>of(make().Exec(closeCall)));
            // try { $var.close() } catch (Exception closex) { $tmpex.addSuppressed(closex); }
            Name closeCatchVarName = naming.tempName("closex");
            JCExpression closeCatchExType = makeJavaType(typeFact().getThrowableType(), JT_CATCH);
            JCVariableDecl closeCatchVar = make().VarDef(make().Modifiers(Flags.FINAL), closeCatchVarName, closeCatchExType, null);
            JCExpression addarg = make().Ident(closeCatchVarName);
            JCMethodInvocation addSuppressedCall = make().Apply(null, makeQualIdent(makeUnquotedIdent(innerExTmpVarName), "addSuppressed"), List.<JCExpression>of(addarg));
            JCCatch closeCatch = make().Catch(closeCatchVar, make().Block(0, List.<JCStatement>of(make().Exec(addSuppressedCall))));
            JCTry closeTry = at(res).Try(closeTryBlock, List.<JCCatch>of(closeCatch), null);
            // $var.close() /// ((Closeable)$var).close()
            JCExpression exarg2 = makeUnquotedIdent(innerExTmpVarName);
            JCExpression resVar2 = expressionGen().applyErasureAndBoxing(makeUnquotedIdent(resVarName), resVarType, true, BoxingStrategy.BOXED, resVarExpectedType);
            JCMethodInvocation closeCall2 = make().Apply(null, makeQualIdent(resVar2, isDestroyable ? "destroy" : "release"), List.<JCExpression>of(exarg2));
            // if ($tmpex != null) { ... } else { ... }
            JCBinary closeCatchCond = make().Binary(JCTree.NE, makeUnquotedIdent(innerExTmpVarName), makeNull());
            JCIf closeCatchIf = make().If(closeCatchCond, closeTry, make().Exec(closeCall2));
            // try { .... } catch (Exception ex) { $tmpex=ex; throw ex; }
            // finally { try { $var.close() } catch (Exception closex) { } }
            JCExpression innerCatchExType = makeJavaType(typeFact().getThrowableType(), JT_CATCH);
            JCVariableDecl innerCatchVar = make().VarDef(make().Modifiers(Flags.FINAL), innerCatchVarName, innerCatchExType, null);
            JCCatch innerCatch = make().Catch(innerCatchVar, innerCatchBlock);
            JCBlock innerFinallyBlock = make().Block(0, List.<JCStatement>of(closeCatchIf));
            JCTry innerTry = at(res).Try(tryBlock, List.<JCCatch>of(innerCatch), innerFinallyBlock);
            stats = stats.append(innerTry);
            tryBlock = at(res).Block(0, stats);
        }
    }
    final List<JCCatch> catches;
    if (usePolymorphicCatches(t.getCatchClauses())) {
        catches = transformCatchesPolymorphic(t.getCatchClauses());
    } else {
        catches = transformCatchesIfElseIf(t.getCatchClauses());
    }
    final JCBlock finallyBlock;
    Tree.FinallyClause finallyClause = t.getFinallyClause();
    if (finallyClause != null) {
        at(finallyClause);
        finallyBlock = transform(finallyClause.getBlock());
    } else {
        finallyBlock = null;
    }
    if (!catches.isEmpty() || finallyBlock != null) {
        return at(t).Try(tryBlock, catches, finallyBlock);
    } else {
        return tryBlock;
    }
}
Also used : Variable(com.redhat.ceylon.compiler.typechecker.tree.Tree.Variable) JCAssign(com.sun.tools.javac.tree.JCTree.JCAssign) ArrayList(java.util.ArrayList) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement) SyntheticName(com.redhat.ceylon.compiler.java.codegen.Naming.SyntheticName) CName(com.redhat.ceylon.compiler.java.codegen.Naming.CName) Name(com.sun.tools.javac.util.Name) OptionName(com.sun.tools.javac.main.OptionName) JCIf(com.sun.tools.javac.tree.JCTree.JCIf) Expression(com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression) CustomTree(com.redhat.ceylon.compiler.typechecker.tree.CustomTree) JCTree(com.sun.tools.javac.tree.JCTree) Tree(com.redhat.ceylon.compiler.typechecker.tree.Tree) JCThrow(com.sun.tools.javac.tree.JCTree.JCThrow) JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JCBinary(com.sun.tools.javac.tree.JCTree.JCBinary) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) JCTry(com.sun.tools.javac.tree.JCTree.JCTry) JCMethodInvocation(com.sun.tools.javac.tree.JCTree.JCMethodInvocation) Type(com.redhat.ceylon.model.typechecker.model.Type) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JCCatch(com.sun.tools.javac.tree.JCTree.JCCatch)

Example 27 with JCBlock

use of com.sun.tools.javac.tree.JCTree.JCBlock in project ceylon-compiler by ceylon.

the class StatementTransformer method makeThenBlock.

private JCBlock makeThenBlock(Cond cond, Node thenPart, Substitution subs, String tmpVar, Tree.Term outerExpression, Type expectedType) {
    List<JCStatement> blockStmts;
    if (thenPart instanceof Tree.Block)
        blockStmts = statementGen().transformBlock((Tree.Block) thenPart);
    else if (thenPart instanceof Tree.Expression) {
        blockStmts = evaluateAndAssign(tmpVar, (Tree.Expression) thenPart, outerExpression, expectedType);
    } else if (thenPart == null) {
        blockStmts = List.<JCStatement>nil();
    } else {
        blockStmts = List.<JCStatement>of(make().Exec(makeErroneous(thenPart, "Only block or expression allowed")));
    }
    if (subs != null) {
        // The variable holding the result for the code inside the code block
        blockStmts = blockStmts.prepend(at(cond.getCondition()).VarDef(make().Modifiers(FINAL), names().fromString(subs.substituted), cond.getVarTrans().makeTypeExpr(), cond.getVarTrans().makeResultExpr()));
    }
    JCBlock thenBlock = at(cond.getCondition()).Block(0, blockStmts);
    return thenBlock;
}
Also used : JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) Expression(com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression) JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) ControlBlock(com.redhat.ceylon.model.typechecker.model.ControlBlock) CustomTree(com.redhat.ceylon.compiler.typechecker.tree.CustomTree) JCTree(com.sun.tools.javac.tree.JCTree) Tree(com.redhat.ceylon.compiler.typechecker.tree.Tree) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement)

Example 28 with JCBlock

use of com.sun.tools.javac.tree.JCTree.JCBlock in project ceylon-compiler by ceylon.

the class StatementTransformer method transformCaseMatch.

private JCStatement transformCaseMatch(Naming.SyntheticName selectorAlias, Tree.SwitchClause switchClause, Tree.CaseClause caseClause, String tmpVar, Tree.Term outerExpression, Type expectedType, Tree.MatchCase matchCase, JCStatement last, Type switchType, boolean primitiveSelector) {
    at(matchCase);
    JCExpression tests = null;
    java.util.List<Tree.Expression> expressions = matchCase.getExpressionList().getExpressions();
    for (Tree.Expression expr : expressions) {
        Tree.Term term = ExpressionTransformer.eliminateParens(expr.getTerm());
        boolean unboxedEquality = primitiveSelector || isCeylonBasicType(typeFact().getDefiniteType(switchType));
        JCExpression transformedExpression = expressionGen().transformExpression(term, unboxedEquality ? BoxingStrategy.UNBOXED : BoxingStrategy.BOXED, term.getTypeModel());
        JCExpression test;
        if (term instanceof Tree.Literal || term instanceof Tree.NegativeOp) {
            if (unboxedEquality) {
                if (term instanceof Tree.StringLiteral) {
                    test = make().Apply(null, makeSelect(unboxType(selectorAlias.makeIdent(), term.getTypeModel()), "equals"), List.<JCExpression>of(transformedExpression));
                } else {
                    test = make().Binary(JCTree.EQ, primitiveSelector ? selectorAlias.makeIdent() : unboxType(selectorAlias.makeIdent(), term.getTypeModel()), transformedExpression);
                }
            } else {
                test = make().Apply(null, makeSelect(selectorAlias.makeIdent(), "equals"), List.<JCExpression>of(transformedExpression));
            }
            if (isOptional(switchType)) {
                test = make().Binary(JCTree.AND, make().Binary(JCTree.NE, selectorAlias.makeIdent(), makeNull()), test);
            }
        } else {
            JCExpression selectorExpr;
            if (!primitiveSelector && isCeylonBasicType(typeFact().getDefiniteType(switchType))) {
                selectorExpr = unboxType(selectorAlias.makeIdent(), term.getTypeModel());
            } else {
                selectorExpr = selectorAlias.makeIdent();
            }
            test = make().Binary(JCTree.EQ, selectorExpr, transformedExpression);
        }
        if (tests == null)
            tests = test;
        else if (isNull(term.getTypeModel())) {
            // ensure we do any null check as the first operation in the ||-ed expression
            tests = make().Binary(JCTree.OR, test, tests);
        } else {
            tests = make().Binary(JCTree.OR, tests, test);
        }
    }
    Substitution prevSubst = null;
    if (switchClause.getSwitched().getVariable() != null) {
        // Prepare for variable substitution in the following code block
        prevSubst = naming.addVariableSubst(switchClause.getSwitched().getVariable().getDeclarationModel(), selectorAlias.toString());
    }
    JCBlock block = transformCaseClauseBlock(caseClause, tmpVar, outerExpression, expectedType);
    if (prevSubst != null) {
        // Deactivate the above variable substitution
        prevSubst.close();
    }
    return at(caseClause).If(tests, block, last);
}
Also used : JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) Term(com.redhat.ceylon.compiler.typechecker.tree.Tree.Term) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) Substitution(com.redhat.ceylon.compiler.java.codegen.Naming.Substitution) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) SpecifierOrInitializerExpression(com.redhat.ceylon.compiler.typechecker.tree.Tree.SpecifierOrInitializerExpression) Expression(com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression) Expression(com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression) CustomTree(com.redhat.ceylon.compiler.typechecker.tree.CustomTree) JCTree(com.sun.tools.javac.tree.JCTree) Tree(com.redhat.ceylon.compiler.typechecker.tree.Tree)

Example 29 with JCBlock

use of com.sun.tools.javac.tree.JCTree.JCBlock in project lombok by rzwitserloot.

the class JavacJavaUtilMapSingularizer method generateSingularMethod.

private void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
    List<JCTypeParameter> typeParams = List.nil();
    List<JCExpression> thrown = List.nil();
    JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
    statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, true, source));
    Name keyName = builderType.toName(data.getSingularName().toString() + "Key");
    Name valueName = builderType.toName(data.getSingularName().toString() + "Value");
    /* this.pluralname$key.add(singularnameKey); */
    {
        JCExpression thisDotKeyFieldDotAdd = chainDots(builderType, "this", data.getPluralName() + "$key", "add");
        JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotKeyFieldDotAdd, List.<JCExpression>of(maker.Ident(keyName)));
        statements.append(maker.Exec(invokeAdd));
    }
    /* this.pluralname$value.add(singularnameValue); */
    {
        JCExpression thisDotValueFieldDotAdd = chainDots(builderType, "this", data.getPluralName() + "$value", "add");
        JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotValueFieldDotAdd, List.<JCExpression>of(maker.Ident(valueName)));
        statements.append(maker.Exec(invokeAdd));
    }
    if (returnStatement != null)
        statements.append(returnStatement);
    JCBlock body = maker.Block(0, statements.toList());
    long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
    Name name = data.getSingularName();
    if (!fluent)
        name = builderType.toName(HandlerUtil.buildAccessorName("put", name.toString()));
    JCExpression paramTypeKey = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
    JCExpression paramTypeValue = cloneParamType(1, maker, data.getTypeArgs(), builderType, source);
    JCVariableDecl paramKey = maker.VarDef(maker.Modifiers(paramFlags), keyName, paramTypeKey, null);
    JCVariableDecl paramValue = maker.VarDef(maker.Modifiers(paramFlags), valueName, paramTypeValue, null);
    JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(paramKey, paramValue), thrown, body, null);
    injectMethod(builderType, method);
}
Also used : JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) ListBuffer(com.sun.tools.javac.util.ListBuffer) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) Name(com.sun.tools.javac.util.Name) JCTypeParameter(com.sun.tools.javac.tree.JCTree.JCTypeParameter) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JCModifiers(com.sun.tools.javac.tree.JCTree.JCModifiers)

Example 30 with JCBlock

use of com.sun.tools.javac.tree.JCTree.JCBlock in project lombok by rzwitserloot.

the class PrettyPrinter method printLambda0.

private void printLambda0(JCTree tree) {
    List<JCVariableDecl> params = readObject(tree, "params", List.<JCVariableDecl>nil());
    boolean explicit = true;
    int paramLength = params.size();
    try {
        explicit = readObject(tree, "paramKind", new Object()).toString().equals("EXPLICIT");
    } catch (Exception e) {
    }
    boolean useParens = paramLength != 1 || explicit;
    if (useParens)
        print("(");
    if (explicit) {
        boolean first = true;
        for (JCVariableDecl vd : params) {
            if (!first)
                print(", ");
            first = false;
            printVarDefInline(vd);
        }
    } else {
        String sep = "";
        for (JCVariableDecl param : params) {
            print(sep);
            print(param.name);
            sep = ", ";
        }
    }
    if (useParens)
        print(")");
    print(" -> ");
    JCTree body = readObject(tree, "body", (JCTree) null);
    if (body instanceof JCBlock) {
        println("{");
        indent++;
        print(((JCBlock) body).stats, "");
        indent--;
        aPrint("}");
    } else {
        print(body);
    }
}
Also used : JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JCTree(com.sun.tools.javac.tree.JCTree) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException)

Aggregations

JCBlock (com.sun.tools.javac.tree.JCTree.JCBlock)44 JCExpression (com.sun.tools.javac.tree.JCTree.JCExpression)32 JCStatement (com.sun.tools.javac.tree.JCTree.JCStatement)31 JCVariableDecl (com.sun.tools.javac.tree.JCTree.JCVariableDecl)28 JCTypeParameter (com.sun.tools.javac.tree.JCTree.JCTypeParameter)23 Name (com.sun.tools.javac.util.Name)22 JCModifiers (com.sun.tools.javac.tree.JCTree.JCModifiers)17 ListBuffer (com.sun.tools.javac.util.ListBuffer)17 JCMethodDecl (com.sun.tools.javac.tree.JCTree.JCMethodDecl)16 JavacTreeMaker (lombok.javac.JavacTreeMaker)13 JCTree (com.sun.tools.javac.tree.JCTree)11 JCAnnotation (com.sun.tools.javac.tree.JCTree.JCAnnotation)10 JCPrimitiveTypeTree (com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree)6 JavacNode (lombok.javac.JavacNode)6 JCMethodInvocation (com.sun.tools.javac.tree.JCTree.JCMethodInvocation)5 HasErrorException (com.redhat.ceylon.compiler.java.codegen.recovery.HasErrorException)4 Tree (com.redhat.ceylon.compiler.typechecker.tree.Tree)4 Type (com.redhat.ceylon.model.typechecker.model.Type)4 JCNewClass (com.sun.tools.javac.tree.JCTree.JCNewClass)4 CustomTree (com.redhat.ceylon.compiler.typechecker.tree.CustomTree)3