@Nullable public static JetElement getOutermostLastBlockElement( @Nullable JetElement element, @NotNull Predicate<JetElement> checkElement) { if (element == null) return null; if (!(element instanceof JetBlockExpression)) return checkElement.apply(element) ? element : null; JetBlockExpression block = (JetBlockExpression) element; int n = block.getStatements().size(); if (n == 0) return null; JetElement lastElement = block.getStatements().get(n - 1); return checkElement.apply(lastElement) ? lastElement : null; }
public static boolean checkVariableDeclarationInBlock( @NotNull JetBlockExpression block, @NotNull String varName) { for (JetElement element : block.getStatements()) { if (element instanceof JetVariableDeclaration) { if (((JetVariableDeclaration) element).getNameAsSafeName().asString().equals(varName)) { return true; } } } return false; }
public static boolean isImplicitlyUsed(@NotNull JetElement element) { PsiElement parent = element.getParent(); if (!(parent instanceof JetBlockExpression)) return true; JetBlockExpression block = (JetBlockExpression) parent; List<JetElement> statements = block.getStatements(); if (statements.get(statements.size() - 1) == element) { JetExpression expression = getDirectParentOfTypeForBlock(block, JetIfExpression.class); if (expression == null) { expression = getDirectParentOfTypeForBlock(block, JetWhenExpression.class); } if (expression == null) { expression = getDirectParentOfTypeForBlock(block, JetFunctionLiteral.class); } if (expression == null) { expression = getDirectParentOfTypeForBlock(block, JetTryExpression.class); } if (expression != null) { return isImplicitlyUsed(expression); } } return false; }
@Nullable public static JetElement getLastStatementInABlock(@Nullable JetBlockExpression blockExpression) { if (blockExpression == null) return null; List<JetElement> statements = blockExpression.getStatements(); return statements.isEmpty() ? null : statements.get(statements.size() - 1); }