code: add an in-process diagnostics engine with squiggles, gutter markers and a problems panel
- Commit
d0a6a609e12da047aa14f28489a978fcc7d64f79- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-07 03:12 UTC (4 months ago)
- Parents
7ee1bc4
Diff
code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt b/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.ktindex d71c382f83..1fcd43f12f 100644--- a/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt@@ -1,5 +1,7 @@ package com.vayunmathur.code.ui +import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -19,6 +21,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextLayoutResult@@ -32,6 +35,8 @@ import com.vayunmathur.code.syntax.SyntaxTransformation import com.vayunmathur.code.syntax.rememberSyntaxColors import com.vayunmathur.code.util.CodeActions import com.vayunmathur.code.util.Completion+import com.vayunmathur.code.util.Diagnostic+import com.vayunmathur.code.util.DiagnosticSeverity import com.vayunmathur.code.util.TabUiState import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.MaterialTheme@@ -57,6 +62,7 @@ fun CodeEditor( completions: List<Completion> = emptyList(), showCompletions: Boolean = false, editorTheme: String = com.vayunmathur.code.syntax.EditorThemes.DEFAULT,+ diagnostics: List<Diagnostic> = emptyList(), /** True when this is the secondary split pane, so focus routes shared actions there. */ secondaryPane: Boolean = false, /** When set, edits route here instead of [CodeActions.onEditorChange] (used by the second pane). */@@ -148,7 +154,7 @@ fun CodeEditor( var layoutResult by remember { mutableStateOf<TextLayoutResult?>(null) } Row(Modifier.fillMaxSize()) {- LineGutter(lineCount, verticalScroll, editorStyle)+ LineGutter(lineCount, verticalScroll, editorStyle, diagnostics) Box(Modifier.weight(1f).fillMaxHeight()) { BasicTextField( value = tab.value,@@ -187,20 +193,51 @@ fun CodeEditor( /** * The line-number column. Rendered as a single right-aligned [Text] (one number per line) so * it stays cheap for large files, and sharing [verticalScroll] keeps it locked to the editor.+ * A thin overlay [Canvas] draws a severity dot beside any line with [diagnostics] (inline squiggles+ * on a [BasicTextField] are impractical, so the classic editor shows gutter markers only). * With soft-wrap on, wrapped lines shift the text below their number — an accepted trade-off. */ @Composable-private fun LineGutter(lineCount: Int, verticalScroll: androidx.compose.foundation.ScrollState, style: TextStyle) {+private fun LineGutter(+ lineCount: Int,+ verticalScroll: androidx.compose.foundation.ScrollState,+ style: TextStyle,+ diagnostics: List<Diagnostic> = emptyList(),+) { val numbers = remember(lineCount) { (1..lineCount).joinToString("\n") } val width = (lineCount.toString().length * 10 + 16).dp- Text(- text = numbers,- modifier = Modifier- .verticalScroll(verticalScroll)- .width(width)- .padding(horizontal = 4.dp),- style = style,- color = MaterialTheme.colorScheme.onSurfaceVariant,- textAlign = TextAlign.Right,- )+ val density = LocalDensity.current+ val lineHeightPx = with(density) { style.lineHeight.toPx() }+ val byLine = remember(diagnostics) { diagnostics.groupBy { it.line } }+ val errorColor = MaterialTheme.colorScheme.error+ val warningColor = Color(0xFFFFB300)+ val infoColor = MaterialTheme.colorScheme.onSurfaceVariant+ Box(Modifier.width(width)) {+ Text(+ text = numbers,+ modifier = Modifier+ .verticalScroll(verticalScroll)+ .fillMaxHeight()+ .padding(horizontal = 4.dp),+ style = style,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ textAlign = TextAlign.Right,+ )+ if (byLine.isNotEmpty() && lineHeightPx > 0f) {+ Canvas(Modifier.matchParentSize()) {+ val scroll = verticalScroll.value.toFloat()+ for ((line, ds) in byLine) {+ val worst = ds.minByOrNull { it.severity.ordinal } ?: continue+ val cy = line * lineHeightPx - scroll + lineHeightPx / 2f+ if (cy < -lineHeightPx || cy > size.height + lineHeightPx) continue+ val color = when (worst.severity) {+ DiagnosticSeverity.ERROR -> errorColor+ DiagnosticSeverity.WARNING -> warningColor+ DiagnosticSeverity.INFO -> infoColor+ }+ drawCircle(color, radius = 3f, center = androidx.compose.ui.geometry.Offset(4f, cy))+ }+ }+ }+ } }
code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt b/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.ktindex 37e60e5f02..541b977b3e 100644--- a/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt@@ -57,6 +57,8 @@ import com.vayunmathur.code.syntax.SyntaxColors import com.vayunmathur.code.syntax.rememberSyntaxColors import com.vayunmathur.code.util.CodeActions import com.vayunmathur.code.util.Completion+import com.vayunmathur.code.util.Diagnostic+import com.vayunmathur.code.util.DiagnosticSeverity import com.vayunmathur.code.util.Edit import com.vayunmathur.code.util.EditorDocument import com.vayunmathur.code.util.TabUiState@@ -94,6 +96,7 @@ fun CodeEditorView( initialQuery: String = "", completions: List<Completion> = emptyList(), showCompletions: Boolean = false,+ diagnostics: List<Diagnostic> = emptyList(), secondaryPane: Boolean = false, onValueChangeOverride: ((TextFieldValue) -> Unit)? = null, ) {@@ -105,6 +108,15 @@ fun CodeEditorView( val caretColor = MaterialTheme.colorScheme.primary val guideColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f) val extraCaretColor = MaterialTheme.colorScheme.tertiary+ val errorColor = MaterialTheme.colorScheme.error+ val warningColor = Color(0xFFFFB300)+ val infoColor = gutterColor+ fun severityColor(s: DiagnosticSeverity): Color = when (s) {+ DiagnosticSeverity.ERROR -> errorColor+ DiagnosticSeverity.WARNING -> warningColor+ DiagnosticSeverity.INFO -> infoColor+ }+ val diagnosticsByLine = remember(diagnostics) { diagnostics.groupBy { it.line } } val spec = tab.language.spec val measurer = rememberTextMeasurer()@@ -449,6 +461,21 @@ fun CodeEditorView( drawRect(extraCaretColor, topLeft = Offset(cx, y), size = Size(2f, lineHeight)) } }++ // Diagnostics: squiggly underline per range + a severity dot in the gutter.+ diagnosticsByLine[source]?.let { diags ->+ for (d in diags) {+ val a = d.startCol.coerceIn(0, lineLen)+ val b = (if (d.endCol > d.startCol) d.endCol else lineLen).coerceIn(a + 1, (lineLen + 1))+ val ax = gutterWidth + a * charWidth - scrollX+ val bx = gutterWidth + b * charWidth - scrollX+ drawSquiggle(ax, bx, y + lineHeight - 1f, severityColor(d.severity))+ }+ val worst = diags.minByOrNull { it.severity.ordinal }+ if (worst != null) {+ drawCircle(severityColor(worst.severity), radius = 3f, center = Offset(12f, y + lineHeight / 2f))+ }+ } } } else { // ---- Soft-wrap draw path: one measured layout per visible source line. ----@@ -523,6 +550,22 @@ fun CodeEditorView( drawRect(extraCaretColor, topLeft = Offset(gutterWidth + rect.left, lineTop + rect.top), size = Size(2f, rect.height)) } }++ // Diagnostics: highlight the range (wrapped) + a gutter severity dot.+ diagnosticsByLine[source]?.let { diags ->+ for (d in diags) {+ val a = d.startCol.coerceIn(0, lineLen)+ val b = (if (d.endCol > d.startCol) d.endCol else lineLen).coerceIn(a + 1, lineLen + 1).coerceAtMost(lineLen)+ if (b > a) {+ val path = layout.getPathForRange(a, b).apply { translate(Offset(gutterWidth, lineTop)) }+ drawPath(path, severityColor(d.severity).copy(alpha = 0.20f))+ }+ }+ val worst = diags.minByOrNull { it.severity.ordinal }+ if (worst != null) {+ drawCircle(severityColor(worst.severity), radius = 3f, center = Offset(12f, lineTop + lineHeight / 2f))+ }+ } } } }@@ -850,4 +893,27 @@ private fun selectionOrWord(text: String, selection: TextRange): Pair<Int, Int>? private fun Char.isJavaIdentifierChar(): Boolean = isLetterOrDigit() || this == '_' +/** Draws a zigzag ("squiggle") underline from [ax] to [bx] at baseline [yBase]. */+private fun androidx.compose.ui.graphics.drawscope.DrawScope.drawSquiggle(+ ax: Float,+ bx: Float,+ yBase: Float,+ color: Color,+) {+ if (bx <= ax) return+ val step = 3f+ val amp = 2f+ var x = ax+ var prev = Offset(ax, yBase)+ var up = false+ while (x < bx) {+ val nx = (x + step).coerceAtMost(bx)+ val ny = if (up) yBase - amp else yBase+ drawLine(color, prev, Offset(nx, ny), strokeWidth = 1f)+ prev = Offset(nx, ny)+ x = nx+ up = !up+ }+}+ private const val MAX_LINE_HIGHLIGHT = 2000
code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.ktindex df4467574d..4de95b1b52 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -151,6 +151,7 @@ fun EditorScreen( var showPalette by remember { mutableStateOf(false) } var showOutline by remember { mutableStateOf(false) } var showMergeResolver by remember { mutableStateOf(false) }+ var showProblems by remember { mutableStateOf(false) } var showExitGuard by remember { mutableStateOf(false) } val anyDirty = state.tabs.any { it.isDirty } @@ -240,6 +241,7 @@ fun EditorScreen( onOpenPalette = { showPalette = true }, onOpenOutline = { showOutline = true }, onResolveConflicts = { showMergeResolver = true },+ onOpenProblems = { showProblems = true }, ) HorizontalDivider() if (tab.changedOnDisk) {@@ -279,6 +281,7 @@ fun EditorScreen( initialQuery = initialFind.orEmpty(), completions = state.completions, showCompletions = state.showCompletions,+ diagnostics = state.diagnostics, ) } else { CodeEditor(@@ -293,6 +296,7 @@ fun EditorScreen( completions = state.completions, showCompletions = state.showCompletions, editorTheme = state.editorTheme,+ diagnostics = state.diagnostics, ) } }@@ -324,6 +328,7 @@ fun EditorScreen( }, onOutline = { showOutline = true }, onResolveConflicts = { showMergeResolver = true },+ onProblems = { showProblems = true }, onOpenSearch = onOpenSearch, onOpenGit = onOpenGit, onOpenTerminal = onOpenTerminal,@@ -367,6 +372,20 @@ fun EditorScreen( onDismiss = { showMergeResolver = false }, ) }+ if (showProblems) {+ FuzzyPickerDialog(+ title = stringResource(R.string.problems),+ placeholder = stringResource(R.string.problems),+ items = state.diagnostics.map { d ->+ PickerItem(+ primary = d.message,+ secondary = "${d.severity.name.lowercase()} \u00B7 ${d.line + 1}",+ matchKey = d.message,+ ) { actions.goToLine(d.line + 1) }+ },+ onDismiss = { showProblems = false },+ )+ } if (showExitGuard) { AlertDialog( onDismissRequest = { showExitGuard = false },@@ -451,6 +470,7 @@ private fun SplitEditors( showCompletions = state.showCompletions && !focusSecondary, editorTheme = state.editorTheme, secondaryPane = false,+ diagnostics = state.diagnostics, ) } }@@ -583,6 +603,7 @@ private fun EditorToolbar( onOpenPalette: () -> Unit = {}, onOpenOutline: () -> Unit = {}, onResolveConflicts: () -> Unit = {},+ onOpenProblems: () -> Unit = {}, ) { val tab = state.activeTab ?: return Row(@@ -616,9 +637,21 @@ private fun EditorToolbar( Item(text = stringResource(R.string.preview)) { onOpenPreview() } Item(text = stringResource(R.string.format_document)) { actions.formatDocument() } Item(text = stringResource(R.string.resolve_conflicts)) { onResolveConflicts() }+ Item(text = stringResource(R.string.problems)) { onOpenProblems() } Item(text = stringResource(R.string.split_view)) { actions.toggleSplit() } } Spacer(Modifier.width(8.dp))+ if (state.diagnostics.isNotEmpty()) {+ val errorColor = MaterialTheme.colorScheme.error+ val warnColor = Color(0xFFFFB300)+ TextButton(onClick = onOpenProblems) {+ Text(+ text = "\u26A0 ${state.errorCount}/${state.warningCount}",+ color = if (state.errorCount > 0) errorColor else warnColor,+ style = MaterialTheme.typography.labelMedium,+ )+ }+ } Text( text = tab.language.label, color = MaterialTheme.colorScheme.onSurfaceVariant,@@ -692,6 +725,7 @@ private fun editorCommands( onQuickOpen: () -> Unit, onOutline: () -> Unit, onResolveConflicts: () -> Unit,+ onProblems: () -> Unit, onOpenSearch: () -> Unit, onOpenGit: () -> Unit, onOpenTerminal: () -> Unit,@@ -713,6 +747,7 @@ private fun editorCommands( PickerItem(stringResource(R.string.delete_line)) { actions.deleteLine() }, PickerItem(stringResource(R.string.format_document)) { actions.formatDocument() }, PickerItem(stringResource(R.string.resolve_conflicts)) { onResolveConflicts() },+ PickerItem(stringResource(R.string.problems)) { onProblems() }, PickerItem(stringResource(R.string.split_view)) { actions.toggleSplit() }, PickerItem(stringResource(R.string.soft_wrap)) { actions.toggleSoftWrap() }, PickerItem(stringResource(R.string.undo)) { actions.undo() },
code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.ktindex a2de6bec5b..2234b77480 100644--- a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt+++ b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt@@ -92,10 +92,15 @@ data class CodeUiState( val projectFiles: List<ProjectFileEntry> = emptyList(), /** Most-recently-opened files, newest first, shown in quick-open when the query is empty. */ val recentFiles: List<ProjectFileEntry> = emptyList(),+ /** Diagnostics for the current tab (squiggles, gutter markers, problems panel). */+ val diagnostics: List<Diagnostic> = emptyList(), ) { val currentTab: TabUiState? get() = tabs.getOrNull(currentIndex) val secondaryTab: TabUiState? get() = tabs.getOrNull(secondaryIndex) + val errorCount: Int get() = diagnostics.count { it.severity == DiagnosticSeverity.ERROR }+ val warningCount: Int get() = diagnostics.count { it.severity == DiagnosticSeverity.WARNING }+ /** The tab the shared toolbar/find/navigation act on: the focused split pane's tab. */ val activeTab: TabUiState? get() = if (focusedSecondary) secondaryTab ?: currentTab else currentTab }
code/src/main/java/com/vayunmathur/code/util/Diagnostics.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/Diagnostics.kt b/code/src/main/java/com/vayunmathur/code/util/Diagnostics.ktnew file mode 100644index 0000000000..79213357d2--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/Diagnostics.kt@@ -0,0 +1,269 @@+package com.vayunmathur.code.util++import com.vayunmathur.code.syntax.Language+import org.json.JSONArray+import org.json.JSONObject+import org.xml.sax.InputSource+import org.xml.sax.SAXParseException+import java.io.StringReader+import javax.xml.parsers.DocumentBuilderFactory++/** Diagnostic severity, ordered most→least severe for sorting and gutter colouring. */+enum class DiagnosticSeverity { ERROR, WARNING, INFO }++/**+ * One diagnostic on a single [line] (0-based), spanning columns `[startCol, endCol)` (0-based).+ * A zero-width range ([startCol] == [endCol]) marks a whole-line issue.+ */+data class Diagnostic(+ val line: Int,+ val startCol: Int,+ val endCol: Int,+ val severity: DiagnosticSeverity,+ val message: String,+)++private const val MAX_DIAGNOSTICS = 200++/**+ * In-process, offline diagnostics — a lightweight stand-in for a language server (which cannot run+ * on-device; see the plan). It composes several pure validators: unresolved merge-conflict markers+ * (all languages, via [parseConflicts]), JSON / XML well-formedness, a couple of YAML sanity checks,+ * bracket balance for brace languages, and TODO/FIXME notes. Everything except JSON (`org.json`) and+ * XML (`javax.xml`) is pure Kotlin, so the core is unit-tested directly.+ */+fun computeDiagnostics(text: String, language: Language): List<Diagnostic> {+ if (text.isEmpty()) return emptyList()+ val out = ArrayList<Diagnostic>()++ out += mergeMarkerDiagnostics(text)+ when (language) {+ Language.JSON -> out += jsonDiagnostics(text)+ Language.XML -> out += xmlDiagnostics(text)+ Language.YAML -> out += yamlDiagnostics(text)+ else -> {}+ }+ if (language in BRACE_LANGUAGES) out += bracketDiagnostics(text, language)+ out += todoDiagnostics(text)++ return out.asSequence()+ .sortedWith(compareBy({ it.line }, { it.startCol }, { it.severity.ordinal }))+ .take(MAX_DIAGNOSTICS)+ .toList()+}++// ---- Merge markers ----++private fun mergeMarkerDiagnostics(text: String): List<Diagnostic> =+ parseConflicts(text).map { conflict ->+ val lines = text.split("\n")+ val marker = lines.getOrNull(conflict.startLine).orEmpty()+ Diagnostic(+ line = conflict.startLine,+ startCol = 0,+ endCol = marker.length,+ severity = DiagnosticSeverity.ERROR,+ message = "Unresolved merge conflict",+ )+ }++// ---- JSON ----++private fun jsonDiagnostics(text: String): List<Diagnostic> {+ val trimmed = text.trimStart()+ if (trimmed.isEmpty()) return emptyList()+ val result = runCatching {+ if (trimmed.startsWith("[")) JSONArray(text) else JSONObject(text)+ }+ val error = result.exceptionOrNull() ?: return emptyList()+ val message = error.message ?: "Invalid JSON"+ // org.json reports the failing offset as "... at character N ...".+ val offset = Regex("character (\\d+)").find(message)?.groupValues?.get(1)?.toIntOrNull()+ val (line, col) = if (offset != null) offsetToLineCol(text, offset) else 0 to 0+ return listOf(Diagnostic(line, col, col, DiagnosticSeverity.ERROR, message.substringBefore(" at ").ifBlank { "Invalid JSON" }))+}++// ---- XML ----++private fun xmlDiagnostics(text: String): List<Diagnostic> {+ val head = text.trimStart().take(64).lowercase()+ // HTML isn't required to be well-formed XML; don't flag it.+ if (head.startsWith("<!doctype html") || head.startsWith("<html")) return emptyList()+ if (text.isBlank()) return emptyList()++ val factory = DocumentBuilderFactory.newInstance()+ runCatching { factory.setFeature("http://xml.org/sax/features/external-general-entities", false) }+ runCatching { factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false) }+ val error = runCatching {+ val builder = factory.newDocumentBuilder()+ builder.setErrorHandler(null)+ builder.parse(InputSource(StringReader(text)))+ }.exceptionOrNull() ?: return emptyList()++ return if (error is SAXParseException) {+ val line = (error.lineNumber - 1).coerceAtLeast(0)+ val col = (error.columnNumber - 1).coerceAtLeast(0)+ listOf(Diagnostic(line, col, col, DiagnosticSeverity.ERROR, error.message ?: "Malformed XML"))+ } else {+ listOf(Diagnostic(0, 0, 0, DiagnosticSeverity.ERROR, error.message ?: "Malformed XML"))+ }+}++// ---- YAML ----++private fun yamlDiagnostics(text: String): List<Diagnostic> {+ val out = ArrayList<Diagnostic>()+ text.split("\n").forEachIndexed { i, line ->+ // YAML forbids tabs for indentation.+ val leading = line.takeWhile { it == ' ' || it == '\t' }+ val tab = leading.indexOf('\t')+ if (tab >= 0) {+ out.add(Diagnostic(i, tab, tab + 1, DiagnosticSeverity.ERROR, "YAML does not allow tabs for indentation"))+ }+ }+ return out+}++// ---- Bracket balance ----++private val BRACE_LANGUAGES = setOf(+ Language.KOTLIN, Language.JAVA, Language.JAVASCRIPT, Language.TYPESCRIPT,+ Language.C, Language.CPP, Language.GO, Language.CSS,+)++private val OPEN_TO_CLOSE = mapOf('(' to ')', '[' to ']', '{' to '}')++private class OpenBracket(val ch: Char, val line: Int, val col: Int)++/**+ * String/comment-aware bracket balance for brace languages. Skips `//` line comments (except CSS),+ * `/* */` blocks, and `"`, `'`, `` ` `` and `"""` string forms so brackets inside them don't count.+ */+private fun bracketDiagnostics(text: String, language: Language): List<Diagnostic> {+ val allowLineComment = language != Language.CSS+ val out = ArrayList<Diagnostic>()+ val stack = ArrayDeque<OpenBracket>()++ var line = 0+ var lineStart = 0+ var i = 0+ val n = text.length+ while (i < n) {+ val c = text[i]+ if (c == '\n') {+ line+++ lineStart = i + 1+ i+++ continue+ }+ val col = i - lineStart++ // Comments.+ if (allowLineComment && c == '/' && i + 1 < n && text[i + 1] == '/') {+ val nl = text.indexOf('\n', i)+ i = if (nl < 0) n else nl+ continue+ }+ if (c == '/' && i + 1 < n && text[i + 1] == '*') {+ val close = text.indexOf("*/", i + 2)+ if (close < 0) { i = n } else {+ // advance line/lineStart across the block comment+ var k = i+ while (k < close + 2) { if (text[k] == '\n') { line++; lineStart = k + 1 }; k++ }+ i = close + 2+ }+ continue+ }++ // Strings.+ when (c) {+ '"' -> {+ if (i + 2 < n && text[i + 1] == '"' && text[i + 2] == '"') {+ i = skipTriple(text, i + 3) { if (text[it] == '\n') { line++; lineStart = it + 1 } }+ } else {+ i = skipString(text, i + 1, '"') { if (text[it] == '\n') { line++; lineStart = it + 1 } }+ }+ continue+ }+ '\'' -> { i = skipString(text, i + 1, '\'') { if (text[it] == '\n') { line++; lineStart = it + 1 } }; continue }+ '`' -> { i = skipString(text, i + 1, '`') { if (text[it] == '\n') { line++; lineStart = it + 1 } }; continue }+ }++ // Brackets.+ if (c in OPEN_TO_CLOSE) {+ stack.addLast(OpenBracket(c, line, col))+ } else if (c == ')' || c == ']' || c == '}') {+ val top = stack.lastOrNull()+ if (top == null || OPEN_TO_CLOSE[top.ch] != c) {+ out.add(Diagnostic(line, col, col + 1, DiagnosticSeverity.ERROR, "Unmatched '$c'"))+ } else {+ stack.removeLast()+ }+ }+ i+++ }+ for (open in stack.take(5)) {+ out.add(Diagnostic(open.line, open.col, open.col + 1, DiagnosticSeverity.WARNING, "Unclosed '${open.ch}'"))+ }+ return out+}++/** Advances past a `"..."`/`'...'`/`` `...` `` string starting at [from]; returns the index after it. */+private inline fun skipString(text: String, from: Int, quote: Char, onNewline: (Int) -> Unit): Int {+ var i = from+ val n = text.length+ while (i < n) {+ val c = text[i]+ if (c == '\\') { i += 2; continue }+ if (c == '\n') onNewline(i)+ if (c == quote) return i + 1+ i+++ }+ return n+}++/** Advances past a `"""..."""` triple-quoted string starting at [from]; returns the index after it. */+private inline fun skipTriple(text: String, from: Int, onNewline: (Int) -> Unit): Int {+ var i = from+ val n = text.length+ while (i < n) {+ if (text[i] == '"' && i + 2 < n && text[i + 1] == '"' && text[i + 2] == '"') return i + 3+ if (text[i] == '\n') onNewline(i)+ i+++ }+ return n+}++// ---- TODO / FIXME ----++private val TODO_REGEX = Regex("\\b(TODO|FIXME)\\b")++private fun todoDiagnostics(text: String): List<Diagnostic> {+ val out = ArrayList<Diagnostic>()+ text.split("\n").forEachIndexed { i, line ->+ val match = TODO_REGEX.find(line) ?: return@forEachIndexed+ out.add(+ Diagnostic(+ line = i,+ startCol = match.range.first,+ endCol = match.range.last + 1,+ severity = DiagnosticSeverity.INFO,+ message = match.value,+ ),+ )+ }+ return out+}++// ---- Shared ----++/** Maps a character [offset] in [text] to a 0-based (line, column) pair. */+private fun offsetToLineCol(text: String, offset: Int): Pair<Int, Int> {+ val safe = offset.coerceIn(0, text.length)+ var line = 0+ var lineStart = 0+ for (i in 0 until safe) {+ if (text[i] == '\n') { line++; lineStart = i + 1 }+ }+ return line to (safe - lineStart)+}
code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.ktindex aca50b9430..4388d3e200 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -198,6 +198,10 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), var showCompletions by mutableStateOf(false) private set + // ---- Diagnostics ----+ val diagnostics = mutableStateListOf<Diagnostic>()+ private var diagnosticsJob: Job? = null+ // ---- User snippets ---- val userSnippets = mutableStateListOf<UserSnippet>() @@ -286,6 +290,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), showMinimap = showMinimap, projectFiles = projectFiles.toList(), recentFiles = recentPaths.map { toProjectEntry(File(it)) },+ diagnostics = diagnostics.toList(), ) init {@@ -342,6 +347,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), } currentIndex = tabs.indexOfFirst { it.file?.absolutePath == current } .takeIf { it >= 0 } ?: if (tabs.isEmpty()) -1 else 0+ scheduleDiagnostics() } /** Persists the current set of file-backed tabs and the foreground tab for session restore. */@@ -550,12 +556,14 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), val existing = tabs.indexOfFirst { it.key == key } if (existing >= 0) { currentIndex = existing+ scheduleDiagnostics() return } viewModelScope.launch { tabs.add(makeFileTab(file)) currentIndex = tabs.lastIndex saveSession()+ scheduleDiagnostics() } } fun openExternal(uri: Uri) {@@ -628,6 +636,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), focusedSecondary = false dismissCompletions() saveSession()+ scheduleDiagnostics() } } @@ -671,6 +680,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), tab.value = processed if (autoSave) scheduleAutoSave() if (isPrimary) updateCompletions()+ scheduleDiagnostics() } /** Opens/closes the second editor pane, choosing an adjacent tab as the secondary. */@@ -725,6 +735,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), tab.value = TextFieldValue(newText, TextRange(newCaret)) dismissCompletions() if (autoSave) scheduleAutoSave()+ scheduleDiagnostics() } override fun dismissCompletions() {@@ -946,6 +957,25 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), if (new.text != tab.value.text) tab.pushUndo(tab.value) tab.value = new if (autoSave) scheduleAutoSave()+ scheduleDiagnostics()+ }++ /** Debounced off-main recompute of diagnostics for the current tab. */+ private fun scheduleDiagnostics() {+ diagnosticsJob?.cancel()+ val tab = currentTab+ if (tab == null) {+ diagnostics.clear()+ return+ }+ val text = tab.value.text+ val language = tab.language+ diagnosticsJob = viewModelScope.launch {+ delay(DIAGNOSTICS_DELAY_MS)+ val result = withContext(Dispatchers.Default) { computeDiagnostics(text, language) }+ diagnostics.clear()+ diagnostics.addAll(result)+ } } /** Applies a pure whole-line edit as a single undo step. */@@ -956,6 +986,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), tab.pushUndo(tab.value) tab.value = next if (autoSave) scheduleAutoSave()+ scheduleDiagnostics() } override fun toggleComment() {@@ -982,6 +1013,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), tab.pushUndo(tab.value) tab.value = TextFieldValue(formatted, TextRange(formatted.length)) if (autoSave) scheduleAutoSave()+ scheduleDiagnostics() } override fun resolveConflicts(resolutions: List<Resolution>) {@@ -991,6 +1023,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), tab.pushUndo(tab.value) tab.value = TextFieldValue(resolved, TextRange(resolved.length)) if (autoSave) scheduleAutoSave()+ scheduleDiagnostics() } /** Moves the caret to the start of [line] (1-based), without recording an undo step. */@@ -1130,6 +1163,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), tab.diskModified = loaded.modified tab.diskLength = loaded.length tab.changedOnDisk = false+ scheduleDiagnostics() } /** Inserts [insert] at the caret, replacing any current selection (used by the Tab button). */@@ -1397,6 +1431,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), private companion object { const val AUTO_SAVE_DELAY_MS = 1500L+ const val DIAGNOSTICS_DELAY_MS = 400L const val MIN_COMPLETION_PREFIX = 1 const val MAX_COMPLETIONS = 50 const val GIT_LOG_LIMIT = 30
code/src/main/res/values/strings.xml
diff --git a/code/src/main/res/values/strings.xml b/code/src/main/res/values/strings.xmlindex dfde0c1a71..31ed902569 100644--- a/code/src/main/res/values/strings.xml+++ b/code/src/main/res/values/strings.xml@@ -137,4 +137,6 @@ <string name="show_minimap_desc">Show a code overview beside the experimental editor</string> <string name="fold_all">Fold all</string> <string name="unfold_all">Unfold all</string>+ <string name="problems">Problems</string>+ <string name="no_problems">No problems detected.</string> </resources>
code/src/test/java/com/vayunmathur/code/util/DiagnosticsTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/DiagnosticsTest.kt b/code/src/test/java/com/vayunmathur/code/util/DiagnosticsTest.ktnew file mode 100644index 0000000000..63ba3af6a0--- /dev/null+++ b/code/src/test/java/com/vayunmathur/code/util/DiagnosticsTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.code.util++import com.vayunmathur.code.syntax.Language+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Unit tests for the pure diagnostics validators. JSON is validated via `org.json`, which is only+ * available on-device (stubbed in JVM unit tests), so it is exercised manually rather than here.+ */+class DiagnosticsTest {++ @Test+ fun mergeConflictMarkersAreErrors() {+ val text = "a\n<<<<<<< HEAD\nx\n=======\ny\n>>>>>>> other\nb"+ val diags = computeDiagnostics(text, Language.PLAINTEXT)+ assertEquals(1, diags.count { it.severity == DiagnosticSeverity.ERROR })+ assertEquals(1, diags.first().line)+ assertTrue(diags.first().message.contains("merge"))+ }++ @Test+ fun todoAndFixmeAreInfo() {+ val text = "line one\n// TODO clean up\n// FIXME later"+ val diags = computeDiagnostics(text, Language.PLAINTEXT)+ val infos = diags.filter { it.severity == DiagnosticSeverity.INFO }+ assertEquals(listOf("TODO", "FIXME"), infos.map { it.message })+ assertEquals(listOf(1, 2), infos.map { it.line })+ }++ @Test+ fun yamlTabIndentationIsError() {+ val text = "root:\n\tchild: 1"+ val diags = computeDiagnostics(text, Language.YAML)+ val err = diags.single { it.severity == DiagnosticSeverity.ERROR }+ assertEquals(1, err.line)+ assertEquals(0, err.startCol)+ }++ @Test+ fun balancedBracketsProduceNoDiagnostics() {+ val diags = computeDiagnostics("fun f() { val a = x[0] }", Language.KOTLIN)+ assertTrue(diags.isEmpty(), "expected no diagnostics, got $diags")+ }++ @Test+ fun unmatchedCloserIsError() {+ val diags = computeDiagnostics("fun f() { )", Language.KOTLIN)+ assertTrue(diags.any { it.severity == DiagnosticSeverity.ERROR && it.message.contains(")") })+ }++ @Test+ fun unclosedOpenerIsWarning() {+ val diags = computeDiagnostics("fun f( {", Language.KOTLIN)+ assertTrue(diags.any { it.severity == DiagnosticSeverity.WARNING })+ }++ @Test+ fun bracketsInsideStringsAreIgnored() {+ val diags = computeDiagnostics("val s = \"a ( b [ c\"", Language.KOTLIN)+ assertTrue(diags.none { it.severity != DiagnosticSeverity.INFO }, "got $diags")+ }++ @Test+ fun bracketsInsideLineCommentsAreIgnored() {+ val diags = computeDiagnostics("val x = 1 // )]}\n", Language.KOTLIN)+ assertTrue(diags.isEmpty(), "got $diags")+ }++ @Test+ fun bracketsInsideBlockCommentsAreIgnored() {+ val diags = computeDiagnostics("/* ( [ { */\nval y = 2", Language.KOTLIN)+ assertTrue(diags.isEmpty(), "got $diags")+ }++ @Test+ fun wellFormedXmlHasNoDiagnostics() {+ val diags = computeDiagnostics("<root><child/></root>", Language.XML)+ assertTrue(diags.isEmpty(), "got $diags")+ }++ @Test+ fun malformedXmlIsReported() {+ val diags = computeDiagnostics("<root><child></root>", Language.XML)+ assertTrue(diags.any { it.severity == DiagnosticSeverity.ERROR })+ }++ @Test+ fun htmlIsNotFlaggedAsMalformedXml() {+ val diags = computeDiagnostics("<!DOCTYPE html>\n<html><br></html>", Language.XML)+ assertTrue(diags.none { it.severity == DiagnosticSeverity.ERROR })+ }+}