package com.vayunmathur.lint import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Location import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.SourceCodeScanner import com.intellij.psi.PsiElement import com.intellij.psi.PsiRecursiveElementVisitor import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtIfExpression import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtQualifiedExpression import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.uast.UElement import org.jetbrains.uast.UFile import java.io.File /** * Dialogs are navigation destinations, not local screen state. * * A dialog that matters — a confirmation, a picker with a result, a small * editor — is a `Route` with `DialogPage()` metadata (the communicate * `DeleteConversationDialog` shape): the identity it acts on travels in the * route arguments, Back / process death / screenshots all see it, and the * dialog content is a stateless composable the route entry renders * unconditionally. The opposite shape — a screen holding * `var showXDialog by remember { mutableStateOf(false) }` (or a nullable * `pending…` / `…Target` state) and rendering a dialog only when that state * says so — hides a screen change inside a composable, so it is flagged here. * * What is flagged, deliberately narrowly (precision over recall): * - a call to `AlertDialog`, `Dialog`, `ModalBottomSheet` or `ConfirmDialog` * (the library's dialog primitives), or to any composable whose simple * name ends in `Dialog` (the app's own dialog composables, e.g. * `RenameTagDialog`), when the call is *gated* by local remember-state: * it sits inside an `if` / `when` whose condition mentions a * `remember`/`rememberSaveable` state property of the same file, or inside * a `state?.let { … }` / qualified `let` on such a property. Route * constructions (`backStack.add(Route.XDialog(...))`) are navigation, not * invocations, and are never flagged. * - one level of indirection: a dialog primitive inside a helper composable * of the same file is flagged when every fact above holds for the helper's * own call sites — e.g. a private `Custom…Dialog` in a screen file that is * only ever invoked under `if (showCustomDialog)`. The helper's gated call * site is flagged too. * * What is never flagged: * - dialog *definitions*: files under `ui/dialogs/` (their internal * text-field / wheel state is dialog-local and stays), and the shared * library (`com.vayunmathur.library.*`), which builds the primitives. * - unconditional dialog calls — a `DialogPage()` route entry rendering its * dialog content, or a dialog host invoked straight from such an entry. * Being shown is decided by the back stack, not by remembered state. * - menus, dropdowns and other in-screen sub-state: only dialog calls match. * - non-`src/main` sources (screenshot captures, tests). * * A dialog that genuinely cannot be a route yet (a multi-step flow whose * intermediate state has no route/result shape) opts out per file with: * `// DIALOG LOCAL EXCEPTION: ` — the shape is validated by * [ExceptionMarkerFormatDetector]. */ class DialogAsRouteDetector : Detector(), SourceCodeScanner { override fun getApplicableUastTypes(): List> = listOf(UFile::class.java) override fun createUastHandler(context: JavaContext): UElementHandler = object : UElementHandler() { override fun visitFile(node: UFile) { val packageName = node.packageName if (packageName.isEmpty()) return if (!packageName.startsWith(APP_PACKAGE_PREFIX)) return if (ExceptionMarkerFormatDetector.isLintRulesPackage(packageName)) return if (LintPackageExclusions.isExcluded(packageName)) return if (isLibraryPackage(packageName)) return val file = context.file ?: return if (!isMainSource(file)) return if (isDialogDefinitionFile(file)) return val ktFile = node.sourcePsi as? KtFile ?: return if (CommentOnlyMatcher.containsMarkerInComments(ktFile, EXCEPTION_MARKER)) return val stateVars = stateProperties(ktFile) if (stateVars.isEmpty()) return val calls = mutableListOf() ktFile.accept(object : PsiRecursiveElementVisitor() { override fun visitElement(element: PsiElement) { super.visitElement(element) if (element is KtCallExpression) calls += element } }) for (call in calls) { val name = simpleCalleeName(call) ?: continue if (!isDialogCall(call, name)) continue val gated = isGated(call, stateVars) || isGatedViaEnclosingFunction(call, calls, stateVars) if (!gated) continue context.report( ISSUE, node, Location.create( file, ktFile.text, call.textRange.startOffset, call.textRange.endOffset, ), "Dialog `$name` is gated by local remember-state here; dialogs are routes. " + "Add a dialog destination (a `Route.…Dialog` entry with `DialogPage()` " + "metadata, its arguments in the route, its content stateless under " + "`ui/dialogs/`) and push it from the click handler instead of holding " + "`show…` / pending-target state in the screen. Definitions under " + "`ui/dialogs/` and unconditional route-entry hosts are not flagged. " + "A flow that genuinely cannot be a route yet opts out per file with " + "`$EXCEPTION_MARKER `.", ) } } } /** Names of `remember`/`rememberSaveable` state properties declared in [ktFile]. */ private fun stateProperties(ktFile: KtFile): Set { val names = mutableSetOf() ktFile.accept(object : PsiRecursiveElementVisitor() { override fun visitElement(element: PsiElement) { super.visitElement(element) if (element !is KtProperty) return val delegate = element.delegateExpression?.text.orEmpty() val initializer = element.initializer?.text.orEmpty() val holdsState = (delegate.contains("remember") || initializer.contains("remember")) && (delegate.contains("mutableState") || initializer.contains("mutableState")) if (holdsState) element.name?.let { names += it } } }) return names } /** Simple callee name: `AlertDialog`, or `AddGroupDialog` for `foo.AddGroupDialog(...)`. */ private fun simpleCalleeName(call: KtCallExpression): String? { val callee = call.calleeExpression ?: return null val text = callee.text.substringBefore('<').trim() return text.substringAfterLast('.').takeIf { it.isNotEmpty() } } private fun isDialogCall(call: KtCallExpression, name: String): Boolean { // Route constructions are navigation targets, not dialog invocations. val calleeText = call.calleeExpression?.text.orEmpty() if (calleeText.startsWith("Route.") || calleeText.contains(".Route.")) return false if (name in DIRECT_DIALOG_CALLS) return true return name.endsWith(DIALOG_SUFFIX) && name.length > DIALOG_SUFFIX.length } /** * True when [element] is lexically gated by one of [stateVars]: an * enclosing `if`/`when` condition mentions the variable, or the element * sits in the selector of a qualified expression (`state?.let { … }`) * whose receiver mentions it. The walk stops at the enclosing function. */ private fun isGated(element: PsiElement, stateVars: Set): Boolean { var current: PsiElement? = element.parent while (current != null && current !is KtNamedFunction && current !is KtFile) { when (current) { is KtIfExpression -> if (mentionsAny(current.condition?.text, stateVars)) return true is KtWhenExpression -> if (mentionsAny(current.subjectExpression?.text, stateVars)) return true is KtQualifiedExpression -> { // Only the selector side is gated by the receiver; the // receiver expression itself is not. if (current.selectorExpression != null && isAncestorOf(current.selectorExpression!!, element) && mentionsAny(current.receiverExpression.text, stateVars) ) return true } } current = current.parent } return false } /** * One level of indirection: [call] sits inside a function whose own call * sites (elsewhere in the file) are gated by remember-state — the shape of * a private `Custom…Dialog` helper invoked only under `if (show…)`. */ private fun isGatedViaEnclosingFunction( call: KtCallExpression, allCalls: List, stateVars: Set, ): Boolean { var current: PsiElement? = call.parent var enclosing: KtNamedFunction? = null while (current != null && current !is KtFile) { if (current is KtNamedFunction) { enclosing = current break } current = current.parent } val function = enclosing ?: return false val functionName = function.name ?: return false return allCalls.any { site -> site != call && !isAncestorOf(function, site) && simpleCalleeName(site) == functionName && isGated(site, stateVars) } } private fun isAncestorOf(ancestor: PsiElement, element: PsiElement): Boolean { var current: PsiElement? = element while (current != null) { if (current == ancestor) return true current = current.parent } return false } private fun mentionsAny(text: String?, stateVars: Set): Boolean { if (text.isNullOrEmpty()) return false return stateVars.any { name -> Regex("""(?`. """.trimIndent(), category = Category.CORRECTNESS, priority = 6, severity = Severity.ERROR, implementation = Implementation( DialogAsRouteDetector::class.java, Scope.JAVA_FILE_SCOPE, ), ) } }