Refactored (and more correct) getOutermostLastBlockElement and its usages

This commit is contained in:
Valentin Kipyatkov
2015-05-12 18:28:37 +03:00
parent 38ac420057
commit d95b198da7
10 changed files with 50 additions and 50 deletions
@@ -600,21 +600,6 @@ public class JetPsiUtil {
((JetBinaryExpression) element).getOperationToken().equals(JetTokens.EQ);
}
@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) {
@@ -44,6 +44,7 @@ import com.intellij.openapi.util.TextRange
import com.intellij.psi.stubs.StubElement
import org.jetbrains.kotlin.JetNodeTypes
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.utils.addToStdlib.lastIsInstanceOrNull
public fun JetCallElement.getCallNameExpression(): JetSimpleNameExpression? {
val calleeExpression = getCalleeExpression() ?: return null
@@ -135,8 +136,11 @@ public fun <T: PsiElement> T.copied(): T = copy() as T
public fun JetElement.blockExpressionsOrSingle(): Sequence<JetElement> =
if (this is JetBlockExpression) getStatements().asSequence() else sequenceOf(this)
public fun JetElement.outermostLastBlockElement(predicate: (JetElement) -> Boolean = { true }): JetElement? {
return JetPsiUtil.getOutermostLastBlockElement(this) { e -> e != null && predicate(e) }
public fun JetExpression.lastBlockStatementOrThis(): JetExpression {
return if (this is JetBlockExpression)
this.getStatements().lastIsInstanceOrNull<JetExpression>() ?: this
else
this
}
public fun JetBlockExpression.appendElement(element: JetElement): JetElement {
@@ -53,6 +53,24 @@ public inline fun <reified T> Array<*>.firstIsInstance(): T {
throw NoSuchElementException("No element of given type found")
}
public inline fun <reified T : Any> Iterable<*>.lastIsInstanceOrNull(): T? {
when (this) {
is List<*> -> {
for (i in this.indices.reversed()) {
val element = this[i]
if (element is T) return element
}
return null
}
else -> {
return reverse().firstIsInstanceOrNull<T>()
}
}
}
public fun <T> streamOfLazyValues(vararg elements: () -> T): Stream<T> = elements.stream().map { it() }
public fun <T1, T2> Pair<T1, T2>.swap(): Pair<T2, T1> = Pair(second, first)
public fun <T1, T2> Pair<T1, T2>.swap(): Pair<T2, T1> = Pair(second, first)
public fun <T: Any> T.check(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null