Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / lint-rules / src / main / java / com / vayunmathur / lint / DialogAsRouteDetector.kt

DialogAsRouteDetector.kt293 lines · 13.9 KiBRaw
1package com.vayunmathur.lint
2
3import com.android.tools.lint.client.api.UElementHandler
4import com.android.tools.lint.detector.api.Category
5import com.android.tools.lint.detector.api.Detector
6import com.android.tools.lint.detector.api.Implementation
7import com.android.tools.lint.detector.api.Issue
8import com.android.tools.lint.detector.api.JavaContext
9import com.android.tools.lint.detector.api.Location
10import com.android.tools.lint.detector.api.Scope
11import com.android.tools.lint.detector.api.Severity
12import com.android.tools.lint.detector.api.SourceCodeScanner
13import com.intellij.psi.PsiElement
14import com.intellij.psi.PsiRecursiveElementVisitor
15import org.jetbrains.kotlin.psi.KtCallExpression
16import org.jetbrains.kotlin.psi.KtFile
17import org.jetbrains.kotlin.psi.KtIfExpression
18import org.jetbrains.kotlin.psi.KtNamedFunction
19import org.jetbrains.kotlin.psi.KtProperty
20import org.jetbrains.kotlin.psi.KtQualifiedExpression
21import org.jetbrains.kotlin.psi.KtWhenExpression
22import org.jetbrains.uast.UElement
23import org.jetbrains.uast.UFile
24import java.io.File
25
26/**
27 * Dialogs are navigation destinations, not local screen state.
28 *
29 * A dialog that matters — a confirmation, a picker with a result, a small
30 * editor — is a `Route` with `DialogPage()` metadata (the communicate
31 * `DeleteConversationDialog` shape): the identity it acts on travels in the
32 * route arguments, Back / process death / screenshots all see it, and the
33 * dialog content is a stateless composable the route entry renders
34 * unconditionally. The opposite shape — a screen holding
35 * `var showXDialog by remember { mutableStateOf(false) }` (or a nullable
36 * `pending…` / `…Target` state) and rendering a dialog only when that state
37 * says so — hides a screen change inside a composable, so it is flagged here.
38 *
39 * What is flagged, deliberately narrowly (precision over recall):
40 * - a call to `AlertDialog`, `Dialog`, `ModalBottomSheet` or `ConfirmDialog`
41 * (the library's dialog primitives), or to any composable whose simple
42 * name ends in `Dialog` (the app's own dialog composables, e.g.
43 * `RenameTagDialog`), when the call is *gated* by local remember-state:
44 * it sits inside an `if` / `when` whose condition mentions a
45 * `remember`/`rememberSaveable` state property of the same file, or inside
46 * a `state?.let { … }` / qualified `let` on such a property. Route
47 * constructions (`backStack.add(Route.XDialog(...))`) are navigation, not
48 * invocations, and are never flagged.
49 * - one level of indirection: a dialog primitive inside a helper composable
50 * of the same file is flagged when every fact above holds for the helper's
51 * own call sites — e.g. a private `Custom…Dialog` in a screen file that is
52 * only ever invoked under `if (showCustomDialog)`. The helper's gated call
53 * site is flagged too.
54 *
55 * What is never flagged:
56 * - dialog *definitions*: files under `ui/dialogs/` (their internal
57 * text-field / wheel state is dialog-local and stays), and the shared
58 * library (`com.vayunmathur.library.*`), which builds the primitives.
59 * - unconditional dialog calls — a `DialogPage()` route entry rendering its
60 * dialog content, or a dialog host invoked straight from such an entry.
61 * Being shown is decided by the back stack, not by remembered state.
62 * - menus, dropdowns and other in-screen sub-state: only dialog calls match.
63 * - non-`src/main` sources (screenshot captures, tests).
64 *
65 * A dialog that genuinely cannot be a route yet (a multi-step flow whose
66 * intermediate state has no route/result shape) opts out per file with:
67 * `// DIALOG LOCAL EXCEPTION: <reason>` — the shape is validated by
68 * [ExceptionMarkerFormatDetector].
69 */
70class DialogAsRouteDetector : Detector(), SourceCodeScanner {
71
72 override fun getApplicableUastTypes(): List<Class<out UElement>> =
73 listOf(UFile::class.java)
74
75 override fun createUastHandler(context: JavaContext): UElementHandler =
76 object : UElementHandler() {
77 override fun visitFile(node: UFile) {
78 val packageName = node.packageName
79 if (packageName.isEmpty()) return
80 if (!packageName.startsWith(APP_PACKAGE_PREFIX)) return
81 if (ExceptionMarkerFormatDetector.isLintRulesPackage(packageName)) return
82 if (LintPackageExclusions.isExcluded(packageName)) return
83 if (isLibraryPackage(packageName)) return
84
85 val file = context.file ?: return
86 if (!isMainSource(file)) return
87 if (isDialogDefinitionFile(file)) return
88
89 val ktFile = node.sourcePsi as? KtFile ?: return
90 if (CommentOnlyMatcher.containsMarkerInComments(ktFile, EXCEPTION_MARKER)) return
91
92 val stateVars = stateProperties(ktFile)
93 if (stateVars.isEmpty()) return
94
95 val calls = mutableListOf<KtCallExpression>()
96 ktFile.accept(object : PsiRecursiveElementVisitor() {
97 override fun visitElement(element: PsiElement) {
98 super.visitElement(element)
99 if (element is KtCallExpression) calls += element
100 }
101 })
102
103 for (call in calls) {
104 val name = simpleCalleeName(call) ?: continue
105 if (!isDialogCall(call, name)) continue
106 val gated = isGated(call, stateVars) ||
107 isGatedViaEnclosingFunction(call, calls, stateVars)
108 if (!gated) continue
109 context.report(
110 ISSUE,
111 node,
112 Location.create(
113 file,
114 ktFile.text,
115 call.textRange.startOffset,
116 call.textRange.endOffset,
117 ),
118 "Dialog `$name` is gated by local remember-state here; dialogs are routes. " +
119 "Add a dialog destination (a `Route.…Dialog` entry with `DialogPage()` " +
120 "metadata, its arguments in the route, its content stateless under " +
121 "`ui/dialogs/`) and push it from the click handler instead of holding " +
122 "`show…` / pending-target state in the screen. Definitions under " +
123 "`ui/dialogs/` and unconditional route-entry hosts are not flagged. " +
124 "A flow that genuinely cannot be a route yet opts out per file with " +
125 "`$EXCEPTION_MARKER <reason>`.",
126 )
127 }
128 }
129 }
130
131 /** Names of `remember`/`rememberSaveable` state properties declared in [ktFile]. */
132 private fun stateProperties(ktFile: KtFile): Set<String> {
133 val names = mutableSetOf<String>()
134 ktFile.accept(object : PsiRecursiveElementVisitor() {
135 override fun visitElement(element: PsiElement) {
136 super.visitElement(element)
137 if (element !is KtProperty) return
138 val delegate = element.delegateExpression?.text.orEmpty()
139 val initializer = element.initializer?.text.orEmpty()
140 val holdsState = (delegate.contains("remember") || initializer.contains("remember")) &&
141 (delegate.contains("mutableState") || initializer.contains("mutableState"))
142 if (holdsState) element.name?.let { names += it }
143 }
144 })
145 return names
146 }
147
148 /** Simple callee name: `AlertDialog`, or `AddGroupDialog` for `foo.AddGroupDialog(...)`. */
149 private fun simpleCalleeName(call: KtCallExpression): String? {
150 val callee = call.calleeExpression ?: return null
151 val text = callee.text.substringBefore('<').trim()
152 return text.substringAfterLast('.').takeIf { it.isNotEmpty() }
153 }
154
155 private fun isDialogCall(call: KtCallExpression, name: String): Boolean {
156 // Route constructions are navigation targets, not dialog invocations.
157 val calleeText = call.calleeExpression?.text.orEmpty()
158 if (calleeText.startsWith("Route.") || calleeText.contains(".Route.")) return false
159 if (name in DIRECT_DIALOG_CALLS) return true
160 return name.endsWith(DIALOG_SUFFIX) && name.length > DIALOG_SUFFIX.length
161 }
162
163 /**
164 * True when [element] is lexically gated by one of [stateVars]: an
165 * enclosing `if`/`when` condition mentions the variable, or the element
166 * sits in the selector of a qualified expression (`state?.let { … }`)
167 * whose receiver mentions it. The walk stops at the enclosing function.
168 */
169 private fun isGated(element: PsiElement, stateVars: Set<String>): Boolean {
170 var current: PsiElement? = element.parent
171 while (current != null && current !is KtNamedFunction && current !is KtFile) {
172 when (current) {
173 is KtIfExpression ->
174 if (mentionsAny(current.condition?.text, stateVars)) return true
175 is KtWhenExpression ->
176 if (mentionsAny(current.subjectExpression?.text, stateVars)) return true
177 is KtQualifiedExpression -> {
178 // Only the selector side is gated by the receiver; the
179 // receiver expression itself is not.
180 if (current.selectorExpression != null &&
181 isAncestorOf(current.selectorExpression!!, element) &&
182 mentionsAny(current.receiverExpression.text, stateVars)
183 ) return true
184 }
185 }
186 current = current.parent
187 }
188 return false
189 }
190
191 /**
192 * One level of indirection: [call] sits inside a function whose own call
193 * sites (elsewhere in the file) are gated by remember-state — the shape of
194 * a private `Custom…Dialog` helper invoked only under `if (show…)`.
195 */
196 private fun isGatedViaEnclosingFunction(
197 call: KtCallExpression,
198 allCalls: List<KtCallExpression>,
199 stateVars: Set<String>,
200 ): Boolean {
201 var current: PsiElement? = call.parent
202 var enclosing: KtNamedFunction? = null
203 while (current != null && current !is KtFile) {
204 if (current is KtNamedFunction) {
205 enclosing = current
206 break
207 }
208 current = current.parent
209 }
210 val function = enclosing ?: return false
211 val functionName = function.name ?: return false
212 return allCalls.any { site ->
213 site != call &&
214 !isAncestorOf(function, site) &&
215 simpleCalleeName(site) == functionName &&
216 isGated(site, stateVars)
217 }
218 }
219
220 private fun isAncestorOf(ancestor: PsiElement, element: PsiElement): Boolean {
221 var current: PsiElement? = element
222 while (current != null) {
223 if (current == ancestor) return true
224 current = current.parent
225 }
226 return false
227 }
228
229 private fun mentionsAny(text: String?, stateVars: Set<String>): Boolean {
230 if (text.isNullOrEmpty()) return false
231 return stateVars.any { name ->
232 Regex("""(?<![A-Za-z0-9_])${Regex.escape(name)}(?![A-Za-z0-9_])""").containsMatchIn(text)
233 }
234 }
235
236 private fun isMainSource(file: File): Boolean {
237 val path = file.path.replace('\\', '/')
238 if (!path.contains("/src/")) return true
239 return path.contains("/src/main/")
240 }
241
242 private fun isDialogDefinitionFile(file: File): Boolean =
243 file.path.replace('\\', '/').contains("/ui/dialogs/")
244
245 companion object {
246 private const val APP_PACKAGE_PREFIX = "com.vayunmathur."
247 private const val LIBRARY_PREFIX = "com.vayunmathur.library"
248 private const val DIALOG_SUFFIX = "Dialog"
249
250 const val EXCEPTION_MARKER = "// DIALOG LOCAL EXCEPTION:"
251
252 private val DIRECT_DIALOG_CALLS = setOf(
253 "AlertDialog",
254 "Dialog",
255 "ModalBottomSheet",
256 "ConfirmDialog",
257 )
258
259 private fun isLibraryPackage(packageName: String): Boolean =
260 packageName == LIBRARY_PREFIX || packageName.startsWith("$LIBRARY_PREFIX.")
261
262 val ISSUE: Issue = Issue.create(
263 id = "DialogAsRoute",
264 briefDescription = "Dialog gated by local remember-state; dialogs are navigation routes",
265 explanation = """
266 A dialog is a navigation destination: a `Route.…Dialog` entry with \
267 `DialogPage()` metadata, the identity it acts on in the route arguments, \
268 and a stateless dialog composable under `ui/dialogs/` that the entry \
269 renders unconditionally (the communicate `DeleteConversationDialog` \
270 shape). Rendering `AlertDialog`, `Dialog`, `ModalBottomSheet`, \
271 `ConfirmDialog`, or an app dialog composable (a call whose name ends in \
272 `Dialog`) only when a `remember`/`rememberSaveable` state property of \
273 the same file says so — an `if (show…)` block, a `pending…?.let { … }`, \
274 or a same-file helper only ever invoked under such a gate — hides a \
275 screen change inside a composable and is flagged here.
276
277 Dialog definitions under `ui/dialogs/`, unconditional route-entry \
278 hosts, route constructions (`backStack.add(Route.…Dialog(...))`), \
279 menus/dropdowns and other in-screen sub-state, and non-`src/main` \
280 sources are not flagged. A multi-step flow that genuinely cannot be \
281 a route yet opts out per file with \
282 `// DIALOG LOCAL EXCEPTION: <reason>`.
283 """.trimIndent(),
284 category = Category.CORRECTNESS,
285 priority = 6,
286 severity = Severity.ERROR,
287 implementation = Implementation(
288 DialogAsRouteDetector::class.java,
289 Scope.JAVA_FILE_SCOPE,
290 ),
291 )
292 }
293}