com.sun.tools.javac.tree.JCTree.JCTry Java Examples

The following examples show how to use com.sun.tools.javac.tree.JCTree.JCTry. 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: HandleSneakyThrows.java    From EasyMPermission with MIT License 6 votes vote down vote up
public JCStatement buildTryCatchBlock(JavacNode node, List<JCStatement> contents, String exception, JCTree source) {
	JavacTreeMaker maker = node.getTreeMaker();
	
	Context context = node.getContext();
	JCBlock tryBlock = setGeneratedBy(maker.Block(0, contents), source, context);
	JCExpression varType = chainDots(node, exception.split("\\."));
	
	JCVariableDecl catchParam = maker.VarDef(maker.Modifiers(Flags.FINAL | Flags.PARAMETER), node.toName("$ex"), varType, null);
	JCExpression lombokLombokSneakyThrowNameRef = chainDots(node, "lombok", "Lombok", "sneakyThrow");
	JCBlock catchBody = maker.Block(0, List.<JCStatement>of(maker.Throw(maker.Apply(
			List.<JCExpression>nil(), lombokLombokSneakyThrowNameRef,
			List.<JCExpression>of(maker.Ident(node.toName("$ex")))))));
	JCTry tryStatement = maker.Try(tryBlock, List.of(recursiveSetGeneratedBy(maker.Catch(catchParam, catchBody), source, context)), null);
	if (JavacHandlerUtil.inNetbeansEditor(node)) {
		//set span (start and end position) of the try statement and the main block
		//this allows NetBeans to dive into the statement correctly:
		JCCompilationUnit top = (JCCompilationUnit) node.top().get();
		int startPos = contents.head.pos;
		int endPos = Javac.getEndPosition(contents.last().pos(), top);
		tryBlock.pos = startPos;
		tryStatement.pos = startPos;
		Javac.storeEnd(tryBlock, endPos, top);
		Javac.storeEnd(tryStatement, endPos, top);
	}
	return setGeneratedBy(tryStatement, source, context);
}
 
Example #2
Source File: CRTable.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitTry(JCTry tree) {
    SourceRange sr = new SourceRange(startPos(tree), endPos(tree));
    sr.mergeWith(csp(tree.resources));
    sr.mergeWith(csp(tree.body));
    sr.mergeWith(cspCatchers(tree.catchers));
    sr.mergeWith(csp(tree.finalizer));
    result = sr;
}
 
Example #3
Source File: TransTypes.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitTry(JCTry tree) {
    tree.resources = translate(tree.resources, syms.autoCloseableType);
    tree.body = translate(tree.body);
    tree.catchers = translateCatchers(tree.catchers);
    tree.finalizer = translate(tree.finalizer);
    result = tree;
}
 
Example #4
Source File: Flow.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitTry(JCTry tree) {
    for (JCTree resource : tree.resources) {
        if (!resource.hasTag(VARDEF)) {
            Symbol var = TreeInfo.symbol(resource);
            if (var != null && (var.flags() & (FINAL | EFFECTIVELY_FINAL)) == 0) {
                log.error(resource.pos(), Errors.TryWithResourcesExprEffectivelyFinalVar(var));
            }
        }
    }
    super.visitTry(tree);
}
 
