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

The following examples show how to use com.sun.tools.javac.tree.JCTree.JCCatch. 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: CRTable.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**  Visitor method: compute source positions for
 *   a list of catch clauses in try statements.
 */
public SourceRange cspCatchers(List<JCCatch> trees) {
    if ((trees == null) || !(trees.nonEmpty())) return null;
    SourceRange list_sr = new SourceRange();
    for (List<JCCatch> l = trees; l.nonEmpty(); l = l.tail) {
        list_sr.mergeWith(csp(l.head));
    }
    positions.put(trees, list_sr);
    return list_sr;
}
 
Example #2
Source File: JavacTrees.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override @DefinedBy(Api.COMPILER_TREE)
public TypeMirror getLub(CatchTree tree) {
    JCCatch ct = (JCCatch) tree;
    JCVariableDecl v = ct.param;
    if (v.type != null && v.type.getKind() == TypeKind.UNION) {
        UnionClassType ut = (UnionClassType) v.type;
        return ut.getLub();
    } else {
        return v.type;
    }
}
 
Example #3
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 #4
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 #5
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private CatchClause convertCatchClause(JCCatch catchClause) {
  // Order is important here, exception declaration must be converted before body.
  return CatchClause.newBuilder()
      .setExceptionVariable(createVariable(catchClause.getParameter(), false))
      .setBody(convertBlock(catchClause.getBlock()))
      .build();
}
 
Example #6
Source File: JavacTrees.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override @DefinedBy(Api.COMPILER_TREE)
public TypeMirror getLub(CatchTree tree) {
    JCCatch ct = (JCCatch) tree;
    JCVariableDecl v = ct.param;
    if (v.type != null && v.type.getKind() == TypeKind.UNION) {
        UnionClassType ut = (UnionClassType) v.type;
        return ut.getLub();
    } else {
        return v.type;
    }
}
 
Example #7
Source File: PrettyCommentsPrinter.java    From EasyMPermission with MIT License 5 votes vote down vote up
public void visitCatch(JCCatch tree) {
	try {
		print(" catch (");
		printExpr(tree.param);
		print(") ");
		printStat(tree.body);
	} catch (IOException e) {
		throw new UncheckedIOException(e);
	}
}
 
Example #8
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 #9
Source File: JavacAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
/** For javac, both JCExpression and JCStatement are considered as valid children types. */
@Override
protected Collection<Class<? extends JCTree>> getStatementTypes() {
	Collection<Class<? extends JCTree>> collection = new ArrayList<Class<? extends JCTree>>(3);
	collection.add(JCStatement.class);
	collection.add(JCExpression.class);
	collection.add(JCCatch.class);
	return collection;
}
 
Example #10
Source File: CRTable.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void visitCatch(JCCatch tree) {
    SourceRange sr = new SourceRange(startPos(tree), endPos(tree));
    sr.mergeWith(csp(tree.param));
    sr.mergeWith(csp(tree.body));
    result = sr;
}
 
Example #11
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
void translate() {
    make.at(pos.getStartPosition());
    JCClassDecl owner = classDef((ClassSymbol)mapVar.owner);

    // synthetic static final int[] $SwitchMap$Color = new int[Color.values().length];
    MethodSymbol valuesMethod = lookupMethod(pos,
                                             names.values,
                                             forEnum.type,
                                             List.nil());
    JCExpression size = make // Color.values().length
        .Select(make.App(make.QualIdent(valuesMethod)),
                syms.lengthVar);
    JCExpression mapVarInit = make
        .NewArray(make.Type(syms.intType), List.of(size), null)
        .setType(new ArrayType(syms.intType, syms.arrayClass));

    // try { $SwitchMap$Color[red.ordinal()] = 1; } catch (java.lang.NoSuchFieldError ex) {}
    ListBuffer<JCStatement> stmts = new ListBuffer<>();
    Symbol ordinalMethod = lookupMethod(pos,
                                        names.ordinal,
                                        forEnum.type,
                                        List.nil());
    List<JCCatch> catcher = List.<JCCatch>nil()
        .prepend(make.Catch(make.VarDef(new VarSymbol(PARAMETER, names.ex,
                                                      syms.noSuchFieldErrorType,
                                                      syms.noSymbol),
                                        null),
                            make.Block(0, List.nil())));
    for (Map.Entry<VarSymbol,Integer> e : values.entrySet()) {
        VarSymbol enumerator = e.getKey();
        Integer mappedValue = e.getValue();
        JCExpression assign = make
            .Assign(make.Indexed(mapVar,
                                 make.App(make.Select(make.QualIdent(enumerator),
                                                      ordinalMethod))),
                    make.Literal(mappedValue))
            .setType(syms.intType);
        JCStatement exec = make.Exec(assign);
        JCStatement _try = make.Try(make.Block(0, List.of(exec)), catcher, null);
        stmts.append(_try);
    }

    owner.defs = owner.defs
        .prepend(make.Block(STATIC, stmts.toList()))
        .prepend(make.VarDef(mapVar, mapVarInit));
}
 
