[Analysis API] refactoring, add utilities to ExpressionMarkersSourceFilePreprocessor which return null in a case caret/selected expression are not found

This commit is contained in:
Ilya Kirillov
2023-08-07 12:27:12 +02:00
committed by Space Team
parent c963eadb44
commit 729bae4a2a
@@ -89,15 +89,19 @@ class ExpressionMarkerProvider : TestService {
}
@OptIn(PrivateForInline::class)
fun getCaretPosition(file: KtFile, caretTag: String? = null): Int {
fun getCaretPositionOrNull(file: KtFile, caretTag: String? = null): Int? {
return carets.getCaretOffset(file.name, caretTag)
}
fun getCaretPosition(file: KtFile, caretTag: String? = null): Int {
return getCaretPositionOrNull(file, caretTag)
?: run {
val caretName = "caret${caretTag?.let { "_$it" }.orEmpty()}"
error("No <$caretName> found in file")
}
}
inline fun <reified P : KtElement> getElementOfTypeAtCaret(file: KtFile, caretTag: String? = null): P {
val offset = getCaretPosition(file, caretTag)
return file.findElementAt(offset)
@@ -143,8 +147,8 @@ class ExpressionMarkerProvider : TestService {
}
fun getSelectedElement(file: KtFile): PsiElement {
val range = selected[file.name] ?: error("No selected expression found in file")
fun getSelectedElementOrNull(file: KtFile): PsiElement? {
val range = selected[file.name] ?: return null
val elements = file.elementsInRange(range).trimWhitespaces()
if (elements.size != 1) {
error("Expected one element at rage but found ${elements.size} [${elements.joinToString { it::class.simpleName + ": " + it.text }}]")
@@ -152,6 +156,11 @@ class ExpressionMarkerProvider : TestService {
return elements.single()
}
fun getSelectedElement(file: KtFile): PsiElement {
return getSelectedElementOrNull(file)
?: error("No selected expression found in file")
}
fun expectedTypeClass(registeredDirectives: RegisteredDirectives): Class<PsiElement>? {
val expectedType = registeredDirectives.singleOrZeroValue(Directives.LOOK_UP_FOR_ELEMENT_OF_TYPE) ?: return null
val ktPsiPackage = "org.jetbrains.kotlin.psi."