Example #5
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private JCStatement makeTwrCloseStatement(Symbol primaryException, JCExpression resource) {
    // primaryException.addSuppressed(catchException);
    VarSymbol catchException =
        new VarSymbol(SYNTHETIC, make.paramName(2),
                      syms.throwableType,
                      currentMethodSym);
    JCStatement addSuppressionStatement =
        make.Exec(makeCall(make.Ident(primaryException),
                           names.addSuppressed,
                           List.of(make.Ident(catchException))));

    // try { resource.close(); } catch (e) { primaryException.addSuppressed(e); }
    JCBlock tryBlock =
        make.Block(0L, List.of(makeResourceCloseInvocation(resource)));
    JCVariableDecl catchExceptionDecl = make.VarDef(catchException, null);
    JCBlock catchBlock = make.Block(0L, List.of(addSuppressionStatement));
    List<JCCatch> catchClauses = List.of(make.Catch(catchExceptionDecl, catchBlock));
    JCTry tryTree = make.Try(tryBlock, catchClauses, null);
    tryTree.finallyCanCompleteNormally = true;

    // if (primaryException != null) {try...} else resourceClose;
    JCIf closeIfStatement = make.If(makeNonNullCheck(make.Ident(primaryException)),
                                    tryTree,
                                    makeResourceCloseInvocation(resource));

    return closeIfStatement;
}
 
Example #6
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void visitTry(JCTry tree) {
    if (tree.resources.nonEmpty()) {
        result = makeTwrTry(tree);
        return;
    }

    boolean hasBody = tree.body.getStatements().nonEmpty();
    boolean hasCatchers = tree.catchers.nonEmpty();
    boolean hasFinally = tree.finalizer != null &&
            tree.finalizer.getStatements().nonEmpty();

    if (!hasCatchers && !hasFinally) {
        result = translate(tree.body);
        return;
    }

    if (!hasBody) {
        if (hasFinally) {
            result = translate(tree.finalizer);
        } else {
            result = translate(tree.body);
        }
        return;
    }

    // no optimizations possible
    super.visitTry(tree);
}
 
Example #7
Source File: Analyzer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void visitTry(JCTry tree) {
    //skip resources (to prevents same statements to be analyzed twice)
    scan(tree.getBlock());
    scan(tree.getCatches());
    scan(tree.getFinallyBlock());
}
 
Example #8
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private TryStatement convertTry(JCTry statement) {
  List<JCCatch> catchClauses = statement.getCatches();

  return TryStatement.newBuilder()
      .setSourcePosition(getSourcePosition(statement))
      .setResourceDeclarations(
          statement.getResources().stream().map(this::toResource).collect(toImmutableList()))
      .setBody(convertBlock(statement.getBlock()))
      .setCatchClauses(
          catchClauses.stream().map(this::convertCatchClause).collect(toImmutableList()))
      .setFinallyBlock((Block) convertStatementOrNull(statement.getFinallyBlock()))
      .build();
}
 
Example #9
Source File: JavacAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
private JavacNode buildTry(JCTry tryNode) {
	if (setAndGetAsHandled(tryNode)) return null;
	List<JavacNode> childNodes = new ArrayList<JavacNode>();
	for (JCTree varDecl : getResourcesForTryNode(tryNode)) {
		if (varDecl instanceof JCVariableDecl) {
			addIfNotNull(childNodes, buildLocalVar((JCVariableDecl) varDecl, Kind.LOCAL));
		}
	}
	addIfNotNull(childNodes, buildStatement(tryNode.body));
	for (JCCatch jcc : tryNode.catchers) addIfNotNull(childNodes, buildTree(jcc, Kind.STATEMENT));
	addIfNotNull(childNodes, buildStatement(tryNode.finalizer));
	return putInMap(new JavacNode(this, tryNode, childNodes, Kind.STATEMENT));
}
 
Example #10
Source File: JavacAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
private JavacNode buildStatementOrExpression(JCTree statement) {
	if (statement == null) return null;
	if (statement instanceof JCAnnotation) return null;
	if (statement instanceof JCClassDecl) return buildType((JCClassDecl)statement);
	if (statement instanceof JCVariableDecl) return buildLocalVar((JCVariableDecl)statement, Kind.LOCAL);
	if (statement instanceof JCTry) return buildTry((JCTry) statement);
	
	if (setAndGetAsHandled(statement)) return null;
	
	return drill(statement);
}
 
