use of org.eclipse.ceylon.langtools.tools.javac.tree.JCTree.JCThrow in project ceylon by eclipse.
the class ClassTransformer method transform.
public void transform(Tree.AttributeDeclaration decl, ClassDefinitionBuilder classBuilder) {
final Value model = decl.getDeclarationModel();
boolean withinInterface = model.isInterfaceMember();
Tree.SpecifierOrInitializerExpression initializer = decl.getSpecifierOrInitializerExpression();
final boolean lazy = initializer instanceof Tree.LazySpecifierExpression;
String attrName = decl.getIdentifier().getText();
boolean memoized = Decl.isMemoized(decl);
boolean isStatic = model.isStatic();
// Only a non-formal or a concrete-non-lazy attribute has a corresponding field
// and if a captured class parameter exists with the same name we skip this part as well
Parameter parameter = CodegenUtil.findParamForDecl(decl);
boolean useField = !lazy && Strategy.useField(model);
boolean createField = !lazy && !model.isFormal() && Strategy.createField(parameter, model) && !model.isJavaNative();
boolean createCompanionField = !lazy && withinInterface && initializer != null;
JCThrow err = null;
JCExpression memoizedInitialValue = null;
if (createCompanionField || createField) {
TypedReference typedRef = getTypedReference(model);
TypedReference nonWideningTypedRef = nonWideningTypeDecl(typedRef);
Type nonWideningType = nonWideningType(typedRef, nonWideningTypedRef);
if (Decl.isIndirect(decl)) {
attrName = Naming.getAttrClassName(model, 0);
nonWideningType = getGetterInterfaceType(model);
}
JCExpression initialValue = null;
BoxingStrategy boxingStrategy = null;
if (initializer != null) {
Tree.Expression expression = initializer.getExpression();
HasErrorException error = errors().getFirstExpressionErrorAndMarkBrokenness(expression.getTerm());
int flags = CodegenUtil.downcastForSmall(expression, model) ? ExpressionTransformer.EXPR_UNSAFE_PRIMITIVE_TYPECAST_OK : 0;
flags |= model.hasUncheckedNullType() ? ExpressionTransformer.EXPR_TARGET_ACCEPTS_NULL : 0;
if (error != null) {
initialValue = null;
err = makeThrowUnresolvedCompilationError(error.getErrorMessage().getMessage());
} else {
boxingStrategy = useJavaBox(model, nonWideningType) && javaBoxExpression(expression.getTypeModel(), nonWideningType) ? BoxingStrategy.JAVA : CodegenUtil.getBoxingStrategy(model);
initialValue = expressionGen().transformExpression(expression, boxingStrategy, isStatic && nonWideningType.isTypeParameter() ? typeFact().getAnythingType() : nonWideningType, flags);
}
}
if (memoized) {
memoizedInitialValue = initialValue;
initialValue = makeDefaultExprForType(nonWideningType);
}
int flags = 0;
if (!CodegenUtil.isUnBoxed(nonWideningTypedRef.getDeclaration())) {
flags |= JT_NO_PRIMITIVES;
}
long modifiers = useField ? modifierTransformation().field(decl) : modifierTransformation().localVar(decl);
// does it in those cases)
if (parameter == null || parameter.isHidden()) {
JCExpression type;
if (isStatic && nonWideningType.isTypeParameter()) {
type = make().Type(syms().objectType);
} else {
type = makeJavaType(nonWideningType, flags);
}
if (createCompanionField) {
classBuilder.getCompanionBuilder((TypeDeclaration) model.getContainer()).field(modifiers, attrName, type, initialValue, !useField);
} else {
List<JCAnnotation> annos = makeAtIgnore().prependList(expressionGen().transformAnnotations(OutputElement.FIELD, decl));
if (classBuilder.hasDelegatingConstructors()) {
annos = annos.prependList(makeAtNoInitCheck());
}
// fields should be ignored, they are accessed by the getters
if (err == null) {
// TODO This should really be using AttributeDefinitionBuilder somehow
if (useField) {
AttributeDefinitionBuilder adb = AttributeDefinitionBuilder.field(this, null, attrName, model, Decl.isIndirect(decl)).fieldAnnotations(annos).fieldNullability(makeNullabilityAnnotations(model)).initialValue(initialValue, boxingStrategy).fieldVisibilityModifiers(modifiers).modifiers(modifiers);
classBuilder.defs(adb.buildFields());
List<JCStatement> buildInit = adb.buildInit(false);
if (!buildInit.isEmpty()) {
if (isStatic) {
classBuilder.defs(make().Block(STATIC, buildInit));
} else {
classBuilder.getInitBuilder().init(buildInit);
}
}
} else if (!memoized) {
classBuilder.field(modifiers, attrName, type, initialValue, !useField, annos);
if (!isEe(model) && model.isLate() && CodegenUtil.needsLateInitField(model, typeFact())) {
classBuilder.field(PRIVATE | Flags.VOLATILE | Flags.TRANSIENT, Naming.getInitializationFieldName(attrName), make().Type(syms().booleanType), make().Literal(false), false, makeAtIgnore());
}
}
}
}
}
// A shared attribute might be initialized in a for statement, so
// we might need a def-assignment subst for it
JCStatement outerSubs = statementGen().openOuterSubstitutionIfNeeded(model, model.getType(), 0);
if (outerSubs != null) {
classBuilder.getInitBuilder().init(outerSubs);
}
}
if (useField || withinInterface || lazy) {
boolean generateInClassOrInterface = !withinInterface || model.isShared() || isStatic;
boolean generateInCompanionClass = withinInterface && lazy && !isStatic;
if (generateInClassOrInterface) {
// Generate getter in main class or interface (when shared)
at(decl.getType());
AttributeDefinitionBuilder getter = makeGetter(decl, false, memoizedInitialValue);
if (err != null) {
getter.getterBlock(make().Block(0, List.<JCStatement>of(err)));
}
classBuilder.attribute(getter);
}
if (generateInCompanionClass) {
Interface container = (Interface) model.getContainer();
// Generate getter in companion class
classBuilder.getCompanionBuilder(container).attribute(makeGetter(decl, true, null));
}
if (Decl.isVariable(model) || model.isLate()) {
if (generateInClassOrInterface) {
// Generate setter in main class or interface (when shared)
classBuilder.attribute(makeSetter(decl, false, memoizedInitialValue));
}
if (generateInCompanionClass) {
Interface container = (Interface) model.getContainer();
// Generate setter in companion class
classBuilder.getCompanionBuilder(container).attribute(makeSetter(decl, true, null));
}
}
}
}
use of org.eclipse.ceylon.langtools.tools.javac.tree.JCTree.JCThrow in project ceylon by eclipse.
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");
}
final TryResourceTransformation resourceTx;
if (typeFact().getDestroyableType().isSupertypeOf(resExpr.getTypeModel())) {
resourceTx = destroyableResource;
} else if (typeFact().getObtainableType().isSupertypeOf(resExpr.getTypeModel())) {
resourceTx = obtainableResource;
} else if (javacJavaTypeToProducedType(syms().autoCloseableType).isSupertypeOf(resExpr.getTypeModel())) {
resourceTx = javaAutoCloseableResource;
} else {
throw BugException.unhandledTypeCase(resExpr.getTypeModel());
}
Type resVarType = resExpr.getTypeModel();
Type resVarExpectedType = resourceTx.getType();
// 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 (resourceTx.getInitMethodName() != null) {
JCExpression resVar0 = expressionGen().applyErasureAndBoxing(makeUnquotedIdent(resVarName), resVarType, true, BoxingStrategy.BOXED, resVarExpectedType);
JCMethodInvocation openCall = make().Apply(null, makeQualIdent(resVar0, resourceTx.getInitMethodName()), 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);
JCExpression closeCall = resourceTx.makeRecover(resVar1, 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));
JCStatement catchForClose;
if (resourceTx != javaAutoCloseableResource) {
// Obtainable.release() and Destroyable.close() could
// rethrow the originating exception, so guard against
// self-supression (which causes addSuppressed() to throw
catchForClose = make().If(make().Binary(JCTree.Tag.NE, makeUnquotedIdent(innerExTmpVarName), make().Ident(closeCatchVarName)), make().Block(0, List.<JCStatement>of(make().Exec(addSuppressedCall))), null);
} else {
// AutoClosable can't rethrow the originating exception,
// so no need to worry about self suppression
catchForClose = make().Exec(addSuppressedCall);
}
JCCatch closeCatch = make().Catch(closeCatchVar, make().Block(0, List.<JCStatement>of(catchForClose)));
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);
JCExpression closeCall2 = resourceTx.makeRecover(resVar1, exarg);
// if ($tmpex != null) { ... } else { ... }
JCBinary closeCatchCond = make().Binary(JCTree.Tag.NE, makeUnquotedIdent(innerExTmpVarName), makeNull());
JCIf closeCatchIf = make().If(closeCatchCond, make().Block(0, List.<JCStatement>of(closeTry)), make().Block(0, List.<JCStatement>of(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;
}
}
use of org.eclipse.ceylon.langtools.tools.javac.tree.JCTree.JCThrow in project ceylon by eclipse.
the class InitializerBuilder method build.
/**
* Only called for classes with parameter lists
*/
JCMethodDecl build() {
if (delegateCall != null) /* && !isAlias*/
{
init.add(0, delegateCall);
}
List<JCStatement> body = statementsBetween(null, null);
int index = 0;
for (JCStatement stmt : body) {
if (stmt instanceof JCThrow) {
ListBuffer<JCStatement> filtered = new ListBuffer<JCStatement>();
filtered.addAll(body.subList(0, index + 1));
body = filtered.toList();
break;
}
index++;
}
MethodDefinitionBuilder constructor = MethodDefinitionBuilder.constructor(gen, deprecated);
constructor.modifiers(modifiers).userAnnotations(userAnnos.toList()).parameters(params.toList()).body(body);
return constructor.build();
}
use of org.eclipse.ceylon.langtools.tools.javac.tree.JCTree.JCThrow in project ceylon by eclipse.
the class JavaPositionsRetriever method getJavaSourceCodeWithCeylonPositions.
public String getJavaSourceCodeWithCeylonPositions() {
final CharArrayWriter writer = new CharArrayWriter();
Pretty printer = new Pretty(writer, true) {
int previousCeylonPosition = -1;
int previousPositionInString = 0;
private void outputCeylonPosition(JCTree tree) {
try {
int currentCeylonPosition = tree.getPreferredPosition();
int currentPositionInString = writer.size();
if (previousCeylonPosition != currentCeylonPosition || previousPositionInString != currentPositionInString) {
if (currentCeylonPosition != -1 && currentCeylonPosition != 0) {
writer.write("/* " + formatCeylonPosition(currentCeylonPosition) + " */");
}
previousCeylonPosition = currentCeylonPosition;
previousPositionInString = writer.size();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void visitTopLevel(JCCompilationUnit tree) {
outputCeylonPosition(tree);
super.visitTopLevel(tree);
}
@Override
public void visitImport(JCImport tree) {
outputCeylonPosition(tree);
super.visitImport(tree);
}
@Override
public void visitClassDef(JCClassDecl tree) {
outputCeylonPosition(tree);
super.visitClassDef(tree);
}
@Override
public void visitMethodDef(JCMethodDecl tree) {
outputCeylonPosition(tree);
super.visitMethodDef(tree);
}
@Override
public void visitVarDef(JCVariableDecl tree) {
outputCeylonPosition(tree);
super.visitVarDef(tree);
}
@Override
public void visitSkip(JCSkip tree) {
outputCeylonPosition(tree);
super.visitSkip(tree);
}
@Override
public void visitBlock(JCBlock tree) {
outputCeylonPosition(tree);
super.visitBlock(tree);
tree.endpos = currentPosition - 1;
}
@Override
public void visitDoLoop(JCDoWhileLoop tree) {
outputCeylonPosition(tree);
super.visitDoLoop(tree);
}
@Override
public void visitWhileLoop(JCWhileLoop tree) {
outputCeylonPosition(tree);
super.visitWhileLoop(tree);
}
@Override
public void visitForLoop(JCForLoop tree) {
outputCeylonPosition(tree);
super.visitForLoop(tree);
}
@Override
public void visitForeachLoop(JCEnhancedForLoop tree) {
outputCeylonPosition(tree);
super.visitForeachLoop(tree);
}
@Override
public void visitLabelled(JCLabeledStatement tree) {
outputCeylonPosition(tree);
super.visitLabelled(tree);
}
@Override
public void visitSwitch(JCSwitch tree) {
outputCeylonPosition(tree);
super.visitSwitch(tree);
}
@Override
public void visitCase(JCCase tree) {
outputCeylonPosition(tree);
super.visitCase(tree);
}
@Override
public void visitSynchronized(JCSynchronized tree) {
outputCeylonPosition(tree);
super.visitSynchronized(tree);
}
@Override
public void visitTry(JCTry tree) {
outputCeylonPosition(tree);
super.visitTry(tree);
}
@Override
public void visitCatch(JCCatch tree) {
outputCeylonPosition(tree);
super.visitCatch(tree);
}
@Override
public void visitConditional(JCConditional tree) {
outputCeylonPosition(tree);
super.visitConditional(tree);
}
@Override
public void visitIf(JCIf tree) {
outputCeylonPosition(tree);
super.visitIf(tree);
}
@Override
public void visitExec(JCExpressionStatement tree) {
outputCeylonPosition(tree);
super.visitExec(tree);
}
@Override
public void visitBreak(JCBreak tree) {
outputCeylonPosition(tree);
super.visitBreak(tree);
}
@Override
public void visitContinue(JCContinue tree) {
outputCeylonPosition(tree);
super.visitContinue(tree);
}
@Override
public void visitReturn(JCReturn tree) {
outputCeylonPosition(tree);
super.visitReturn(tree);
}
@Override
public void visitThrow(JCThrow tree) {
outputCeylonPosition(tree);
super.visitThrow(tree);
}
@Override
public void visitAssert(JCAssert tree) {
outputCeylonPosition(tree);
super.visitAssert(tree);
}
@Override
public void visitApply(JCMethodInvocation tree) {
outputCeylonPosition(tree);
super.visitApply(tree);
}
@Override
public void visitNewClass(JCNewClass tree) {
outputCeylonPosition(tree);
super.visitNewClass(tree);
}
@Override
public void visitNewArray(JCNewArray tree) {
outputCeylonPosition(tree);
super.visitNewArray(tree);
}
@Override
public void visitParens(JCParens tree) {
outputCeylonPosition(tree);
super.visitParens(tree);
}
@Override
public void visitAssign(JCAssign tree) {
outputCeylonPosition(tree);
super.visitAssign(tree);
}
@Override
public void visitAssignop(JCAssignOp tree) {
outputCeylonPosition(tree);
super.visitAssignop(tree);
}
@Override
public void visitUnary(JCUnary tree) {
outputCeylonPosition(tree);
super.visitUnary(tree);
}
@Override
public void visitBinary(JCBinary tree) {
outputCeylonPosition(tree);
super.visitBinary(tree);
}
@Override
public void visitTypeCast(JCTypeCast tree) {
outputCeylonPosition(tree);
super.visitTypeCast(tree);
}
@Override
public void visitTypeTest(JCInstanceOf tree) {
outputCeylonPosition(tree);
super.visitTypeTest(tree);
}
@Override
public void visitIndexed(JCArrayAccess tree) {
outputCeylonPosition(tree);
super.visitIndexed(tree);
}
@Override
public void visitSelect(JCFieldAccess tree) {
outputCeylonPosition(tree);
super.visitSelect(tree);
}
@Override
public void visitIdent(JCIdent tree) {
outputCeylonPosition(tree);
super.visitIdent(tree);
}
@Override
public void visitLiteral(JCLiteral tree) {
outputCeylonPosition(tree);
super.visitLiteral(tree);
}
@Override
public void visitTypeIdent(JCPrimitiveTypeTree tree) {
outputCeylonPosition(tree);
super.visitTypeIdent(tree);
}
@Override
public void visitTypeArray(JCArrayTypeTree tree) {
outputCeylonPosition(tree);
super.visitTypeArray(tree);
}
@Override
public void visitTypeApply(JCTypeApply tree) {
outputCeylonPosition(tree);
super.visitTypeApply(tree);
}
@Override
public void visitTypeParameter(JCTypeParameter tree) {
outputCeylonPosition(tree);
super.visitTypeParameter(tree);
}
@Override
public void visitWildcard(JCWildcard tree) {
outputCeylonPosition(tree);
super.visitWildcard(tree);
}
@Override
public void visitTypeBoundKind(TypeBoundKind tree) {
outputCeylonPosition(tree);
super.visitTypeBoundKind(tree);
}
@Override
public void visitErroneous(JCErroneous tree) {
outputCeylonPosition(tree);
super.visitErroneous(tree);
}
@Override
public void visitLetExpr(LetExpr tree) {
outputCeylonPosition(tree);
super.visitLetExpr(tree);
}
@Override
public void visitModifiers(JCModifiers mods) {
outputCeylonPosition(mods);
super.visitModifiers(mods);
}
@Override
public void visitAnnotation(JCAnnotation tree) {
outputCeylonPosition(tree);
super.visitAnnotation(tree);
}
@Override
public void visitTree(JCTree tree) {
outputCeylonPosition(tree);
super.visitTree(tree);
}
};
printer.visitTopLevel(unit);
return writer.toString();
}
Aggregations