Example #12
Source File: NBAttr.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void visitCatch(JCCatch that) {
    super.visitBlock(tm.Block(0, List.of(that.param, that.body)));
}
 
Example #13
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 #14
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 #15
Source File: JavacTreeMaker.java    From EasyMPermission with MIT License 4 votes vote down vote up
public JCCatch Catch(JCVariableDecl param, JCBlock body) {
	return invoke(Catch, param, body);
}
 
Example #16
Source File: HandleCleanup.java    From EasyMPermission with MIT License 4 votes vote down vote up
@Override public void handle(AnnotationValues<Cleanup> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleFlagUsage(annotationNode, ConfigurationKeys.CLEANUP_FLAG_USAGE, "@Cleanup");
	
	if (inNetbeansEditor(annotationNode)) return;
	
	deleteAnnotationIfNeccessary(annotationNode, Cleanup.class);
	String cleanupName = annotation.getInstance().value();
	if (cleanupName.length() == 0) {
		annotationNode.addError("cleanupName cannot be the empty string.");
		return;
	}
	
	if (annotationNode.up().getKind() != Kind.LOCAL) {
		annotationNode.addError("@Cleanup is legal only on local variable declarations.");
		return;
	}
	
	JCVariableDecl decl = (JCVariableDecl)annotationNode.up().get();
	
	if (decl.init == null) {
		annotationNode.addError("@Cleanup variable declarations need to be initialized.");
		return;
	}
	
	JavacNode ancestor = annotationNode.up().directUp();
	JCTree blockNode = ancestor.get();
	
	final List<JCStatement> statements;
	if (blockNode instanceof JCBlock) {
		statements = ((JCBlock)blockNode).stats;
	} else if (blockNode instanceof JCCase) {
		statements = ((JCCase)blockNode).stats;
	} else if (blockNode instanceof JCMethodDecl) {
		statements = ((JCMethodDecl)blockNode).body.stats;
	} else {
		annotationNode.addError("@Cleanup is legal only on a local variable declaration inside a block.");
		return;
	}
	
	boolean seenDeclaration = false;
	ListBuffer<JCStatement> newStatements = new ListBuffer<JCStatement>();
	ListBuffer<JCStatement> tryBlock = new ListBuffer<JCStatement>();
	for (JCStatement statement : statements) {
		if (!seenDeclaration) {
			if (statement == decl) seenDeclaration = true;
			newStatements.append(statement);
		} else {
			tryBlock.append(statement);
		}
	}
	
	if (!seenDeclaration) {
		annotationNode.addError("LOMBOK BUG: Can't find this local variable declaration inside its parent.");
		return;
	}
	doAssignmentCheck(annotationNode, tryBlock.toList(), decl.name);
	
	JavacTreeMaker maker = annotationNode.getTreeMaker();
	JCFieldAccess cleanupMethod = maker.Select(maker.Ident(decl.name), annotationNode.toName(cleanupName));
	List<JCStatement> cleanupCall = List.<JCStatement>of(maker.Exec(
			maker.Apply(List.<JCExpression>nil(), cleanupMethod, List.<JCExpression>nil())));
	
	JCExpression preventNullAnalysis = preventNullAnalysis(maker, annotationNode, maker.Ident(decl.name));
	JCBinary isNull = maker.Binary(CTC_NOT_EQUAL, preventNullAnalysis, maker.Literal(CTC_BOT, null));
	
	JCIf ifNotNullCleanup = maker.If(isNull, maker.Block(0, cleanupCall), null);
	
	Context context = annotationNode.getContext();
	JCBlock finalizer = recursiveSetGeneratedBy(maker.Block(0, List.<JCStatement>of(ifNotNullCleanup)), ast, context);
	
	newStatements.append(setGeneratedBy(maker.Try(setGeneratedBy(maker.Block(0, tryBlock.toList()), ast, context), List.<JCCatch>nil(), finalizer), ast, context));
	
	if (blockNode instanceof JCBlock) {
		((JCBlock)blockNode).stats = newStatements.toList();
	} else if (blockNode instanceof JCCase) {
		((JCCase)blockNode).stats = newStatements.toList();
	} else if (blockNode instanceof JCMethodDecl) {
		((JCMethodDecl)blockNode).body.stats = newStatements.toList();
	} else throw new AssertionError("Should not get here");
	
	ancestor.rebuild();
}