Example #11
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 4 votes vote down vote up
private Statement convertStatement(JCStatement jcStatement) {
  switch (jcStatement.getKind()) {
    case ASSERT:
      return convertAssert((JCAssert) jcStatement);
    case BLOCK:
      return convertBlock((JCBlock) jcStatement);
    case BREAK:
      return convertBreak((JCBreak) jcStatement);
    case CLASS:
      convertClassDeclaration((JCClassDecl) jcStatement);
      return null;
    case CONTINUE:
      return convertContinue((JCContinue) jcStatement);
    case DO_WHILE_LOOP:
      return convertDoWhileLoop((JCDoWhileLoop) jcStatement);
    case EMPTY_STATEMENT:
      return new EmptyStatement(getSourcePosition(jcStatement));
    case ENHANCED_FOR_LOOP:
      return convertEnhancedForLoop((JCEnhancedForLoop) jcStatement);
    case EXPRESSION_STATEMENT:
      return convertExpressionStatement((JCExpressionStatement) jcStatement);
    case FOR_LOOP:
      return convertForLoop((JCForLoop) jcStatement);
    case IF:
      return convertIf((JCIf) jcStatement);
    case LABELED_STATEMENT:
      return convertLabeledStatement((JCLabeledStatement) jcStatement);
    case RETURN:
      return convertReturn((JCReturn) jcStatement);
    case SWITCH:
      return convertSwitch((JCSwitch) jcStatement);
    case THROW:
      return convertThrow((JCThrow) jcStatement);
    case TRY:
      return convertTry((JCTry) jcStatement);
    case VARIABLE:
      return convertVariableDeclaration((JCVariableDecl) jcStatement);
    case WHILE_LOOP:
      return convertWhileLoop((JCWhileLoop) jcStatement);
    case SYNCHRONIZED:
      return convertSynchronized((JCSynchronized) jcStatement);
    default:
      throw new AssertionError("Unknown statement node type: " + jcStatement.getKind());
  }
}
 
Example #12
Source File: JavacTreeMaker.java    From EasyMPermission with MIT License 4 votes vote down vote up
public JCTry Try(JCBlock body, List<JCCatch> catchers, JCBlock finalizer) {
	return invoke(Try, body, catchers, finalizer);
}
 
Example #13
Source File: JavacTreeMaker.java    From EasyMPermission with MIT License 4 votes vote down vote up
public JCTry Try(List<JCTree> resources, JCBlock body, List<JCCatch> catchers, JCBlock finalizer) {
	return invoke(TryWithResources, resources, body, catchers, finalizer);
}
 
Example #14
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Optionally replace a try statement with the desugaring of a
 * try-with-resources statement.  The canonical desugaring of
 *
 * try ResourceSpecification
 *   Block
 *
 * is
 *
 * {
 *   final VariableModifiers_minus_final R #resource = Expression;
 *   Throwable #primaryException = null;
 *
 *   try ResourceSpecificationtail
 *     Block
 *   catch (Throwable #t) {
 *     #primaryException = t;
 *     throw #t;
 *   } finally {
 *     if (#resource != null) {
 *       if (#primaryException != null) {
 *         try {
 *           #resource.close();
 *         } catch(Throwable #suppressedException) {
 *           #primaryException.addSuppressed(#suppressedException);
 *         }
 *       } else {
 *         #resource.close();
 *       }
 *     }
 *   }
 *
 * @param tree  The try statement to inspect.
 * @return A a desugared try-with-resources tree, or the original
 * try block if there are no resources to manage.
 */
JCTree makeTwrTry(JCTry tree) {
    make_at(tree.pos());
    twrVars = twrVars.dup();
    JCBlock twrBlock = makeTwrBlock(tree.resources, tree.body,
            tree.finallyCanCompleteNormally, 0);
    if (tree.catchers.isEmpty() && tree.finalizer == null)
        result = translate(twrBlock);
    else
        result = translate(make.Try(twrBlock, tree.catchers, tree.finalizer));
    twrVars = twrVars.leave();
    return result;
}