Modern Apps git

← Modern-Apps.git

office: native rust formula engine and document crdt

Commit
a60f128c87c602dc06938086fca3351529560e7b
Author
Vayun Mathur <[email protected]>
When
2026-07-29 03:16 UTC (4 months ago)
Parents
e20c0c7

Diff

office/build.gradle.kts
diff --git a/office/build.gradle.kts b/office/build.gradle.ktsindex d3e57fd8c4..55b69b24e6 100644--- a/office/build.gradle.kts+++ b/office/build.gradle.kts@@ -16,6 +16,17 @@ android {     sourceSets.getByName("androidTest").assets.directories.add(rootProject.file("metadata_data/assets").absolutePath) } +androidComponents {+    onVariants { variant ->+        variant.sources.jniLibs?.addStaticSourceDirectory(+            layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+        )+    }+}++// Native ODF formula engine + document CRDT (Rust). See office/src/main/rust/.+rustNativeLib("office_engine", "office")+ dependencies {     implementation(project(":library:network"))     implementation(project(":library:e2ee-p2p"))
office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.kt b/office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.ktdeleted file mode 100644index d6ddf9ba21..0000000000--- a/office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.kt+++ /dev/null@@ -1,1284 +0,0 @@-package com.vayunmathur.office.odf--import com.vayunmathur.library.ui.odf.*-import java.util.GregorianCalendar-import kotlin.math.abs-import kotlin.math.ceil-import kotlin.math.exp-import kotlin.math.floor-import kotlin.math.ln-import kotlin.math.log10-import kotlin.math.pow-import kotlin.math.roundToLong-import kotlin.math.sign-import kotlin.math.sqrt-import kotlin.math.truncate--/**- * OpenFormula evaluator for spreadsheet cells (H49 / Priority 3).- *- * Value-typed engine: cells/expressions evaluate to numbers, strings, booleans- * or error values (#DIV/0!, #VALUE!, #N/A, #REF!, #NAME?). Supports numeric and- * string literals, cell references ([.A1]) and ranges ([.A1:.B3]), arithmetic- * (+ - * / ^), string concat (&), comparisons (= <> < <= > >=), parentheses, and- * a broad function library: math/stat, logical (incl. IFERROR/IFS/IS*),- * lookup (VLOOKUP/HLOOKUP/MATCH/INDEX/CHOOSE), text (LEFT/RIGHT/MID/LEN/...),- * date/time (DATE/TODAY/NOW/YEAR/...), and conditional aggregation- * (SUMIF/COUNTIF/AVERAGEIF). References resolve against the sheet grid and- * recursively evaluate dependent formula cells (with cycle protection).- *- * Best-effort: covers common cases, not the full OpenFormula spec. Cross-sheet- * references resolve within the current sheet only (the caller supplies a single- * sheet). Cells whose formula cannot be evaluated fall back to their cached text.- */-object OdfFormulaEngine {--    /** Display string for a cell: evaluates the formula if present, else cached text. */-    fun displayValue(sheet: OdfSheet, row: Int, col: Int, workbook: Map<String, OdfSheet> = emptyMap(), sheetName: String = ""): String {-        val cell = sheet.rows.getOrNull(row)?.cells?.getOrNull(col) ?: return ""-        if (cell.formula == null) return cell.text-        return try {-            when (val v = Evaluator(sheet, mutableSetOf(), workbook, sheetName).evaluateCellValue(row, col)) {-                is Value.Num -> if (v.v.isNaN()) "#ERR" else formatWithStyle(v.v, cell.numberFormat)-                is Value.Bool -> if (v.b) "TRUE" else "FALSE"-                is Value.Str -> v.s-                is Value.Err -> v.code-                Value.Blank -> ""-            }-        } catch (_: Exception) {-            cell.text-        }-    }--    /** Formats a numeric value using an ODF number-format descriptor (H50). */-    fun formatWithStyle(v: Double, fmt: OdfNumberFormat?): String {-        if (fmt == null) return formatNumber(v)-        // Date / date-time: render the exact token pattern (falls back to ISO for a bare date flag).-        if (fmt.dateTimeTokens.isNotEmpty()) return formatDateTime(v, fmt.dateTimeTokens)-        if (fmt.isDate) return formatDateIso(v)-        if (fmt.isTime) return formatTime(v)-        if (fmt.isScientific) {-            val decimals = (fmt.decimals ?: 2).coerceIn(0, 10)-            return String.format("%.${decimals}E", v)-        }-        if (fmt.isFraction) return formatFraction(v, fmt.fractionDenominatorDigits)-        var value = v-        if (fmt.percent) value *= 100.0-        val decimals = (fmt.decimals ?: 2).coerceIn(0, 10)-        val pattern = (if (fmt.grouping) "%,." else "%.") + decimals + "f"-        var s = String.format(pattern, value)-        if (fmt.percent) s += "%"-        if (fmt.currencySymbol != null) s = fmt.currencySymbol + s-        return s-    }--    private val MONTHS = arrayOf("January", "February", "March", "April", "May", "June",-        "July", "August", "September", "October", "November", "December")-    private val MONTHS_SHORT = arrayOf("Jan", "Feb", "Mar", "Apr", "May", "Jun",-        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")-    private val WEEKDAYS = arrayOf("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")-    private val WEEKDAYS_SHORT = arrayOf("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")--    /** Renders a date/time serial using an ordered [tokens] pattern (number:date-style children). */-    private fun formatDateTime(serial: Double, tokens: List<OdfNumberToken>): String {-        val cal = serialToCal(serial)-        val year = cal.get(GregorianCalendar.YEAR)-        val month = cal.get(GregorianCalendar.MONTH)                 // 0-based-        val day = cal.get(GregorianCalendar.DAY_OF_MONTH)-        val dow = cal.get(GregorianCalendar.DAY_OF_WEEK) - 1         // 0 = Sunday-        val hour24 = cal.get(GregorianCalendar.HOUR_OF_DAY)-        val minute = cal.get(GregorianCalendar.MINUTE)-        val second = cal.get(GregorianCalendar.SECOND)-        val ampm = tokens.any { it.kind == "am-pm" }-        val sb = StringBuilder()-        for (t in tokens) when (t.kind) {-            "year" -> sb.append(if (t.style == "long") year.toString() else (year % 100).toString().padStart(2, '0'))-            "month" -> sb.append(when {-                t.textual && t.style == "long" -> MONTHS[month]-                t.textual -> MONTHS_SHORT[month]-                t.style == "long" -> (month + 1).toString().padStart(2, '0')-                else -> (month + 1).toString()-            })-            "day" -> sb.append(if (t.style == "long") day.toString().padStart(2, '0') else day.toString())-            "day-of-week" -> sb.append(if (t.style == "long") WEEKDAYS[dow] else WEEKDAYS_SHORT[dow])-            "hours" -> {-                val h = if (ampm) (hour24 % 12).let { if (it == 0) 12 else it } else hour24-                sb.append(if (t.style == "long") h.toString().padStart(2, '0') else h.toString())-            }-            "minutes" -> sb.append(if (t.style == "long") minute.toString().padStart(2, '0') else minute.toString())-            "seconds" -> sb.append(if (t.style == "long") second.toString().padStart(2, '0') else second.toString())-            "am-pm" -> sb.append(if (hour24 < 12) "AM" else "PM")-            "text" -> sb.append(t.text ?: "")-        }-        return sb.toString()-    }--    /** Formats a date serial as ISO yyyy-MM-dd (fallback when no explicit tokens are present). */-    private fun formatDateIso(serial: Double): String {-        val cal = serialToCal(serial)-        return "%04d-%02d-%02d".format(-            cal.get(GregorianCalendar.YEAR), cal.get(GregorianCalendar.MONTH) + 1, cal.get(GregorianCalendar.DAY_OF_MONTH)-        )-    }--    /** Formats a day-fraction serial (0..1) as HH:MM:SS. */-    private fun formatTime(serial: Double): String {-        val totalSeconds = Math.round((serial - floor(serial)) * 86400.0)-        val h = (totalSeconds / 3600) % 24-        val m = (totalSeconds % 3600) / 60-        val s = totalSeconds % 60-        return String.format("%02d:%02d:%02d", h, m, s)-    }--    /** Approximates a value as "whole num/den" using the largest denominator with [denomDigits] digits. */-    private fun formatFraction(value: Double, denomDigits: Int): String {-        val maxDen = 10.0.pow(denomDigits.coerceIn(1, 5)).toInt() - 1-        val whole = truncate(value).toLong()-        var frac = abs(value - whole)-        if (frac < 1e-9) return whole.toString()-        var bestN = 0; var bestD = 1; var bestErr = Double.MAX_VALUE-        for (d in 1..maxDen) {-            val n = Math.round(frac * d).toInt()-            val err = abs(frac - n.toDouble() / d)-            if (err < bestErr) { bestErr = err; bestN = n; bestD = d }-        }-        if (bestN == 0) return whole.toString()-        val sign = if (value < 0 && whole == 0L) "-" else ""-        return if (whole != 0L) "$whole $bestN/$bestD" else "$sign$bestN/$bestD"-    }--    /** True when the (evaluated) cell holds a numeric value (used for right-alignment, H54). */-    fun isNumeric(sheet: OdfSheet, row: Int, col: Int, workbook: Map<String, OdfSheet> = emptyMap(), sheetName: String = ""): Boolean {-        val cell = sheet.rows.getOrNull(row)?.cells?.getOrNull(col) ?: return false-        if (cell.numberValue != null) return true-        if (cell.valueType in setOf("float", "percentage", "currency")) return true-        if (cell.formula != null) {-            return try {-                Evaluator(sheet, mutableSetOf(), workbook, sheetName).evaluateCellValue(row, col).let {-                    it is Value.Num && !it.v.isNaN()-                }-            } catch (_: Exception) { false }-        }-        return cell.text.toDoubleOrNull() != null-    }--    fun formatNumber(v: Double): String {-        if (v.isNaN()) return "#ERR"-        if (v.isInfinite()) return "#DIV/0!"-        return if (v == v.toLong().toDouble()) v.toLong().toString() else "%.4f".format(v).trimEnd('0').trimEnd('.')-    }--    private fun colToIndex(col: String): Int {-        var n = 0-        for (c in col) { if (c.isLetter()) n = n * 26 + (c.uppercaseChar() - 'A' + 1) }-        return n - 1-    }--    /** 0-based column index -> letters (0 -> A, 26 -> AA). */-    private fun indexToCol(index: Int): String {-        if (index < 0) return "A"-        var n = index + 1-        val sb = StringBuilder()-        while (n > 0) { val rem = (n - 1) % 26; sb.insert(0, ('A' + rem)); n = (n - 1) / 26 }-        return sb.toString()-    }--    private fun factD(k: Int): Double { var r = 1.0; for (i in 2..k) r *= i; return r }--    private fun romanToArabic(roman: String): Int {-        val map = mapOf('I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000)-        val s = roman.trim().uppercase()-        var total = 0-        for (i in s.indices) {-            val cur = map[s[i]] ?: continue-            val next = if (i + 1 < s.length) map[s[i + 1]] ?: 0 else 0-            if (cur < next) total -= cur else total += cur-        }-        return total-    }--    private fun arabicToRoman(value: Int): String {-        if (value <= 0 || value >= 4000) return value.toString()-        val nums = intArrayOf(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)-        val syms = arrayOf("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")-        var v = value-        val sb = StringBuilder()-        for (i in nums.indices) { while (v >= nums[i]) { sb.append(syms[i]); v -= nums[i] } }-        return sb.toString()-    }--    // ---- Value model ---------------------------------------------------------    private sealed class Value {-        data class Num(val v: Double) : Value()-        data class Str(val s: String) : Value()-        data class Bool(val b: Boolean) : Value()-        data class Err(val code: String) : Value()-        object Blank : Value()-    }--    private class FormulaException(val code: String) : Exception(code)--    /** Reference parsed from a [..] token: a single cell (isRange=false) or a rectangular range. */-    private data class Ref(val r1: Int, val c1: Int, val r2: Int, val c2: Int, val isRange: Boolean, val sheet: String? = null)--    private sealed class Arg {-        data class Scalar(val v: Value) : Arg()-        data class RangeRef(val r1: Int, val c1: Int, val r2: Int, val c2: Int, val sheet: String? = null) : Arg()-    }--    // ---- Date helpers (serial = days since 1899-12-30) -----------------------    private const val MS_PER_DAY = 86_400_000.0--    private fun dateSerial(y: Int, m: Int, d: Int): Double {-        val cal = GregorianCalendar(y, m - 1, d, 0, 0, 0)-        cal.set(GregorianCalendar.MILLISECOND, 0)-        val base = GregorianCalendar(1899, 11, 30, 0, 0, 0)-        base.set(GregorianCalendar.MILLISECOND, 0)-        return ((cal.timeInMillis - base.timeInMillis) / MS_PER_DAY).let { Math.round(it).toDouble() }-    }--    private fun nowSerial(withTime: Boolean): Double {-        val cal = GregorianCalendar()-        val base = GregorianCalendar(1899, 11, 30, 0, 0, 0)-        base.set(GregorianCalendar.MILLISECOND, 0)-        val raw = (cal.timeInMillis - base.timeInMillis) / MS_PER_DAY-        return if (withTime) raw else floor(raw)-    }--    private fun serialToCal(serial: Double): GregorianCalendar {-        val base = GregorianCalendar(1899, 11, 30, 0, 0, 0)-        base.set(GregorianCalendar.MILLISECOND, 0)-        val cal = GregorianCalendar()-        cal.timeInMillis = base.timeInMillis + Math.round(serial * MS_PER_DAY)-        return cal-    }--    private class Evaluator(-        val sheet: OdfSheet,-        val visiting: MutableSet<String>,-        val workbook: Map<String, OdfSheet> = emptyMap(),-        val sheetName: String = ""-    ) {--        /** Coordinates of the cell whose formula is currently being parsed (for ROW/COLUMN/OFFSET/ADDRESS). */-        var curRow = 0-        var curCol = 0--        /** Public entry: evaluates a cell, converting thrown errors into a Value.Err. */-        fun evaluateCellValue(row: Int, col: Int): Value = try {-            evaluateCellV(row, col)-        } catch (e: FormulaException) {-            Value.Err(e.code)-        }--        /** Resolves a (possibly cross-sheet) cell reference, evaluating on the target sheet. (R4) */-        private fun evalOn(name: String?, row: Int, col: Int): Value {-            if (name == null || name == sheetName) return evaluateCellV(row, col)-            val target = workbook[name] ?: return Value.Err("#REF!")-            return Evaluator(target, visiting, workbook, name).evaluateCellV(row, col)-        }--        private fun evaluateCellV(row: Int, col: Int): Value {-            val key = "$sheetName!$row,$col"-            if (key in visiting) throw FormulaException("#REF!")-            val cell = sheet.rows.getOrNull(row)?.cells?.getOrNull(col) ?: return Value.Blank-            val formula = cell.formula ?: return rawCellValue(cell)-            visiting.add(key)-            val saveR = curRow; val saveC = curCol-            curRow = row; curCol = col-            try {-                val expr = normalize(formula)-                return Parser(expr).parseExpression()-            } finally {-                visiting.remove(key)-                curRow = saveR; curCol = saveC-            }-        }--        private fun rawCellValue(cell: OdfCell): Value {-            cell.numberValue?.let { return Value.Num(it) }-            val t = cell.text-            if (t.isEmpty()) return Value.Blank-            t.toDoubleOrNull()?.let { return Value.Num(it) }-            if (t.equals("TRUE", true)) return Value.Bool(true)-            if (t.equals("FALSE", true)) return Value.Bool(false)-            return Value.Str(t)-        }--        private fun normalize(formula: String): String {-            var f = formula.trim()-            if (f.startsWith("of:")) f = f.substring(3)-            if (f.startsWith("=")) f = f.substring(1)-            return f-        }--        // ---- coercions -------------------------------------------------------        private fun num(v: Value): Double = when (v) {-            is Value.Num -> v.v-            is Value.Bool -> if (v.b) 1.0 else 0.0-            is Value.Str -> v.s.trim().toDoubleOrNull() ?: throw FormulaException("#VALUE!")-            Value.Blank -> 0.0-            is Value.Err -> throw FormulaException(v.code)-        }--        private fun numOrNull(v: Value): Double? = when (v) {-            is Value.Num -> v.v-            is Value.Bool -> if (v.b) 1.0 else 0.0-            else -> null-        }--        private fun str(v: Value): String = when (v) {-            is Value.Num -> formatNumber(v.v)-            is Value.Bool -> if (v.b) "TRUE" else "FALSE"-            is Value.Str -> v.s-            Value.Blank -> ""-            is Value.Err -> throw FormulaException(v.code)-        }--        private fun truthy(v: Value): Boolean = when (v) {-            is Value.Bool -> v.b-            is Value.Num -> v.v != 0.0-            is Value.Str -> when {-                v.s.equals("TRUE", true) -> true-                v.s.equals("FALSE", true) -> false-                else -> v.s.trim().toDoubleOrNull()?.let { it != 0.0 } ?: throw FormulaException("#VALUE!")-            }-            Value.Blank -> false-            is Value.Err -> throw FormulaException(v.code)-        }--        // ---- range / arg helpers --------------------------------------------        private fun rangeValues(r1: Int, c1: Int, r2: Int, c2: Int, sheetRef: String? = null): List<Value> {-            val out = ArrayList<Value>()-            val target = if (sheetRef == null || sheetRef == sheetName) sheet else workbook[sheetRef] ?: sheet-            for (r in minOf(r1, r2)..maxOf(r1, r2)) {-                for (c in minOf(c1, c2)..maxOf(c1, c2)) {-                    val cell = target.rows.getOrNull(r)?.cells?.getOrNull(c)-                    if (cell != null && cell.isCovered) continue-                    out.add(evalOn(sheetRef, r, c))-                }-            }-            return out-        }--        private fun argValues(arg: Arg): List<Value> = when (arg) {-            is Arg.Scalar -> listOf(arg.v)-            is Arg.RangeRef -> rangeValues(arg.r1, arg.c1, arg.r2, arg.c2, arg.sheet)-        }--        /** Resolves the raw cell at a (possibly cross-sheet) coordinate without evaluating it. */-        private fun cellAt(sheetRef: String?, r: Int, c: Int): OdfCell? {-            val target = if (sheetRef == null || sheetRef == sheetName) sheet else workbook[sheetRef] ?: sheet-            return target.rows.getOrNull(r)?.cells?.getOrNull(c)-        }--        // A lazily-evaluated function argument (for IF/IFERROR/CHOOSE short-circuiting).-        private inner class ArgThunk(val text: String) {-            fun arg(): Arg = Parser(text).parseArgTop()-            fun value(): Value = when (val a = arg()) {-                is Arg.Scalar -> a.v-                is Arg.RangeRef -> evalOn(a.sheet, a.r1, a.c1)-            }-            fun values(): List<Value> = argValues(arg())-            /** Raw reference (single cell or range) if the whole arg is a reference token, else null. */-            fun ref(): Ref? = Parser(text).parseRefTop()-        }--        // ---- comparison ------------------------------------------------------        private fun compareOp(op: String, l: Value, r: Value): Boolean {-            val ln = cmpNum(l); val rn = cmpNum(r)-            if (ln != null && rn != null) {-                return when (op) {-                    "<" -> ln < rn; "<=" -> ln <= rn; ">" -> ln > rn-                    ">=" -> ln >= rn; "=" -> ln == rn; "<>" -> ln != rn; else -> false-                }-            }-            val cmp = str(l).compareTo(str(r), ignoreCase = true)-            return when (op) {-                "<" -> cmp < 0; "<=" -> cmp <= 0; ">" -> cmp > 0-                ">=" -> cmp >= 0; "=" -> cmp == 0; "<>" -> cmp != 0; else -> false-            }-        }--        private fun cmpNum(v: Value): Double? = when (v) {-            is Value.Num -> v.v-            is Value.Bool -> if (v.b) 1.0 else 0.0-            Value.Blank -> 0.0-            is Value.Err -> throw FormulaException(v.code)-            is Value.Str -> null-        }--        // ---- criteria matching (SUMIF/COUNTIF/AVERAGEIF) ---------------------        private fun matchesCriteria(v: Value, criteria: Value): Boolean {-            val crit = str(criteria)-            var op = "="; var rest = crit.trim()-            for (o in listOf("<=", ">=", "<>", "<", ">", "=")) {-                if (rest.startsWith(o)) { op = o; rest = rest.substring(o.length).trim(); break }-            }-            val restNum = rest.toDoubleOrNull()-            val vNum = numOrNull(v)-            if (restNum != null && vNum != null) {-                return when (op) {-                    "<" -> vNum < restNum; "<=" -> vNum <= restNum; ">" -> vNum > restNum-                    ">=" -> vNum >= restNum; "<>" -> vNum != restNum; else -> vNum == restNum-                }-            }-            val vStr = if (v == Value.Blank) "" else str(v)-            return when (op) {-                "<>" -> !wildcardEquals(vStr, rest)-                "=" -> wildcardEquals(vStr, rest)-                else -> false-            }-        }--        private fun wildcardEquals(value: String, pattern: String): Boolean {-            if (!pattern.contains('*') && !pattern.contains('?')) return value.equals(pattern, true)-            val regex = StringBuilder("^")-            for (ch in pattern) when (ch) {-                '*' -> regex.append(".*")-                '?' -> regex.append('.')-                else -> regex.append(Regex.escape(ch.toString()))-            }-            regex.append('$')-            return Regex(regex.toString(), RegexOption.IGNORE_CASE).matches(value)-        }--        // Recursive-descent parser over the formula string.-        private inner class Parser(val s: String) {-            var pos = 0--            fun parseExpression(): Value = parseComparison()--            /** Top-level parse of a single function argument; preserves range references. */-            fun parseArgTop(): Arg {-                skipWs()-                if (peek() == '[') {-                    val save = pos-                    val ref = parseRefRaw()-                    skipWs()-                    if (pos >= s.length) {-                        return if (ref.isRange) Arg.RangeRef(ref.r1, ref.c1, ref.r2, ref.c2, ref.sheet)-                        else Arg.Scalar(evalOn(ref.sheet, ref.r1, ref.c1))-                    }-                    pos = save-                }-                return Arg.Scalar(parseExpression())-            }--            /** Parses a lone top-level reference token (single cell or range), else null. */-            fun parseRefTop(): Ref? {-                skipWs()-                if (peek() != '[') return null-                val ref = parseRefRaw()-                skipWs()-                return if (pos >= s.length) ref else null-            }--            private fun parseComparison(): Value {-                var left = parseConcat()-                while (true) {-                    skipWs()-                    val op = when {-                        match("<=") -> "<="; match(">=") -> ">="; match("<>") -> "<>"-                        peek() == '<' -> { pos++; "<" }-                        peek() == '>' -> { pos++; ">" }-                        peek() == '=' -> { pos++; "=" }-                        else -> return left-                    }-                    val right = parseConcat()-                    left = Value.Bool(compareOp(op, left, right))-                }-            }--            private fun parseConcat(): Value {-                var v = parseAddSub()-                while (true) {-                    skipWs()-                    if (peek() == '&') { pos++; v = Value.Str(str(v) + str(parseAddSub())) }-                    else return v-                }-            }--            private fun parseAddSub(): Value {-                var v = parseMulDiv()-                while (true) {-                    skipWs()-                    when (peek()) {-                        '+' -> { pos++; v = Value.Num(num(v) + num(parseMulDiv())) }-                        '-' -> { pos++; v = Value.Num(num(v) - num(parseMulDiv())) }-                        else -> return v-                    }-                }-            }--            private fun parseMulDiv(): Value {-                var v = parsePower()-                while (true) {-                    skipWs()-                    when (peek()) {-                        '*' -> { pos++; v = Value.Num(num(v) * num(parsePower())) }-                        '/' -> {-                            pos++-                            val d = num(parsePower())-                            if (d == 0.0) throw FormulaException("#DIV/0!")-                            v = Value.Num(num(v) / d)-                        }-                        else -> return v-                    }-                }-            }--            private fun parsePower(): Value {-                val base = parseUnary()-                skipWs()-                if (peek() == '^') { pos++; return Value.Num(num(base).pow(num(parseUnary()))) }-                return base-            }--            private fun parseUnary(): Value {-                skipWs()-                if (peek() == '-') { pos++; return Value.Num(-num(parseUnary())) }-                if (peek() == '+') { pos++; return parseUnary() }-                return parsePrimary()-            }--            private fun parsePrimary(): Value {-                skipWs()-                val c = peek()-                return when {-                    c == '(' -> { pos++; val v = parseExpression(); skipWs(); if (peek() == ')') pos++; v }-                    c == '[' -> { val ref = parseRefRaw(); evalOn(ref.sheet, ref.r1, ref.c1) }-                    c == '"' -> Value.Str(parseString())-                    c.isDigit() || c == '.' -> Value.Num(parseNumber())-                    c.isLetter() -> parseFunctionOrConst()-                    else -> { pos++; Value.Num(0.0) }-                }-            }--            private fun parseNumber(): Double {-                val start = pos-                while (pos < s.length && (s[pos].isDigit() || s[pos] == '.' || s[pos] == 'E' || s[pos] == 'e')) pos++-                var value = s.substring(start, pos).toDoubleOrNull() ?: 0.0-                skipWs()-                if (peek() == '%') { pos++; value /= 100.0 }-                return value-            }--            private fun parseString(): String {-                pos++ // opening quote-                val sb = StringBuilder()-                while (pos < s.length) {-                    val ch = s[pos]-                    if (ch == '"') {-                        // Doubled quote -> literal quote (OpenFormula escaping).-                        if (pos + 1 < s.length && s[pos + 1] == '"') { sb.append('"'); pos += 2; continue }-                        pos++; break-                    }-                    sb.append(ch); pos++-                }-                return sb.toString()-            }--            /** Parses a [.A1] / [.A1:.B3] / [Sheet.A1] reference token. */-            private fun parseRefRaw(): Ref {-                pos++ // '['-                val sb = StringBuilder()-                while (pos < s.length && s[pos] != ']') { sb.append(s[pos]); pos++ }-                if (pos < s.length) pos++ // ']'-                val raw = sb.toString().replace("$", "")-                val firstEndpoint = raw.substringBefore(":")-                val sheetRef = firstEndpoint.substringBeforeLast('.', "").removePrefix(".").trim().trim('\'').ifEmpty { null }-                return if (raw.contains(":")) {-                    val (a, b) = raw.split(":", limit = 2)-                    val (r1, c1) = parseCellCoords(a)-                    val (r2, c2) = parseCellCoords(b)-                    Ref(r1, c1, r2, c2, true, sheetRef)-                } else {-                    val (r, c) = parseCellCoords(raw)-                    Ref(r, c, r, c, false, sheetRef)-                }-            }--            /** Returns (rowIndex, colIndex) 0-based. Drops any sheet prefix / leading dot. */-            private fun parseCellCoords(token: String): Pair<Int, Int> {-                val t = token.substringAfterLast('.')-                val m = Regex("([A-Za-z]+)(\\d+)").find(t) ?: return 0 to 0-                val col = colToIndex(m.groupValues[1])-                val row = (m.groupValues[2].toIntOrNull() ?: 1) - 1-                return row to col-            }--            private fun parseFunctionOrConst(): Value {-                val start = pos-                while (pos < s.length && (s[pos].isLetterOrDigit() || s[pos] == '_' || s[pos] == '.')) pos++-                var name = s.substring(start, pos).uppercase()-                if (name.startsWith("ORG.OPENOFFICE.")) name = name.removePrefix("ORG.OPENOFFICE.")-                if (name.startsWith("COM.MICROSOFT.")) name = name.removePrefix("COM.MICROSOFT.")-                skipWs()-                if (peek() != '(') {-                    return when (name) {-                        "TRUE" -> Value.Bool(true)-                        "FALSE" -> Value.Bool(false)-                        "PI" -> Value.Num(Math.PI)-                        else -> throw FormulaException("#NAME?")-                    }-                }-                pos++ // '('-                val argTexts = splitArgs()-                return applyFunction(name, argTexts.map { ArgThunk(it) })-            }--            /** Splits the current argument list, consuming through the matching ')'. */-            private fun splitArgs(): List<String> {-                val parts = mutableListOf<String>()-                val cur = StringBuilder()-                var depth = 0-                var inStr = false-                while (pos < s.length) {-                    val c = s[pos]-                    if (inStr) { cur.append(c); if (c == '"') inStr = false; pos++; continue }-                    when (c) {-                        '"' -> { inStr = true; cur.append(c); pos++ }-                        '(', '[' -> { depth++; cur.append(c); pos++ }-                        ']' -> { depth--; cur.append(c); pos++ }-                        ')' -> { if (depth == 0) { pos++; break } else { depth--; cur.append(c); pos++ } }-                        ',', ';' -> { if (depth == 0) { parts.add(cur.toString()); cur.clear(); pos++ } else { cur.append(c); pos++ } }-                        else -> { cur.append(c); pos++ }-                    }-                }-                if (cur.isNotBlank() || parts.isNotEmpty()) parts.add(cur.toString())-                return parts-            }--            // ---- function library -------------------------------------------            private fun applyFunction(name: String, a: List<ArgThunk>): Value {-                fun allVals() = a.flatMap { it.values() }-                fun allNums() = allVals().mapNotNull { numOrNull(it) }-                fun n(i: Int) = num(a[i].value())-                fun v(i: Int) = a[i].value()-                fun sArg(i: Int) = str(a[i].value())-                fun arr(i: Int) = a[i].values().mapNotNull { numOrNull(it) }-                fun pair(i: Int, j: Int): Pair<List<Double>, List<Double>> {-                    val x = arr(i); val y = arr(j); val m = minOf(x.size, y.size)-                    return x.take(m) to y.take(m)-                }-                fun valsA(): List<Double> = allVals().mapNotNull {-                    when (it) {-                        is Value.Num -> it.v-                        is Value.Bool -> if (it.b) 1.0 else 0.0-                        is Value.Str -> 0.0-                        Value.Blank -> null-                        is Value.Err -> throw FormulaException(it.code)-                    }-                }--                return when (name) {-                    // ---- math / statistics -----                    "SUM" -> Value.Num(allNums().sum())-                    "AVERAGE" -> allNums().let { if (it.isEmpty()) throw FormulaException("#DIV/0!") else Value.Num(it.average()) }-                    "MIN" -> allNums().minOrNull()?.let { Value.Num(it) } ?: Value.Num(0.0)-                    "MAX" -> allNums().maxOrNull()?.let { Value.Num(it) } ?: Value.Num(0.0)-                    "COUNT" -> Value.Num(allNums().size.toDouble())-                    "COUNTA" -> Value.Num(allVals().count { it != Value.Blank }.toDouble())-                    "COUNTBLANK" -> Value.Num(allVals().count { it == Value.Blank }.toDouble())-                    "PRODUCT" -> allNums().let { if (it.isEmpty()) Value.Num(0.0) else Value.Num(it.fold(1.0) { x, y -> x * y }) }-                    "ABS" -> Value.Num(abs(n(0)))-                    "SQRT" -> Value.Num(sqrt(n(0)))-                    "POWER" -> Value.Num(n(0).pow(n(1)))-                    "MOD" -> { val b = n(1); if (b == 0.0) throw FormulaException("#DIV/0!") else Value.Num(n(0).let { it - floor(it / b) * b }) }-                    "INT" -> Value.Num(floor(n(0)))-                    "TRUNC" -> Value.Num(truncate(n(0)))-                    "SIGN" -> Value.Num(sign(n(0)))-                    "EXP" -> Value.Num(exp(n(0)))-                    "LN" -> Value.Num(ln(n(0)))-                    "LOG10" -> Value.Num(log10(n(0)))-                    "LOG" -> Value.Num(ln(n(0)) / ln(if (a.size > 1) n(1) else 10.0))-                    "ROUND" -> { val f = 10.0.pow(if (a.size > 1) n(1).toInt() else 0); Value.Num((n(0) * f).roundToLong() / f) }-                    "ROUNDUP" -> { val d = if (a.size > 1) n(1).toInt() else 0; val f = 10.0.pow(d); val x = n(0); Value.Num(ceil(abs(x) * f) / f * (if (x < 0) -1.0 else 1.0)) }-                    "ROUNDDOWN" -> { val d = if (a.size > 1) n(1).toInt() else 0; val f = 10.0.pow(d); val x = n(0); Value.Num(floor(abs(x) * f) / f * (if (x < 0) -1.0 else 1.0)) }-                    "CEILING" -> { val step = if (a.size > 1) n(1) else 1.0; if (step == 0.0) Value.Num(0.0) else Value.Num(ceil(n(0) / step) * step) }-                    "FLOOR" -> { val step = if (a.size > 1) n(1) else 1.0; if (step == 0.0) Value.Num(0.0) else Value.Num(floor(n(0) / step) * step) }-                    "MEDIAN" -> allNums().let {-                        if (it.isEmpty()) throw FormulaException("#NUM!")-                        val sorted = it.sorted(); val sz = sorted.size-                        Value.Num(if (sz % 2 == 1) sorted[sz / 2] else (sorted[sz / 2 - 1] + sorted[sz / 2]) / 2.0)-                    }-                    "STDEV" -> allNums().let { if (it.size < 2) throw FormulaException("#DIV/0!") else { val m = it.average(); Value.Num(sqrt(it.sumOf { x -> (x - m).pow(2) } / (it.size - 1))) } }-                    "VAR" -> allNums().let { if (it.size < 2) throw FormulaException("#DIV/0!") else { val m = it.average(); Value.Num(it.sumOf { x -> (x - m).pow(2) } / (it.size - 1)) } }--                    // ---- conditional aggregation -----                    "SUMIF" -> conditionalAgg(a, sumKind = true) { vals -> vals.sum() }-                    "AVERAGEIF" -> conditionalAgg(a, sumKind = true) { vals -> if (vals.isEmpty()) throw FormulaException("#DIV/0!") else vals.average() }-                    "COUNTIF" -> {-                        val rng = a[0].arg()-                        val crit = v(1)-                        var count = 0-                        forEachRangeCell(rng) { cv -> if (matchesCriteria(cv, crit)) count++ }-                        Value.Num(count.toDouble())-                    }--                    // ---- logical -----                    "IF" -> if (truthy(v(0))) v(1) else if (a.size > 2) v(2) else Value.Bool(false)-                    "IFS" -> {-                        var i = 0-                        while (i + 1 < a.size) { if (truthy(a[i].value())) return a[i + 1].value(); i += 2 }-                        throw FormulaException("#N/A")-                    }-                    "IFERROR" -> try { val r = v(0); if (r is Value.Err) v(1) else r } catch (_: FormulaException) { v(1) }-                    "IFNA" -> try { val r = v(0); if (r is Value.Err && r.code == "#N/A") v(1) else r } catch (e: FormulaException) { if (e.code == "#N/A") v(1) else throw e }-                    "AND" -> { val f = allVals().mapNotNull { boolOrNull(it) }; Value.Bool(f.isNotEmpty() && f.all { it }) }-                    "OR" -> { val f = allVals().mapNotNull { boolOrNull(it) }; Value.Bool(f.any { it }) }-                    "NOT" -> Value.Bool(!truthy(v(0)))-                    "ISERROR" -> Value.Bool(isError(a[0]) != null)-                    "ISERR" -> Value.Bool(isError(a[0]).let { it != null && it != "#N/A" })-                    "ISNA" -> Value.Bool(isError(a[0]) == "#N/A")-                    "ISNUMBER" -> Value.Bool(safeValue(a[0]) is Value.Num)-                    "ISTEXT" -> Value.Bool(safeValue(a[0]) is Value.Str)-                    "ISBLANK" -> Value.Bool(safeValue(a[0]) == Value.Blank)-                    "ISLOGICAL" -> Value.Bool(safeValue(a[0]) is Value.Bool)-                    "NA" -> throw FormulaException("#N/A")--                    // ---- lookup -----                    "CHOOSE" -> { val idx = n(0).toInt(); if (idx < 1 || idx >= a.size) throw FormulaException("#VALUE!") else a[idx].value() }-                    "VLOOKUP" -> lookup(a, horizontal = false)-                    "HLOOKUP" -> lookup(a, horizontal = true)-                    "MATCH" -> matchFn(a)-                    "INDEX" -> indexFn(a)--                    // ---- text -----                    "LEN" -> Value.Num(sArg(0).length.toDouble())-                    "LEFT" -> { val str = sArg(0); val k = if (a.size > 1) n(1).toInt() else 1; Value.Str(str.take(k.coerceAtLeast(0))) }-                    "RIGHT" -> { val str = sArg(0); val k = if (a.size > 1) n(1).toInt() else 1; Value.Str(str.takeLast(k.coerceAtLeast(0))) }-                    "MID" -> { val str = sArg(0); val start = (n(1).toInt() - 1).coerceAtLeast(0); val len = n(2).toInt().coerceAtLeast(0); Value.Str(if (start >= str.length) "" else str.substring(start, minOf(str.length, start + len))) }-                    "UPPER" -> Value.Str(sArg(0).uppercase())-                    "LOWER" -> Value.Str(sArg(0).lowercase())-                    "TRIM" -> Value.Str(sArg(0).trim().replace(Regex("\\s+"), " "))-                    "PROPER" -> Value.Str(sArg(0).split(" ").joinToString(" ") { w -> w.replaceFirstChar { it.uppercase() } })-                    "CONCATENATE", "CONCAT" -> Value.Str(allVals().joinToString("") { str(it) })-                    "REPT" -> Value.Str(sArg(0).repeat(n(1).toInt().coerceAtLeast(0)))-                    "EXACT" -> Value.Bool(sArg(0) == sArg(1))-                    "FIND" -> { val start = if (a.size > 2) n(2).toInt() - 1 else 0; val idx = sArg(1).indexOf(sArg(0), start.coerceAtLeast(0)); if (idx < 0) throw FormulaException("#VALUE!") else Value.Num((idx + 1).toDouble()) }-                    "SEARCH" -> { val start = if (a.size > 2) n(2).toInt() - 1 else 0; val idx = sArg(1).indexOf(sArg(0), start.coerceAtLeast(0), ignoreCase = true); if (idx < 0) throw FormulaException("#VALUE!") else Value.Num((idx + 1).toDouble()) }-                    "SUBSTITUTE" -> Value.Str(sArg(0).replace(sArg(1), sArg(2)))-                    "REPLACE" -> { val str = sArg(0); val start = (n(1).toInt() - 1).coerceIn(0, str.length); val len = n(2).toInt().coerceAtLeast(0); val end = minOf(str.length, start + len); Value.Str(str.substring(0, start) + sArg(3) + str.substring(end)) }-                    "VALUE" -> Value.Num(sArg(0).trim().toDoubleOrNull() ?: throw FormulaException("#VALUE!"))-                    "TEXT" -> Value.Str(textFormat(n(0), sArg(1)))--                    // ---- date / time -----                    "DATE" -> Value.Num(dateSerial(n(0).toInt(), n(1).toInt(), n(2).toInt()))-                    "TODAY" -> Value.Num(nowSerial(false))-                    "NOW" -> Value.Num(nowSerial(true))-                    "YEAR" -> Value.Num(serialToCal(n(0)).get(GregorianCalendar.YEAR).toDouble())-                    "MONTH" -> Value.Num((serialToCal(n(0)).get(GregorianCalendar.MONTH) + 1).toDouble())-                    "DAY" -> Value.Num(serialToCal(n(0)).get(GregorianCalendar.DAY_OF_MONTH).toDouble())-                    "HOUR" -> Value.Num(serialToCal(n(0)).get(GregorianCalendar.HOUR_OF_DAY).toDouble())-                    "MINUTE" -> Value.Num(serialToCal(n(0)).get(GregorianCalendar.MINUTE).toDouble())-                    "SECOND" -> Value.Num(serialToCal(n(0)).get(GregorianCalendar.SECOND).toDouble())-                    "WEEKDAY" -> Value.Num(serialToCal(n(0)).get(GregorianCalendar.DAY_OF_WEEK).toDouble())-                    "TIME" -> Value.Num((n(0) * 3600 + n(1) * 60 + n(2)) / 86400.0)--                    // ---- multi-criteria aggregation (Round 3) -----                    "SUMIFS" -> {-                        val sumVals = a[0].values()-                        val pairs = (1 until a.size step 2).map { a[it].values() to a[it + 1].value() }-                        var total = 0.0-                        for (k in sumVals.indices) if (pairs.all { (rng, crit) -> k < rng.size && matchesCriteria(rng[k], crit) }) numOrNull(sumVals[k])?.let { total += it }-                        Value.Num(total)-                    }-                    "COUNTIFS" -> {-                        val pairs = (0 until a.size step 2).map { a[it].values() to a[it + 1].value() }-                        val len = pairs.firstOrNull()?.first?.size ?: 0-                        var c = 0-                        for (k in 0 until len) if (pairs.all { (rng, crit) -> k < rng.size && matchesCriteria(rng[k], crit) }) c++-                        Value.Num(c.toDouble())-                    }-                    "AVERAGEIFS" -> {-                        val sumVals = a[0].values()-                        val pairs = (1 until a.size step 2).map { a[it].values() to a[it + 1].value() }-                        var total = 0.0; var cnt = 0-                        for (k in sumVals.indices) if (pairs.all { (rng, crit) -> k < rng.size && matchesCriteria(rng[k], crit) }) numOrNull(sumVals[k])?.let { total += it; cnt++ }-                        if (cnt == 0) throw FormulaException("#DIV/0!") else Value.Num(total / cnt)-                    }-                    "SUMPRODUCT" -> {-                        val arrays = a.map { it.values().map { v -> numOrNull(v) ?: 0.0 } }-                        val len = arrays.minOfOrNull { it.size } ?: 0-                        var total = 0.0-                        for (k in 0 until len) { var p = 1.0; for (arr in arrays) p *= arr[k]; total += p }-                        Value.Num(total)-                    }--                    // ---- extended math (Round 3) -----                    "SUMSQ" -> Value.Num(allNums().sumOf { it * it })-                    "MROUND" -> { val m = n(1); if (m == 0.0) Value.Num(0.0) else Value.Num(Math.round(n(0) / m) * m) }-                    "EVEN" -> { val x = n(0); val r = ceil(abs(x) / 2.0) * 2.0; Value.Num(if (x < 0) -r else r) }-                    "ODD" -> { val x = n(0); var r = ceil(abs(x)); if (r % 2.0 == 0.0) r += 1.0; if (r < 1.0) r = 1.0; Value.Num(if (x < 0) -r else r) }-                    "GCD" -> { val ints = allNums().map { abs(it).toLong() }; Value.Num((ints.reduceOrNull { x, y -> gcdL(x, y) } ?: 0L).toDouble()) }-                    "LCM" -> { val ints = allNums().map { abs(it).toLong() }; Value.Num((ints.reduceOrNull { x, y -> if (x == 0L || y == 0L) 0L else x / gcdL(x, y) * y } ?: 0L).toDouble()) }-                    "FACT" -> { var r = 1.0; val k = n(0).toInt(); if (k < 0) throw FormulaException("#NUM!"); for (i in 2..k) r *= i; Value.Num(r) }-                    "COMBIN" -> { val nn = n(0).toInt(); val k = n(1).toInt(); if (k < 0 || k > nn) throw FormulaException("#NUM!"); var r = 1.0; for (i in 0 until k) r = r * (nn - i) / (i + 1); Value.Num(Math.round(r).toDouble()) }-                    "RAND" -> Value.Num(Math.random())-                    "RANDBETWEEN" -> { val lo = n(0).toLong(); val hi = n(1).toLong(); Value.Num((lo + (Math.random() * (hi - lo + 1)).toLong()).toDouble()) }-                    "SIN" -> Value.Num(kotlin.math.sin(n(0)))-                    "COS" -> Value.Num(kotlin.math.cos(n(0)))-                    "TAN" -> Value.Num(kotlin.math.tan(n(0)))-                    "ASIN" -> Value.Num(kotlin.math.asin(n(0)))-                    "ACOS" -> Value.Num(kotlin.math.acos(n(0)))-                    "ATAN" -> Value.Num(kotlin.math.atan(n(0)))-                    "ATAN2" -> Value.Num(kotlin.math.atan2(n(1), n(0)))-                    "RADIANS" -> Value.Num(Math.toRadians(n(0)))-                    "DEGREES" -> Value.Num(Math.toDegrees(n(0)))--                    // ---- extended statistics (Round 3) -----                    "STDEVP" -> allNums().let { if (it.isEmpty()) throw FormulaException("#DIV/0!") else { val m = it.average(); Value.Num(sqrt(it.sumOf { x -> (x - m).pow(2) } / it.size)) } }-                    "VARP" -> allNums().let { if (it.isEmpty()) throw FormulaException("#DIV/0!") else { val m = it.average(); Value.Num(it.sumOf { x -> (x - m).pow(2) } / it.size) } }-                    "MODE" -> allNums().let { ns -> if (ns.isEmpty()) throw FormulaException("#N/A") else ns.groupingBy { it }.eachCount().maxByOrNull { it.value }!!.key.let { Value.Num(it) } }-                    "RANK" -> { val x = n(0); val list = a[1].values().mapNotNull { numOrNull(it) }; val asc = a.size > 2 && truthy(v(2)); val sorted = if (asc) list.sorted() else list.sortedDescending(); val idx = sorted.indexOf(x); if (idx < 0) throw FormulaException("#N/A") else Value.Num((idx + 1).toDouble()) }-                    "LARGE" -> { val list = a[0].values().mapNotNull { numOrNull(it) }.sortedDescending(); val k = n(1).toInt(); if (k < 1 || k > list.size) throw FormulaException("#NUM!") else Value.Num(list[k - 1]) }-                    "SMALL" -> { val list = a[0].values().mapNotNull { numOrNull(it) }.sorted(); val k = n(1).toInt(); if (k < 1 || k > list.size) throw FormulaException("#NUM!") else Value.Num(list[k - 1]) }-                    "PERCENTILE" -> { val list = a[0].values().mapNotNull { numOrNull(it) }.sorted(); val p = n(1); if (list.isEmpty() || p < 0 || p > 1) throw FormulaException("#NUM!"); val rank = p * (list.size - 1); val lo = floor(rank).toInt(); val hi = ceil(rank).toInt(); Value.Num(if (lo == hi) list[lo] else list[lo] + (rank - lo) * (list[hi] - list[lo])) }--                    // ---- extended logical (Round 3) -----                    "SWITCH" -> {-                        val subject = v(0); var i = 1-                        while (i + 1 < a.size) { if (compareOp("=", subject, a[i].value())) return a[i + 1].value(); i += 2 }-                        if (i < a.size) a[i].value() else throw FormulaException("#N/A")-                    }-                    "XOR" -> { val f = allVals().mapNotNull { boolOrNull(it) }; Value.Bool(f.count { it } % 2 == 1) }--                    // ---- extended text (Round 3) -----                    "TEXTJOIN" -> { val delim = sArg(0); val ignoreEmpty = truthy(v(1)); val parts = a.drop(2).flatMap { it.values() }.map { str(it) }.filter { !ignoreEmpty || it.isNotEmpty() }; Value.Str(parts.joinToString(delim)) }-                    "CHAR" -> Value.Str(n(0).toInt().toChar().toString())-                    "CODE" -> { val s = sArg(0); if (s.isEmpty()) throw FormulaException("#VALUE!") else Value.Num(s[0].code.toDouble()) }-                    "T" -> { val r = v(0); if (r is Value.Str) r else Value.Str("") }-                    "CLEAN" -> Value.Str(sArg(0).filter { it.code >= 0x20 })-                    "NUMBERVALUE" -> Value.Num(sArg(0).trim().replace(",", "").toDoubleOrNull() ?: throw FormulaException("#VALUE!"))--                    // ---- lookup dimensions (Round 3) -----                    "ROWS" -> (a[0].arg() as? Arg.RangeRef)?.let { Value.Num((abs(it.r2 - it.r1) + 1).toDouble()) } ?: Value.Num(1.0)-                    "COLUMNS" -> (a[0].arg() as? Arg.RangeRef)?.let { Value.Num((abs(it.c2 - it.c1) + 1).toDouble()) } ?: Value.Num(1.0)--                    // ---- extended date (Round 3) -----                    "DAYS" -> Value.Num(floor(n(0)) - floor(n(1)))-                    "DATEVALUE" -> Value.Num(floor(n(0)))-                    "EDATE" -> { val c = serialToCal(n(0)); c.add(GregorianCalendar.MONTH, n(1).toInt()); Value.Num(dateSerial(c.get(GregorianCalendar.YEAR), c.get(GregorianCalendar.MONTH) + 1, c.get(GregorianCalendar.DAY_OF_MONTH))) }-                    "EOMONTH" -> { val c = serialToCal(n(0)); c.add(GregorianCalendar.MONTH, n(1).toInt() + 1); c.set(GregorianCalendar.DAY_OF_MONTH, 1); c.add(GregorianCalendar.DAY_OF_MONTH, -1); Value.Num(dateSerial(c.get(GregorianCalendar.YEAR), c.get(GregorianCalendar.MONTH) + 1, c.get(GregorianCalendar.DAY_OF_MONTH))) }-                    "WEEKNUM" -> Value.Num(serialToCal(n(0)).get(GregorianCalendar.WEEK_OF_YEAR).toDouble())-                    "DATEDIF" -> {-                        val c1 = serialToCal(n(0)); val c2 = serialToCal(n(1)); val unit = sArg(2).uppercase()-                        when (unit) {-                            "D" -> Value.Num(floor(n(1)) - floor(n(0)))-                            "M" -> Value.Num(((c2.get(GregorianCalendar.YEAR) - c1.get(GregorianCalendar.YEAR)) * 12 + (c2.get(GregorianCalendar.MONTH) - c1.get(GregorianCalendar.MONTH))).toDouble())-                            "Y" -> Value.Num((c2.get(GregorianCalendar.YEAR) - c1.get(GregorianCalendar.YEAR)).toDouble())-                            "MD" -> {-                                val d1 = c1.get(GregorianCalendar.DAY_OF_MONTH); val d2 = c2.get(GregorianCalendar.DAY_OF_MONTH)-                                var diff = d2 - d1-                                if (diff < 0) {-                                    val prev = serialToCal(n(1)); prev.set(GregorianCalendar.DAY_OF_MONTH, 1); prev.add(GregorianCalendar.DAY_OF_MONTH, -1)-                                    diff = prev.get(GregorianCalendar.DAY_OF_MONTH) - d1 + d2-                                }-                                Value.Num(diff.toDouble())-                            }-                            "YM" -> {-                                var m = (c2.get(GregorianCalendar.YEAR) - c1.get(GregorianCalendar.YEAR)) * 12 + (c2.get(GregorianCalendar.MONTH) - c1.get(GregorianCalendar.MONTH))-                                if (c2.get(GregorianCalendar.DAY_OF_MONTH) < c1.get(GregorianCalendar.DAY_OF_MONTH)) m---                                Value.Num((((m % 12) + 12) % 12).toDouble())-                            }-                            "YD" -> {-                                val tmp = serialToCal(n(0))-                                tmp.set(GregorianCalendar.YEAR, c2.get(GregorianCalendar.YEAR))-                                if (tmp.timeInMillis > c2.timeInMillis) tmp.add(GregorianCalendar.YEAR, -1)-                                val startSerial = dateSerial(tmp.get(GregorianCalendar.YEAR), tmp.get(GregorianCalendar.MONTH) + 1, tmp.get(GregorianCalendar.DAY_OF_MONTH))-                                Value.Num(floor(n(1)) - startSerial)-                            }-                            else -> throw FormulaException("#NUM!")-                        }-                    }-                    "NETWORKDAYS" -> {-                        var s = floor(n(0)).toInt(); val e = floor(n(1)).toInt(); var cnt = 0-                        val lo = minOf(s, e); val hi = maxOf(s, e)-                        for (d in lo..hi) { val dow = serialToCal(d.toDouble()).get(GregorianCalendar.DAY_OF_WEEK); if (dow != GregorianCalendar.SATURDAY && dow != GregorianCalendar.SUNDAY) cnt++ }-                        Value.Num((if (e < s) -cnt else cnt).toDouble())-                    }-                    "WORKDAY" -> {-                        var d = floor(n(0)).toInt(); var remaining = n(1).toInt(); val step = if (remaining >= 0) 1 else -1-                        while (remaining != 0) { d += step; val dow = serialToCal(d.toDouble()).get(GregorianCalendar.DAY_OF_WEEK); if (dow != GregorianCalendar.SATURDAY && dow != GregorianCalendar.SUNDAY) remaining -= step }-                        Value.Num(d.toDouble())-                    }--                    // ---- financial (Round 3) -----                    "PMT" -> { val r = n(0); val nper = n(1); val pv = n(2); val fv = if (a.size > 3) n(3) else 0.0; Value.Num(if (r == 0.0) -(pv + fv) / nper else -(pv * (1 + r).pow(nper) + fv) * r / ((1 + r).pow(nper) - 1)) }-                    "FV" -> { val r = n(0); val nper = n(1); val pmt = n(2); val pv = if (a.size > 3) n(3) else 0.0; Value.Num(if (r == 0.0) -(pv + pmt * nper) else -(pv * (1 + r).pow(nper) + pmt * ((1 + r).pow(nper) - 1) / r)) }-                    "PV" -> { val r = n(0); val nper = n(1); val pmt = n(2); val fv = if (a.size > 3) n(3) else 0.0; Value.Num(if (r == 0.0) -(fv + pmt * nper) else -(fv + pmt * ((1 + r).pow(nper) - 1) / r) / (1 + r).pow(nper)) }-                    "NPV" -> { val r = n(0); var total = 0.0; var t = 1; for (i in 1 until a.size) for (cf in a[i].values().mapNotNull { numOrNull(it) }) { total += cf / (1 + r).pow(t); t++ }; Value.Num(total) }-                    "NPER" -> { val r = n(0); val pmt = n(1); val pv = n(2); val fv = if (a.size > 3) n(3) else 0.0; Value.Num(if (r == 0.0) -(pv + fv) / pmt else ln((pmt - fv * r) / (pmt + pv * r)) / ln(1 + r)) }--                    // ---- info / logical (Phase 1) -----                    "ISEVEN" -> Value.Bool(truncate(n(0)).toLong() % 2L == 0L)-                    "ISODD" -> Value.Bool(truncate(n(0)).toLong() % 2L != 0L)-                    "ISFORMULA" -> { val r = a[0].ref(); Value.Bool(r != null && cellAt(r.sheet, minOf(r.r1, r.r2), minOf(r.c1, r.c2))?.formula != null) }-                    "ISREF" -> Value.Bool(a[0].ref() != null)-                    "ISNONTEXT" -> Value.Bool(safeValue(a[0]) !is Value.Str)-                    "N" -> when (val vv = v(0)) {-                        is Value.Num -> vv-                        is Value.Bool -> Value.Num(if (vv.b) 1.0 else 0.0)-                        is Value.Err -> vv-                        else -> Value.Num(0.0)-                    }-                    "TYPE" -> Value.Num(when (safeValue(a[0])) {-                        is Value.Num -> 1.0; is Value.Str -> 2.0; is Value.Bool -> 4.0-                        is Value.Err -> 16.0; Value.Blank -> 1.0-                    })-                    "ERROR.TYPE" -> {-                        val code = isError(a[0])-                        val t = when (code) { "#NULL!" -> 1; "#DIV/0!" -> 2; "#VALUE!" -> 3; "#REF!" -> 4; "#NAME?" -> 5; "#NUM!" -> 6; "#N/A" -> 7; else -> null }-                        if (t == null) throw FormulaException("#N/A") else Value.Num(t.toDouble())-                    }-                    "SHEET" -> { val idx = workbook.keys.indexOf(sheetName); Value.Num((if (idx < 0) 1 else idx + 1).toDouble()) }-                    "SHEETS" -> Value.Num((if (workbook.isEmpty()) 1 else workbook.size).toDouble())--                    // ---- math (Phase 1) -----                    "QUOTIENT" -> { val d = n(1); if (d == 0.0) throw FormulaException("#DIV/0!") else Value.Num(truncate(n(0) / d)) }-                    "SEC" -> Value.Num(1.0 / kotlin.math.cos(n(0)))-                    "CSC" -> Value.Num(1.0 / kotlin.math.sin(n(0)))-                    "COT" -> Value.Num(1.0 / kotlin.math.tan(n(0)))-                    "SINH" -> Value.Num(kotlin.math.sinh(n(0)))-                    "COSH" -> Value.Num(kotlin.math.cosh(n(0)))-                    "TANH" -> Value.Num(kotlin.math.tanh(n(0)))-                    "ASINH" -> Value.Num(kotlin.math.asinh(n(0)))-                    "ACOSH" -> Value.Num(kotlin.math.acosh(n(0)))-                    "ATANH" -> Value.Num(kotlin.math.atanh(n(0)))-                    "MULTINOMIAL" -> { val ns = allNums().map { it.toInt() }; var r = factD(ns.sum()); for (x in ns) r /= factD(x); Value.Num(r) }-                    "SUMX2PY2" -> { val (xs, ys) = pair(0, 1); var t = 0.0; for (i in xs.indices) t += xs[i] * xs[i] + ys[i] * ys[i]; Value.Num(t) }-                    "SUMX2MY2" -> { val (xs, ys) = pair(0, 1); var t = 0.0; for (i in xs.indices) t += xs[i] * xs[i] - ys[i] * ys[i]; Value.Num(t) }-                    "SUMXMY2" -> { val (xs, ys) = pair(0, 1); var t = 0.0; for (i in xs.indices) t += (xs[i] - ys[i]).pow(2); Value.Num(t) }-                    "BASE" -> { val num = n(0).toLong(); val radix = n(1).toInt(); val minLen = if (a.size > 2) n(2).toInt() else 0; if (radix < 2 || radix > 36) throw FormulaException("#NUM!") else Value.Str(num.toString(radix).uppercase().padStart(minLen, '0')) }-                    "DECIMAL" -> { val radix = n(1).toInt(); if (radix < 2 || radix > 36) throw FormulaException("#NUM!") else Value.Num((sArg(0).trim().toLongOrNull(radix) ?: throw FormulaException("#NUM!")).toDouble()) }-                    "ARABIC" -> Value.Num(romanToArabic(sArg(0)).toDouble())-                    "ROMAN" -> Value.Str(arabicToRoman(n(0).toInt()))--                    // ---- bitwise (Phase 1) -----                    "BITAND" -> Value.Num((n(0).toLong() and n(1).toLong()).toDouble())-                    "BITOR" -> Value.Num((n(0).toLong() or n(1).toLong()).toDouble())-                    "BITXOR" -> Value.Num((n(0).toLong() xor n(1).toLong()).toDouble())-                    "BITLSHIFT" -> { val sh = n(1).toInt(); Value.Num((if (sh >= 0) n(0).toLong() shl sh else n(0).toLong() shr -sh).toDouble()) }-                    "BITRSHIFT" -> { val sh = n(1).toInt(); Value.Num((if (sh >= 0) n(0).toLong() shr sh else n(0).toLong() shl -sh).toDouble()) }--                    // ---- statistics (Phase 1) -----                    "GEOMEAN" -> { val ns = allNums(); if (ns.isEmpty()) throw FormulaException("#NUM!") else Value.Num(exp(ns.sumOf { ln(it) } / ns.size)) }-                    "HARMEAN" -> { val ns = allNums(); if (ns.isEmpty()) throw FormulaException("#NUM!") else Value.Num(ns.size / ns.sumOf { 1.0 / it }) }-                    "AVEDEV" -> { val ns = allNums(); if (ns.isEmpty()) throw FormulaException("#NUM!") else { val m = ns.average(); Value.Num(ns.sumOf { abs(it - m) } / ns.size) } }-                    "DEVSQ" -> { val ns = allNums(); if (ns.isEmpty()) Value.Num(0.0) else { val m = ns.average(); Value.Num(ns.sumOf { (it - m).pow(2) }) } }-                    "CORREL", "PEARSON" -> { val (xs, ys) = pair(0, 1); Value.Num(correl(xs, ys)) }-                    "COVAR" -> { val (xs, ys) = pair(0, 1); if (xs.isEmpty()) throw FormulaException("#DIV/0!") else { val mx = xs.average(); val my = ys.average(); var t = 0.0; for (i in xs.indices) t += (xs[i] - mx) * (ys[i] - my); Value.Num(t / xs.size) } }-                    "SLOPE" -> { val (ys, xs) = pair(0, 1); Value.Num(slope(ys, xs)) }-                    "INTERCEPT" -> { val (ys, xs) = pair(0, 1); Value.Num(ys.average() - slope(ys, xs) * xs.average()) }-                    "FORECAST" -> { val x = n(0); val ys = arr(1); val xs = arr(2); val m = minOf(xs.size, ys.size); val yy = ys.take(m); val xx = xs.take(m); Value.Num(yy.average() + slope(yy, xx) * (x - xx.average())) }-                    "QUARTILE" -> { val list = arr(0).sorted(); val q = n(1).toInt(); if (list.isEmpty() || q < 0 || q > 4) throw FormulaException("#NUM!") else Value.Num(percentileOf(list, q / 4.0)) }-                    "PERCENTRANK" -> {-                        val list = arr(0).sorted(); val x = n(1)-                        if (list.isEmpty()) throw FormulaException("#NUM!")-                        val res = when {-                            x <= list.first() -> 0.0-                            x >= list.last() -> 1.0-                            else -> { var i = 0; while (i < list.size && list[i] <= x) i++; val lo = i - 1; val frac = if (list[i] == list[lo]) 0.0 else (x - list[lo]) / (list[i] - list[lo]); (lo + frac) / (list.size - 1) }-                        }-                        Value.Num(res)-                    }-                    "AVERAGEA" -> { val vs = valsA(); if (vs.isEmpty()) throw FormulaException("#DIV/0!") else Value.Num(vs.average()) }-                    "MAXA" -> valsA().maxOrNull()?.let { Value.Num(it) } ?: Value.Num(0.0)-                    "MINA" -> valsA().minOrNull()?.let { Value.Num(it) } ?: Value.Num(0.0)--                    // ---- text (Phase 1) -----                    "FIXED" -> { val dec = (if (a.size > 1) n(1).toInt() else 2).coerceAtLeast(0); val noComma = a.size > 2 && truthy(v(2)); Value.Str(String.format((if (noComma) "%." else "%,.") + dec + "f", n(0))) }-                    "DOLLAR" -> { val dec = (if (a.size > 1) n(1).toInt() else 2).coerceAtLeast(0); Value.Str("$" + String.format("%,.${dec}f", n(0))) }-                    "UNICHAR" -> { val cp = n(0).toInt(); if (cp <= 0) throw FormulaException("#VALUE!") else Value.Str(String(Character.toChars(cp))) }-                    "UNICODE" -> { val s = sArg(0); if (s.isEmpty()) throw FormulaException("#VALUE!") else Value.Num(s.codePointAt(0).toDouble()) }-                    "TEXTBEFORE" -> textBeforeAfter(sArg(0), sArg(1), if (a.size > 2) n(2).toInt() else 1, before = true)-                    "TEXTAFTER" -> textBeforeAfter(sArg(0), sArg(1), if (a.size > 2) n(2).toInt() else 1, before = false)--                    // ---- date (Phase 1) -----                    "YEARFRAC" -> Value.Num(yearFrac(n(0), n(1), if (a.size > 2) n(2).toInt() else 0))-                    "ISOWEEKNUM" -> Value.Num(isoWeekNum(n(0)).toDouble())-                    "DAYS360" -> Value.Num(days360(n(0), n(1), a.size > 2 && truthy(v(2))).toDouble())--                    // ---- financial (Phase 1) -----                    "RATE" -> {-                        val nper = n(0); val pmt = n(1); val pv = n(2); val fv = if (a.size > 3) n(3) else 0.0-                        val type = if (a.size > 4) n(4).toInt() else 0; var r = if (a.size > 5) n(5) else 0.1-                        fun f(rate: Double) = if (rate == 0.0) pv + pmt * nper + fv else pv * (1 + rate).pow(nper) + pmt * (1 + rate * type) * ((1 + rate).pow(nper) - 1) / rate + fv-                        for (iter in 0 until 100) { val dr = 1e-6; val d = (f(r + dr) - f(r)) / dr; if (d == 0.0) break; val nr = r - f(r) / d; if (abs(nr - r) < 1e-9) { r = nr; break }; r = nr }-                        Value.Num(r)-                    }-                    "IPMT" -> { val r = n(0); val per = n(1).toInt(); val nper = n(2); val pv = n(3); val fv = if (a.size > 4) n(4) else 0.0; val type = if (a.size > 5) n(5).toInt() else 0; Value.Num(ipmtCalc(r, per, nper, pv, fv, type)) }-                    "PPMT" -> { val r = n(0); val per = n(1).toInt(); val nper = n(2); val pv = n(3); val fv = if (a.size > 4) n(4) else 0.0; val type = if (a.size > 5) n(5).toInt() else 0; Value.Num(pmtCalc(r, nper, pv, fv, type) - ipmtCalc(r, per, nper, pv, fv, type)) }-                    "SLN" -> Value.Num((n(0) - n(1)) / n(2))-                    "SYD" -> { val cost = n(0); val salvage = n(1); val life = n(2); val per = n(3); Value.Num((cost - salvage) * (life - per + 1) * 2.0 / (life * (life + 1))) }-                    "IRR" -> {-                        val flows = arr(0); var r = if (a.size > 1) n(1) else 0.1-                        for (iter in 0 until 100) {-                            var npv = 0.0; var d = 0.0-                            for (t in flows.indices) { npv += flows[t] / (1 + r).pow(t); if (t > 0) d += -t * flows[t] / (1 + r).pow(t + 1) }-                            if (d == 0.0) break; val nr = r - npv / d; if (abs(nr - r) < 1e-9) { r = nr; break }; r = nr-                        }-                        Value.Num(r)-                    }-                    "CUMIPMT" -> { val r = n(0); val nper = n(1); val pv = n(2); val s = n(3).toInt(); val e = n(4).toInt(); val type = n(5).toInt(); var t = 0.0; for (p in s..e) t += ipmtCalc(r, p, nper, pv, 0.0, type); Value.Num(t) }-                    "CUMPRINC" -> { val r = n(0); val nper = n(1); val pv = n(2); val s = n(3).toInt(); val e = n(4).toInt(); val type = n(5).toInt(); val pmt = pmtCalc(r, nper, pv, 0.0, type); var t = 0.0; for (p in s..e) t += pmt - ipmtCalc(r, p, nper, pv, 0.0, type); Value.Num(t) }--                    // ---- lookup (Phase 1) -----                    "ROW" -> if (a.isEmpty()) Value.Num((curRow + 1).toDouble()) else { val r = a[0].ref() ?: throw FormulaException("#REF!"); Value.Num((minOf(r.r1, r.r2) + 1).toDouble()) }-                    "COLUMN" -> if (a.isEmpty()) Value.Num((curCol + 1).toDouble()) else { val r = a[0].ref() ?: throw FormulaException("#REF!"); Value.Num((minOf(r.c1, r.c2) + 1).toDouble()) }-                    "LOOKUP" -> {-                        val key = v(0); val lv = a[1].values(); val rv = if (a.size > 2) a[2].values() else lv-                        var best = -1; val k = cmpNum(key)-                        for (i in lv.indices) { if (compareOp("=", lv[i], key)) { best = i; break }; val nv = cmpNum(lv[i]); if (k != null && nv != null && nv <= k) best = i }-                        if (best < 0 || best >= rv.size) throw FormulaException("#N/A") else rv[best]-                    }-                    "OFFSET" -> { val r = a[0].ref() ?: throw FormulaException("#REF!"); evalOn(r.sheet, minOf(r.r1, r.r2) + n(1).toInt(), minOf(r.c1, r.c2) + n(2).toInt()) }-                    "ADDRESS" -> {-                        val row = n(0).toInt(); val col = n(1).toInt(); val absNum = if (a.size > 2) n(2).toInt() else 1-                        val colStr = indexToCol(col - 1)-                        val res = when (absNum) { 1 -> "\$$colStr\$$row"; 2 -> "$colStr\$$row"; 3 -> "\$$colStr$row"; else -> "$colStr$row" }-                        if (a.size > 4 && sArg(4).isNotEmpty()) Value.Str("${sArg(4)}.$res") else Value.Str(res)-                    }-                    "INDIRECT" -> { val (rr, cc) = a1ToCoords(sArg(0)) ?: throw FormulaException("#REF!"); evaluateCellV(rr, cc) }-                    "HYPERLINK" -> Value.Str(if (a.size > 1) sArg(1) else sArg(0))--                    else -> throw FormulaException("#NAME?")-                }-            }--            private fun boolOrNull(v: Value): Boolean? = when (v) {-                is Value.Num -> v.v != 0.0-                is Value.Bool -> v.b-                else -> null-            }--            private fun gcdL(x: Long, y: Long): Long = if (y == 0L) abs(x) else gcdL(y, x % y)--            /** Returns the error code if the thunk evaluates to/throws an error, else null. */-            private fun isError(t: ArgThunk): String? = try {-                (t.value() as? Value.Err)?.code-            } catch (e: FormulaException) { e.code }--            /** Evaluates a thunk, returning Value.Err instead of throwing (for IS* type checks). */-            private fun safeValue(t: ArgThunk): Value = try { t.value() } catch (e: FormulaException) { Value.Err(e.code) }--            private fun forEachRangeCell(arg: Arg, action: (Value) -> Unit) {-                when (arg) {-                    is Arg.Scalar -> action(arg.v)-                    is Arg.RangeRef -> for (r in minOf(arg.r1, arg.r2)..maxOf(arg.r1, arg.r2))-                        for (c in minOf(arg.c1, arg.c2)..maxOf(arg.c1, arg.c2)) {-                            val cell = sheet.rows.getOrNull(r)?.cells?.getOrNull(c)-                            if (cell != null && cell.isCovered) continue-                            action(evaluateCellV(r, c))-                        }-                }-            }--            /** SUMIF/AVERAGEIF: range, criteria, [sumRange]. Aligns sumRange by offset. */-            private fun conditionalAgg(a: List<ArgThunk>, sumKind: Boolean, reduce: (List<Double>) -> Double): Value {-                val rangeArg = a[0].arg()-                val crit = a[1].value()-                val sumArg = if (a.size > 2) a[2].arg() else rangeArg-                val rRef = rangeArg as? Arg.RangeRef-                val sRef = sumArg as? Arg.RangeRef-                val matched = ArrayList<Double>()-                if (rRef != null) {-                    val r0 = minOf(rRef.r1, rRef.r2); val c0 = minOf(rRef.c1, rRef.c2)-                    val rs0 = sRef?.let { minOf(it.r1, it.r2) } ?: r0-                    val cs0 = sRef?.let { minOf(it.c1, it.c2) } ?: c0-                    for (r in r0..maxOf(rRef.r1, rRef.r2)) {-                        for (c in c0..maxOf(rRef.c1, rRef.c2)) {-                            val cell = sheet.rows.getOrNull(r)?.cells?.getOrNull(c)-                            if (cell != null && cell.isCovered) continue-                            if (matchesCriteria(evaluateCellV(r, c), crit)) {-                                val sv = evaluateCellV(rs0 + (r - r0), cs0 + (c - c0))-                                numOrNull(sv)?.let { matched.add(it) }-                            }-                        }-                    }-                }-                if (!sumKind) return Value.Num(matched.size.toDouble())-                return Value.Num(reduce(matched))-            }--            private fun lookup(a: List<ArgThunk>, horizontal: Boolean): Value {-                val key = a[0].value()-                val rng = a[1].arg() as? Arg.RangeRef ?: throw FormulaException("#N/A")-                val index = n2(a, 2).toInt() // 1-based row/col offset into range-                val approx = if (a.size > 3) truthy(a[3].value()) else true-                val r0 = minOf(rng.r1, rng.r2); val r1e = maxOf(rng.r1, rng.r2)-                val c0 = minOf(rng.c1, rng.c2); val c1e = maxOf(rng.c1, rng.c2)-                var foundLine = -1-                if (horizontal) {-                    var best = -1-                    for (c in c0..c1e) {-                        val cv = evaluateCellV(r0, c)-                        if (compareOp("=", cv, key)) { foundLine = c; break }-                        if (approx && cmpNum(cv) != null && cmpNum(key) != null && cmpNum(cv)!! <= cmpNum(key)!!) best = c-                    }-                    if (foundLine < 0) foundLine = best-                    if (foundLine < 0) throw FormulaException("#N/A")-                    val targetRow = r0 + index - 1-                    if (targetRow > r1e) throw FormulaException("#REF!")-                    return evaluateCellV(targetRow, foundLine)-                } else {-                    var best = -1-                    for (r in r0..r1e) {-                        val cv = evaluateCellV(r, c0)-                        if (compareOp("=", cv, key)) { foundLine = r; break }-                        if (approx && cmpNum(cv) != null && cmpNum(key) != null && cmpNum(cv)!! <= cmpNum(key)!!) best = r-                    }-                    if (foundLine < 0) foundLine = best-                    if (foundLine < 0) throw FormulaException("#N/A")-                    val targetCol = c0 + index - 1-                    if (targetCol > c1e) throw FormulaException("#REF!")-                    return evaluateCellV(foundLine, targetCol)-                }-            }--            private fun matchFn(a: List<ArgThunk>): Value {-                val key = a[0].value()-                val rng = a[1].arg() as? Arg.RangeRef ?: throw FormulaException("#N/A")-                val type = if (a.size > 2) n2(a, 2).toInt() else 1-                val cells = ArrayList<Value>()-                for (r in minOf(rng.r1, rng.r2)..maxOf(rng.r1, rng.r2))-                    for (c in minOf(rng.c1, rng.c2)..maxOf(rng.c1, rng.c2))-                        cells.add(evaluateCellV(r, c))-                when (type) {-                    0 -> { val i = cells.indexOfFirst { compareOp("=", it, key) }; if (i < 0) throw FormulaException("#N/A") else return Value.Num((i + 1).toDouble()) }-                    1 -> { // largest value <= key, assumes ascending-                        var best = -1-                        val k = cmpNum(key)-                        for ((i, cv) in cells.withIndex()) { val n = cmpNum(cv); if (k != null && n != null && n <= k) best = i }-                        if (best < 0) throw FormulaException("#N/A") else return Value.Num((best + 1).toDouble())-                    }-                    else -> { // -1: smallest value >= key, assumes descending-                        var best = -1-                        val k = cmpNum(key)-                        for ((i, cv) in cells.withIndex()) { val n = cmpNum(cv); if (k != null && n != null && n >= k) best = i }-                        if (best < 0) throw FormulaException("#N/A") else return Value.Num((best + 1).toDouble())-                    }-                }-            }--            private fun indexFn(a: List<ArgThunk>): Value {-                val rng = a[0].arg() as? Arg.RangeRef ?: return a[0].value()-                val r0 = minOf(rng.r1, rng.r2); val c0 = minOf(rng.c1, rng.c2)-                val rn = if (a.size > 1) n2(a, 1).toInt() else 1-                val cn = if (a.size > 2) n2(a, 2).toInt() else 1-                val targetRow = if (rn <= 0) r0 else r0 + rn - 1-                val targetCol = if (cn <= 0) c0 else c0 + cn - 1-                if (targetRow > maxOf(rng.r1, rng.r2) || targetCol > maxOf(rng.c1, rng.c2)) throw FormulaException("#REF!")-                return evaluateCellV(targetRow, targetCol)-            }--            private fun n2(a: List<ArgThunk>, i: Int): Double = num(a[i].value())--            private fun correl(xs: List<Double>, ys: List<Double>): Double {-                val n = xs.size; if (n == 0) throw FormulaException("#DIV/0!")-                val mx = xs.average(); val my = ys.average()-                var sxy = 0.0; var sxx = 0.0; var syy = 0.0-                for (i in 0 until n) { sxy += (xs[i] - mx) * (ys[i] - my); sxx += (xs[i] - mx).pow(2); syy += (ys[i] - my).pow(2) }-                val d = sqrt(sxx * syy); if (d == 0.0) throw FormulaException("#DIV/0!"); return sxy / d-            }--            private fun slope(ys: List<Double>, xs: List<Double>): Double {-                val n = xs.size; if (n == 0) throw FormulaException("#DIV/0!")-                val mx = xs.average(); val my = ys.average()-                var num = 0.0; var den = 0.0-                for (i in 0 until n) { num += (xs[i] - mx) * (ys[i] - my); den += (xs[i] - mx).pow(2) }-                if (den == 0.0) throw FormulaException("#DIV/0!"); return num / den-            }--            private fun percentileOf(sorted: List<Double>, p: Double): Double {-                if (sorted.isEmpty()) throw FormulaException("#NUM!")-                val rank = p * (sorted.size - 1); val lo = floor(rank).toInt(); val hi = ceil(rank).toInt()-                return if (lo == hi) sorted[lo] else sorted[lo] + (rank - lo) * (sorted[hi] - sorted[lo])-            }--            private fun textBeforeAfter(text: String, delim: String, instance: Int, before: Boolean): Value {-                if (delim.isEmpty()) return Value.Str(if (before) "" else text)-                var idx = -1; var count = 0; var from = 0-                while (true) { val f = text.indexOf(delim, from); if (f < 0) break; count++; if (count == instance) { idx = f; break }; from = f + delim.length }-                if (idx < 0) throw FormulaException("#N/A")-                return Value.Str(if (before) text.substring(0, idx) else text.substring(idx + delim.length))-            }--            private fun days360(start: Double, end: Double, european: Boolean): Int {-                val c1 = serialToCal(start); val c2 = serialToCal(end)-                var d1 = c1.get(GregorianCalendar.DAY_OF_MONTH); var d2 = c2.get(GregorianCalendar.DAY_OF_MONTH)-                val m1 = c1.get(GregorianCalendar.MONTH) + 1; val m2 = c2.get(GregorianCalendar.MONTH) + 1-                val y1 = c1.get(GregorianCalendar.YEAR); val y2 = c2.get(GregorianCalendar.YEAR)-                if (european) { if (d1 == 31) d1 = 30; if (d2 == 31) d2 = 30 } else { if (d1 == 31) d1 = 30; if (d2 == 31 && d1 == 30) d2 = 30 }-                return (y2 - y1) * 360 + (m2 - m1) * 30 + (d2 - d1)-            }--            private fun yearFrac(start: Double, end: Double, basis: Int): Double {-                val days = abs(floor(end) - floor(start))-                return when (basis) {-                    0 -> abs(days360(start, end, false)) / 360.0-                    1 -> days / 365.25-                    2 -> days / 360.0-                    3 -> days / 365.0-                    4 -> abs(days360(start, end, true)) / 360.0-                    else -> days / 365.0-                }-            }--            private fun isoWeekNum(serial: Double): Int {-                val cal = serialToCal(serial)-                cal.firstDayOfWeek = GregorianCalendar.MONDAY-                cal.minimalDaysInFirstWeek = 4-                return cal.get(GregorianCalendar.WEEK_OF_YEAR)-            }--            private fun fvOf(r: Double, nper: Double, pmt: Double, pv: Double, type: Int): Double =-                if (r == 0.0) -(pv + pmt * nper) else { val p = (1 + r).pow(nper); -(pv * p + pmt * (1 + r * type) * (p - 1) / r) }--            private fun pmtCalc(r: Double, nper: Double, pv: Double, fv: Double, type: Int): Double =-                if (r == 0.0) -(pv + fv) / nper else { val p = (1 + r).pow(nper); -(pv * p + fv) * r / ((1 + r * type) * (p - 1)) }--            private fun ipmtCalc(r: Double, per: Int, nper: Double, pv: Double, fv: Double, type: Int): Double {-                val pmt = pmtCalc(r, nper, pv, fv, type)-                var ip = fvOf(r, (per - 1).toDouble(), pmt, pv, type) * r-                if (type == 1) ip /= (1 + r)-                return ip-            }--            private fun a1ToCoords(t: String): Pair<Int, Int>? {-                val cell = t.substringAfterLast('.').replace("$", "").trim()-                val m = Regex("([A-Za-z]+)(\\d+)").find(cell) ?: return null-                return (m.groupValues[2].toIntOrNull()?.minus(1) ?: return null) to colToIndex(m.groupValues[1])-            }--            private fun textFormat(value: Double, fmt: String): String {-                val f = fmt.trim()-                if (f.contains("%")) {-                    val decimals = f.substringAfter('.', "").count { it == '0' || it == '#' }-                    return String.format("%.${decimals}f%%", value * 100)-                }-                val grouping = f.contains(",")-                val decimals = f.substringAfter('.', "").count { it == '0' || it == '#' }-                val pattern = (if (grouping) "%,." else "%.") + decimals + "f"-                return String.format(pattern, value)-            }--            private fun peek(): Char = if (pos < s.length) s[pos] else '\u0000'-            private fun skipWs() { while (pos < s.length && s[pos].isWhitespace()) pos++ }-            private fun match(token: String): Boolean {-                skipWs()-                if (s.startsWith(token, pos)) { pos += token.length; return true }-                return false-            }-        }-    }-}
office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.kt b/office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.ktindex 65d2f1ec8a..20bd10fafd 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.kt@@ -2,6 +2,7 @@ package com.vayunmathur.office.odf  import androidx.compose.ui.text.style.TextAlign import com.vayunmathur.library.ui.odf.*+import com.vayunmathur.office.util.OfficeNative import org.xmlpull.v1.XmlPullParser  /**@@ -534,7 +535,7 @@ internal object OoxmlXlsx {         // formatted per the number format so dates/percent/currency don't show as bare numbers.         val fmtForDisplay = resolvedFmt ?: if (base.valueType == "date") OdfNumberFormat(isDate = true) else null         val displayText = if (base.numberValue != null && base.valueType != "boolean" && fmtForDisplay != null)-            OdfFormulaEngine.formatWithStyle(base.numberValue!!, fmtForDisplay) else base.text+            OfficeNative.formatValue(base.numberValue!!, fmtForDisplay) else base.text         return base.copy(             text = displayText,             formula = formula ?: base.formula,
office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt b/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.ktindex 348b66b46e..0b89ffa76b 100644--- a/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt@@ -61,6 +61,7 @@ import com.vayunmathur.library.ui.TextField import com.vayunmathur.library.ui.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf@@ -120,6 +121,7 @@ import androidx.compose.ui.unit.sp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import com.vayunmathur.office.odf.*+import com.vayunmathur.office.util.OfficeNative import com.vayunmathur.library.ui.odf.* import androidx.compose.ui.res.stringResource import com.vayunmathur.office.R@@ -1360,7 +1362,10 @@ fun SpreadsheetView(         }          val sheet = doc.sheets[selectedSheet]-        val workbook = remember(doc) { doc.sheets.associateBy { it.name } }+        // Native formula workbook: built once per document snapshot over the SAME ordered sheet list+        // (doc.sheets) whose index we pass as sheetIdx, so cross-sheet references resolve correctly.+        val wbHandle = remember(doc) { OfficeNative.createWorkbook(doc.sheets, System.currentTimeMillis()) }+        DisposableEffect(doc) { onDispose { OfficeNative.nativeFree(wbHandle) } }         val maxCols = sheet.rows.maxOfOrNull { it.cells.count { c -> !c.isCovered } } ?: 0         fun colWidthDp(start: Int, span: Int): androidx.compose.ui.unit.Dp {             var w = 0f@@ -1409,7 +1414,7 @@ fun SpreadsheetView(                                         colspanSkip = if (cell.spannedColumns > 1) cell.spannedColumns - 1 else 0                                         val isEditing = editingCell?.let { it.first == selectedSheet && it.second == rowIdx && it.third == cellIdx } == true                                         val isMatch = searchQuery.isNotEmpty() && cell.text.contains(searchQuery, ignoreCase = true)-                                        val displayText = OdfFormulaEngine.displayValue(sheet, rowIdx, cellIdx, workbook, sheet.name)+                                        val displayText = OfficeNative.nativeDisplayValue(wbHandle, selectedSheet, rowIdx, cellIdx) ?: ""                                         val cf = if (cell.condFormats.isEmpty()) null else evalCondFormat(cell.condFormats, cell.numberValue ?: displayText.toDoubleOrNull(), displayText)                                         val effBg = cf?.backgroundColor ?: cell.backgroundColor                                         Box(@@ -1434,7 +1439,7 @@ fun SpreadsheetView(                                                 } else Modifier)                                                 .padding(8.dp, 4.dp)                                         ) {-                                            val cellAlign = cell.alignment ?: if (OdfFormulaEngine.isNumeric(sheet, rowIdx, cellIdx, workbook, sheet.name)) TextAlign.End else null+                                            val cellAlign = cell.alignment ?: if (OfficeNative.nativeIsNumeric(wbHandle, selectedSheet, rowIdx, cellIdx)) TextAlign.End else null                                             Text(displayText,                                                 style = MaterialTheme.typography.bodyMedium.let { if (fontSizeMultiplier != 1f && it.fontSize != TextUnit.Unspecified) it.copy(fontSize = it.fontSize * fontSizeMultiplier) else it },                                                 fontWeight = if (cell.bold) FontWeight.Bold else null,
office/src/main/java/com/vayunmathur/office/util/DocumentTreeCrdt.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/DocumentTreeCrdt.kt b/office/src/main/java/com/vayunmathur/office/util/DocumentTreeCrdt.ktindex 6b1b90cbe6..d4b9f21b6e 100644--- a/office/src/main/java/com/vayunmathur/office/util/DocumentTreeCrdt.kt+++ b/office/src/main/java/com/vayunmathur/office/util/DocumentTreeCrdt.kt@@ -1,244 +1,32 @@ package com.vayunmathur.office.util -import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json- /**- * A hierarchical (tree) CRDT over a flat-ODF XML document. Every character/element is a **node with a- * parent**, so deleting an element deletes its whole subtree — including characters a peer inserted- * into it concurrently. Text within a node merges at character level (RGA among sibling char nodes),- * and an element's **attributes merge by last-writer-wins** (elements keep identity across attribute- * edits, so concurrent formatting changes never drop the element or its text).+ * Thin handle wrapper over the native `office_engine` document-tree CRDT.+ *+ * The CRDT algorithm (hierarchical tree over flat-ODF XML, RGA text merge, LWW+ * attributes) lives in the Rust crate; this class only owns a native handle and+ * forwards calls. The native serialization is byte-identical to the previous+ * Kotlin serializer, so the signed collaboration wire format is unchanged.  *- * Node kinds: "e" element (has children; [payload] is the open tag, [name] the tag name), "s" opaque- * leaf (self-closing element / `<?xml?>` / comment / doctype), "c" character, "r" raw run (base64).+ * Call [close] to release the native handle when the CRDT is no longer needed.  */-class DocumentTreeCrdt(private val device: String) {--    @Serializable-    data class Node(-        val id: String,-        val parent: String,-        val left: String,-        val kind: String,-        var payload: String,-        var deleted: Boolean = false,-        val lamport: Long,-        val dev: String,-        val name: String = "",      // element tag name (kind "e"); used for identity across attr edits-        var attrLamport: Long = 0,  // LWW clock for attribute (payload) updates on elements-        var attrDev: String = "",   // device of the last attribute write (LWW tie-break)-    )--    @Serializable-    data class State(val device: String, val clock: Long, val nodes: List<Node>)--    private val nodes = LinkedHashMap<String, Node>()-    private val childrenByParent = HashMap<String, MutableList<Node>>() // parent id -> children (incl. tombstones)-    private var clock = 0L-    private val json = Json { ignoreUnknownKeys = true }--    fun toState(): State = State(device, clock, nodes.values.map { it.copy() })--    fun loadState(jsonStr: String) {-        val s = runCatching { json.decodeFromString<State>(jsonStr) }.getOrNull() ?: return-        nodes.clear(); childrenByParent.clear()-        for (n in s.nodes) { val c = n.copy(); nodes[c.id] = c; childrenByParent.getOrPut(c.parent) { ArrayList() }.add(c) }-        clock = s.clock-    }--    fun serialize(): String = json.encodeToString(toState())--    private fun index(node: Node) { childrenByParent.getOrPut(node.parent) { ArrayList() }.add(node) }--    /** Merges a batch of remote node ops. Commutative + idempotent; deletion + attrs are monotonic. */-    fun apply(ops: List<Node>) {-        for (op in ops) {-            clock = maxOf(clock, maxOf(op.lamport, op.attrLamport))-            val cur = nodes[op.id]-            if (cur == null) { val c = op.copy(); nodes[c.id] = c; index(c) }-            else {-                if (op.deleted) cur.deleted = true-                // Attribute LWW: the write with the higher lamport wins (device breaks ties).-                if (op.kind == "e" && (op.attrLamport > cur.attrLamport ||-                        (op.attrLamport == cur.attrLamport && op.attrDev > cur.attrDev))) {-                    cur.payload = op.payload; cur.attrLamport = op.attrLamport; cur.attrDev = op.attrDev-                }-            }-        }-    }--    fun render(): String {-        val sb = StringBuilder()-        renderChildren("", sb)-        return sb.toString()-    }--    private fun renderChildren(parent: String, sb: StringBuilder) {-        for (node in orderedChildren(parent)) {-            if (node.deleted) continue // skip deleted node + its subtree (never descend)-            when (node.kind) {-                "e" -> { sb.append(node.payload); renderChildren(node.id, sb); sb.append(closeTagOf(node.payload)) }-                else -> sb.append(node.payload)-            }-        }-    }--    /** RGA order of a parent's children (incl. tombstones, needed to chain `left`). O(children). */-    private fun orderedChildren(parent: String): List<Node> {-        val kids = childrenByParent[parent] ?: return emptyList()-        val byLeft = HashMap<String, MutableList<Node>>()-        for (n in kids) byLeft.getOrPut(n.left) { mutableListOf() }.add(n)-        val cmp = compareByDescending<Node> { it.lamport }.thenByDescending { it.dev }-        for (l in byLeft.values) l.sortWith(cmp)-        val result = ArrayList<Node>(kids.size)-        val stack = ArrayDeque<Node>()-        byLeft[""]?.asReversed()?.forEach { stack.addLast(it) }-        while (stack.isNotEmpty()) {-            val e = stack.removeLast()-            result.add(e)-            byLeft[e.id]?.asReversed()?.forEach { stack.addLast(it) }-        }-        return result-    }--    // --- Reconcile the current tree toward a new flat-XML state, producing ops -----    fun update(xml: String): List<Node> {-        val ops = ArrayList<Node>()-        diffChildren("", parse(xml).children, ops)-        return ops-    }--    private fun newId(): String { clock += 1; return "$clock:$device" }--    private fun keyOfDesired(d: Desired): String = when (d) {-        is Desired.El -> if (d.selfClosing) "s:" + d.tag else "e:" + nameOf(d.tag)-        is Desired.Text -> (if (d.raw) "r:" else "c:") + d.text-    }--    private fun keyOfNode(n: Node): String = if (n.kind == "e") "e:" + n.name else n.kind + ":" + n.payload--    private fun diffChildren(parent: String, desired: List<Desired>, ops: MutableList<Node>) {-        val current = (childrenByParent[parent]?.let { orderedChildren(parent) } ?: emptyList()).filter { !it.deleted }-        val keyC = current.map { keyOfNode(it) }-        val keyD = desired.map { keyOfDesired(it) }--        var pre = 0-        while (pre < current.size && pre < desired.size && keyC[pre] == keyD[pre]) pre++-        var suf = 0-        while (suf < current.size - pre && suf < desired.size - pre &&-            keyC[current.size - 1 - suf] == keyD[desired.size - 1 - suf]) suf++--        var prevId = ""-        fun reuse(node: Node, d: Desired) {-            if (d is Desired.El && node.kind == "e") {-                if (node.payload != d.tag) { // attributes changed → LWW update, identity kept-                    node.payload = d.tag; node.attrLamport = ++clock; node.attrDev = device-                    ops.add(node.copy())-                }-                if (!d.selfClosing) diffChildren(node.id, d.children, ops)-            }-            prevId = node.id-        }-        fun insert(d: Desired) {-            val id = newId()-            val kind = when (d) { is Desired.El -> if (d.selfClosing) "s" else "e"; is Desired.Text -> if (d.raw) "r" else "c" }-            val payload = when (d) { is Desired.El -> d.tag; is Desired.Text -> d.text }-            val name = if (d is Desired.El && !d.selfClosing) nameOf(d.tag) else ""-            val node = Node(id, parent, prevId, kind, payload, false, clock, device, name, if (kind == "e") clock else 0, if (kind == "e") device else "")-            nodes[id] = node; index(node); ops.add(node.copy())-            if (d is Desired.El && !d.selfClosing) diffChildren(id, d.children, ops)-            prevId = id-        }+class DocumentTreeCrdt(device: String) {+    private val handle: Long = OfficeNative.crdtNew(device) -        for (i in 0 until pre) reuse(current[i], desired[i])-        val midC = current.subList(pre, current.size - suf)-        val midD = desired.subList(pre, desired.size - suf)-        val pairs = lcs(midD.map { keyOfDesired(it) }, midC.map { keyOfNode(it) })-        val matchedC = HashSet<Int>()-        var pp = 0-        for (di in midD.indices) {-            if (pp < pairs.size && pairs[pp].first == di) {-                val ci = pairs[pp].second; pp++-                matchedC.add(ci)-                reuse(midC[ci], midD[di])-            } else insert(midD[di])-        }-        for (ci in midC.indices) if (ci !in matchedC && !midC[ci].deleted) { midC[ci].deleted = true; ops.add(midC[ci].copy(deleted = true)) }-        for (i in 0 until suf) reuse(current[current.size - suf + i], desired[desired.size - suf + i])-    }+    fun loadState(json: String) = OfficeNative.crdtLoadState(handle, json) -    private fun lcs(a: List<String>, b: List<String>): List<Pair<Int, Int>> {-        val n = a.size; val m = b.size-        if (n == 0 || m == 0) return emptyList()-        val dp = Array(n + 1) { IntArray(m + 1) }-        for (i in n - 1 downTo 0) for (j in m - 1 downTo 0)-            dp[i][j] = if (a[i] == b[j]) dp[i + 1][j + 1] + 1 else maxOf(dp[i + 1][j], dp[i][j + 1])-        val out = ArrayList<Pair<Int, Int>>()-        var i = 0; var j = 0-        while (i < n && j < m) {-            when {-                a[i] == b[j] -> { out.add(i to j); i++; j++ }-                dp[i + 1][j] >= dp[i][j + 1] -> i++-                else -> j++-            }-        }-        return out-    }+    fun serialize(): String = OfficeNative.crdtSerialize(handle) -    // --- Flat XML → desired tree ---+    /** Merge a batch of remote ops (a JSON array of Node). */+    fun applyJson(opsJson: String) = OfficeNative.crdtApply(handle, opsJson) -    private sealed class Desired {-        class El(val tag: String, val selfClosing: Boolean, val children: MutableList<Desired> = ArrayList()) : Desired()-        class Text(val text: String, val raw: Boolean) : Desired()-    }+    /** Reconcile toward [xml]; returns produced ops as a JSON array (or "[]"). */+    fun updateJson(xml: String): String = OfficeNative.crdtUpdate(handle, xml) -    private fun parse(xml: String): Desired.El {-        val root = Desired.El("", false)-        val stack = ArrayDeque<Desired.El>(); stack.addLast(root)-        val n = xml.length-        var i = 0-        var inBinary = false-        while (i < n) {-            if (xml[i] == '<') {-                var j = i + 1; var quote = '\u0000'-                while (j < n) {-                    val c = xml[j]-                    when {-                        quote != '\u0000' -> if (c == quote) quote = '\u0000'-                        c == '"' || c == '\'' -> quote = c-                        c == '>' -> break-                    }-                    j++-                }-                val tag = xml.substring(i, minOf(j + 1, n))-                when {-                    tag.startsWith("</") -> { if (stack.size > 1) stack.removeLast(); if (tag.startsWith("</office:binary-data")) inBinary = false }-                    tag.startsWith("<?") || tag.startsWith("<!") -> stack.last().children.add(Desired.El(tag, true))-                    tag.endsWith("/>") -> stack.last().children.add(Desired.El(tag, true))-                    else -> {-                        val el = Desired.El(tag, false); stack.last().children.add(el); stack.addLast(el)-                        if (tag.startsWith("<office:binary-data")) inBinary = true-                    }-                }-                i = j + 1-            } else {-                val end = xml.indexOf('<', i).let { if (it < 0) n else it }-                val text = xml.substring(i, end)-                if (inBinary) stack.last().children.add(Desired.Text(text, raw = true))-                else for (c in text) stack.last().children.add(Desired.Text(c.toString(), raw = false))-                i = end-            }-        }-        return root-    }+    fun render(): String = OfficeNative.crdtRender(handle) -    private fun nameOf(tag: String): String {-        var k = 1-        while (k < tag.length && tag[k] != ' ' && tag[k] != '>' && tag[k] != '/' && tag[k] != '\t' && tag[k] != '\n') k++-        return tag.substring(1, k)-    }+    /** JSON array of the current state's nodes (for re-baseline snapshots). */+    fun toStateNodesJson(): String = OfficeNative.crdtToStateNodesJson(handle) -    private fun closeTagOf(openTag: String): String = "</" + nameOf(openTag) + ">"+    fun close() = OfficeNative.crdtFree(handle) }
office/src/main/java/com/vayunmathur/office/util/OfficeNative.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/OfficeNative.kt b/office/src/main/java/com/vayunmathur/office/util/OfficeNative.ktnew file mode 100644index 0000000000..aa42292aad--- /dev/null+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeNative.kt@@ -0,0 +1,164 @@+package com.vayunmathur.office.util++import com.vayunmathur.library.ui.odf.OdfNumberFormat+import com.vayunmathur.library.ui.odf.OdfSheet+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * JNI bridge to the native `office_engine` Rust library: the ODF formula engine+ * and the document-tree CRDT, which now own these features outright (the former+ * Kotlin implementations have been deleted).+ *+ * ## CRDT wire format (SIGNED — do not change casually)+ * The Rust CRDT serializes Node/State byte-for-byte identically to the previous+ * Kotlin `kotlinx.serialization` output used on the collaboration wire+ * (`Json { ignoreUnknownKeys = true }`, i.e. `encodeDefaults = false` — default+ * fields `deleted`/`name`/`attrLamport`/`attrDev` are OMITTED). This was verified+ * with an exact-string round-trip test in the crate (`crdt::tests`). The+ * signed-collaboration path in [OfficeViewModel] signs the native engine's ops+ * JSON directly; [DocumentTreeCrdt] is a thin handle wrapper over these calls.+ *+ * ## Formula engine+ * Build a workbook handle once per sheet snapshot via [createWorkbook] (serialize+ * all sheets with [buildWorkbookJson]), then call [nativeDisplayValue]/+ * [nativeIsNumeric], and [nativeFree] when the snapshot changes. Non-deterministic+ * funcs (TODAY/NOW/RAND) read [nowMillis]. [nativeFormatValue] formats a lone+ * number with no workbook (XLSX cell display).+ */+object OfficeNative {+    init {+        System.loadLibrary("office_engine")+    }++    // ---- Document tree CRDT ----++    /** Creates a native CRDT for [device]; returns a handle (0 on failure). */+    external fun crdtNew(device: String): Long++    /** Replaces the CRDT state from a serialized [State] JSON (ignores parse errors). */+    external fun crdtLoadState(handle: Long, json: String)++    /** Serializes the full [State] (byte-identical to the Kotlin serializer). */+    external fun crdtSerialize(handle: Long): String++    /** Merges a batch of remote node ops (a JSON array of Node). Commutative + idempotent. */+    external fun crdtApply(handle: Long, opsJson: String)++    /** Reconciles toward [xml], returning the produced ops as a JSON array of Node. */+    external fun crdtUpdate(handle: Long, xml: String): String++    /** Renders the current tree back to flat XML. */+    external fun crdtRender(handle: Long): String++    /** Serializes just the current state's node array (JSON array of Node). */+    external fun crdtToStateNodesJson(handle: Long): String++    /** Releases the CRDT. */+    external fun crdtFree(handle: Long)++    // ---- ODF formula engine ----++    /**+     * Parses a compact workbook JSON (see [buildWorkbookJson]) into a native+     * workbook; returns a handle (0 on failure). [nowMillis] seeds TODAY/NOW/RAND.+     */+    external fun nativeCreateWorkbook(json: String, nowMillis: Long): Long++    /** Display string for a cell (empty string out of range). */+    external fun nativeDisplayValue(handle: Long, sheetIdx: Int, row: Int, col: Int): String?++    /** Whether the (evaluated) cell holds a numeric value. */+    external fun nativeIsNumeric(handle: Long, sheetIdx: Int, row: Int, col: Int): Boolean++    /** Releases a workbook. */+    external fun nativeFree(handle: Long)++    /**+     * Formats [value] using a serialized [OdfNumberFormat] ([numberFormatJson]);+     * `"null"` or empty means "no format" (plain number). Standalone number+     * formatter for callers with no workbook context.+     */+    external fun nativeFormatValue(value: Double, numberFormatJson: String): String++    /** Formats [value] with an optional [fmt], serializing it to the NfDto JSON the Rust engine parses. */+    fun formatValue(value: Double, fmt: OdfNumberFormat?): String =+        nativeFormatValue(value, fmt?.let { json.encodeToString(nfDtoOf(it)) } ?: "null")++    /**+     * Convenience: serialize [sheets] and create a native workbook handle, or+     * return 0 if the native lib is unavailable or creation fails.+     */+    fun createWorkbook(sheets: List<OdfSheet>, nowMillis: Long = System.currentTimeMillis()): Long =+        nativeCreateWorkbook(buildWorkbookJson(sheets), nowMillis)++    // ---- Workbook serialization (must agree with the serde schema in formula.rs) ----++    private val json = Json { encodeDefaults = true; explicitNulls = false }++    /** Serializes all [sheets] (name + 2D cell grid) to the compact JSON the Rust engine parses. */+    fun buildWorkbookJson(sheets: List<OdfSheet>): String {+        val dto = WbDto(sheets.map { s ->+            SheetDto(s.name, s.rows.map { r ->+                RowDto(r.cells.map { c ->+                    CellDto(+                        text = c.text,+                        formula = c.formula,+                        numberValue = c.numberValue,+                        valueType = c.valueType,+                        isCovered = c.isCovered,+                        numberFormat = c.numberFormat?.let { nfDtoOf(it) }+                    )+                })+            })+        })+        return json.encodeToString(dto)+    }++    /** Maps an [OdfNumberFormat] to the compact NfDto the Rust engine parses. */+    private fun nfDtoOf(nf: OdfNumberFormat): NfDto = NfDto(+        decimals = nf.decimals,+        percent = nf.percent,+        currencySymbol = nf.currencySymbol,+        grouping = nf.grouping,+        isDate = nf.isDate,+        isTime = nf.isTime,+        isScientific = nf.isScientific,+        isFraction = nf.isFraction,+        fractionDenominatorDigits = nf.fractionDenominatorDigits,+        dateTimeTokens = nf.dateTimeTokens.map { t -> TokDto(t.kind, t.style, t.text, t.textual) }+    )++    @Serializable private data class WbDto(val sheets: List<SheetDto>)+    @Serializable private data class SheetDto(val name: String, val rows: List<RowDto>)+    @Serializable private data class RowDto(val cells: List<CellDto>)++    @Serializable private data class CellDto(+        val text: String,+        val formula: String? = null,+        val numberValue: Double? = null,+        val valueType: String? = null,+        val isCovered: Boolean = false,+        val numberFormat: NfDto? = null,+    )++    @Serializable private data class NfDto(+        val decimals: Int? = null,+        val percent: Boolean = false,+        val currencySymbol: String? = null,+        val grouping: Boolean = false,+        val isDate: Boolean = false,+        val isTime: Boolean = false,+        val isScientific: Boolean = false,+        val isFraction: Boolean = false,+        val fractionDenominatorDigits: Int = 1,+        val dateTimeTokens: List<TokDto> = emptyList(),+    )++    @Serializable private data class TokDto(+        val kind: String,+        val style: String? = null,+        val text: String? = null,+        val textual: Boolean = false,+    )+}
office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.ktindex e17098150d..aa2cf38037 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt@@ -307,7 +307,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         // Track (or clear) the online identity of the document now open.         currentDocId = onlineDocId         currentDocKey = onlineDocKey-        currentTree = null+        currentTree?.close(); currentTree = null         currentCharKind = ""         _isOnline.value = onlineDocId != null         if (onlineDocId == null) {@@ -358,7 +358,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         documentUri = null         currentDocId = null         currentDocKey = null-        currentTree = null+        currentTree?.close(); currentTree = null         currentCharKind = ""         OfficeSync.stopLive()         livePollJob?.cancel()@@ -373,7 +373,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)     // --- Create new documents ---      fun createNewTextDocument() {-        currentDocId = null; currentDocKey = null; currentTree = null; currentCharKind = ""+        currentDocId = null; currentDocKey = null; currentTree?.close(); currentTree = null; currentCharKind = ""         currentRole = OfficeRoles.OWNER; currentOwnerKey = null; currentMembers.clear(); _isOnline.value = false         undoStack.clear(); redoStack.clear()         _canUndo.value = false; _canRedo.value = false@@ -388,7 +388,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)     }      fun createNewSpreadsheet() {-        currentDocId = null; currentDocKey = null; currentTree = null; currentCharKind = ""+        currentDocId = null; currentDocKey = null; currentTree?.close(); currentTree = null; currentCharKind = ""         currentRole = OfficeRoles.OWNER; currentOwnerKey = null; currentMembers.clear(); _isOnline.value = false         undoStack.clear(); redoStack.clear()         _canUndo.value = false; _canRedo.value = false@@ -404,7 +404,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)     }      fun createNewPresentation() {-        currentDocId = null; currentDocKey = null; currentTree = null; currentCharKind = ""+        currentDocId = null; currentDocKey = null; currentTree?.close(); currentTree = null; currentCharKind = ""         currentRole = OfficeRoles.OWNER; currentOwnerKey = null; currentMembers.clear(); _isOnline.value = false         undoStack.clear(); redoStack.clear()         _canUndo.value = false; _canRedo.value = false@@ -2167,8 +2167,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         if (!allowed) return false         val authorKey = memberKey(so.author) ?: return false         if (!OfficeSync.verify(authorKey, so.ops.encodeToByteArray(), Base64.decode(so.sig))) return false-        val ops = runCatching { syncJson.decodeFromString<List<DocumentTreeCrdt.Node>>(so.ops) }.getOrNull() ?: return false-        tree.apply(ops)+        tree.applyJson(so.ops)         return true     } @@ -2182,14 +2181,14 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)                     val localXml = exportFlat()                     // Fold pending local edits into the tree FIRST (and push them), so an incoming or                     // echoed op can't render a stale state and resurrect a char we just deleted.-                    val localOps = tree.update(localXml)-                    if (localOps.isNotEmpty() && OfficeRoles.canEdit(currentRole)) {-                        val opsJson = syncJson.encodeToString(localOps)+                    val opsJson = tree.updateJson(localXml)+                    val hasLocal = opsJson != "[]"+                    if (hasLocal && OfficeRoles.canEdit(currentRole)) {                         val sig = Base64.encode(OfficeSync.sign(opsJson.encodeToByteArray()))                         val signed = syncJson.encodeToString(SignedOp(OfficeSync.deviceId, sig, opsJson))                         if (!OfficeSync.liveAppend(docId, key, listOf(signed))) OfficeSync.appendDocActions(docId, key, listOf(signed))                     }-                    var changed = localOps.isNotEmpty()+                    var changed = hasLocal                     for (blob in msg.actions) {                         val plain = OfficeSync.decrypt(key, blob) ?: continue                         if (applySignedOp(tree, plain)) changed = true@@ -2320,10 +2319,9 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         val cursor = ds.getLong("crdtCursor:$docId")?.toInt() ?: 0         val localXml = exportFlat()         val startVersion = editVersion-        val localOps = tree.update(localXml)+        val opsJson = tree.updateJson(localXml)         // Only push signed ops if we're allowed to edit; viewers never push.-        if (localOps.isNotEmpty() && OfficeRoles.canEdit(currentRole)) {-            val opsJson = syncJson.encodeToString(localOps)+        if (opsJson != "[]" && OfficeRoles.canEdit(currentRole)) {             val sig = Base64.encode(OfficeSync.sign(opsJson.encodeToByteArray()))             val signed = syncJson.encodeToString(SignedOp(OfficeSync.deviceId, sig, opsJson))             // Prefer the live WebSocket (peers get it instantly, like presence); HTTP is the fallback.@@ -2463,6 +2461,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)                 val mergedXml = crdt.render()                 if (mergedXml.isBlank()) {                     // No accepted content — usually ops from an older version that no longer verify.+                    crdt.close() // never adopted as currentTree; free its native handle                     withContext(Dispatchers.Main) {                         _state.value = ViewState.Error("This shared document has no readable content. It was likely created with an older version — ask the owner to re-share a new copy.")                     }@@ -2476,6 +2475,8 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)                     loadDocument(Uri.fromFile(file), "$safeTitle.fodt", meta.docId, key)                     _isEditMode.value = OfficeRoles.canEdit(meta.role) // viewers are read-only                 }+                // loadDocument() above already closed+nulled any prior tree; guard defensively.+                if (currentTree !== crdt) currentTree?.close()                 currentTree = crdt                 currentCharKind = meta.charKind.ifEmpty { if (meta.charMode) "text" else "" }                 startLive(meta.docId, key)@@ -2619,8 +2620,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         currentDocKey = newKey         val crdt = currentTree         if (crdt != null) {-            val snapshot = crdt.toState().nodes-            val opsJson = syncJson.encodeToString(snapshot)+            val opsJson = crdt.toStateNodesJson()             val opSig = Base64.encode(OfficeSync.sign(opsJson.encodeToByteArray()))             OfficeSync.appendDocActions(docId, newKey, listOf(syncJson.encodeToString(SignedOp(OfficeSync.deviceId, opSig, opsJson))))         }
office/src/main/rust/.gitignore
diff --git a/office/src/main/rust/.gitignore b/office/src/main/rust/.gitignorenew file mode 100644index 0000000000..ea8c4bf7f3--- /dev/null+++ b/office/src/main/rust/.gitignore@@ -0,0 +1 @@+/target
office/src/main/rust/Cargo.lock
diff --git a/office/src/main/rust/Cargo.lock b/office/src/main/rust/Cargo.locknew file mode 100644index 0000000000..7f422da17a--- /dev/null+++ b/office/src/main/rust/Cargo.lock@@ -0,0 +1,326 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "cesu8"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "jni"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"+dependencies = [+ "cesu8",+ "cfg-if",+ "combine",+ "jni-sys 0.3.1",+ "log",+ "thiserror",+ "walkdir",+ "windows-sys 0.45.0",+]++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "log"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "office_engine"+version = "0.1.0"+dependencies = [+ "jni",+ "serde",+ "serde_json",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.3",+]++[[package]]+name = "serde_json"+version = "1.0.151"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"++[[package]]+name = "windows_aarch64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"++[[package]]+name = "windows_i686_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"++[[package]]+name = "windows_i686_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"++[[package]]+name = "windows_x86_64_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"++[[package]]+name = "windows_x86_64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
office/src/main/rust/Cargo.toml
diff --git a/office/src/main/rust/Cargo.toml b/office/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..c4e875243b--- /dev/null+++ b/office/src/main/rust/Cargo.toml@@ -0,0 +1,21 @@+[package]+name = "office_engine"+version = "0.1.0"+edition = "2021"+description = "Native ODF formula engine + document tree CRDT for the office app, via JNI"+license = "GPL-2.0-only"++[lib]+name = "office_engine"+crate-type = ["cdylib", "rlib"]++[dependencies]+jni = "0.21"+serde = { version = "1", features = ["derive"] }+serde_json = "1"++[profile.release]+opt-level = 3+lto = true+codegen-units = 1+strip = true
office/src/main/rust/rust-toolchain.toml
diff --git a/office/src/main/rust/rust-toolchain.toml b/office/src/main/rust/rust-toolchain.tomlnew file mode 100644index 0000000000..fa6ac3abd8--- /dev/null+++ b/office/src/main/rust/rust-toolchain.toml@@ -0,0 +1,3 @@+[toolchain]+channel = "1.97.0"+targets = ["aarch64-linux-android"]
office/src/main/rust/src/crdt.rs
diff --git a/office/src/main/rust/src/crdt.rs b/office/src/main/rust/src/crdt.rsnew file mode 100644index 0000000000..c423fea3e7--- /dev/null+++ b/office/src/main/rust/src/crdt.rs@@ -0,0 +1,765 @@+//! Hierarchical (tree) CRDT over a flat-ODF XML document. Faithful port of+//! `DocumentTreeCrdt.kt`. Node/State JSON is signed and exchanged across+//! devices, so serde output MUST be byte-for-byte identical to the Kotlin+//! kotlinx.serialization output (all fields, declaration order, compact).+//!+//! Node kinds: "e" element, "s" opaque leaf, "c" character, "r" raw run.++use serde::{Deserialize, Serialize};+use std::collections::HashMap;++/// A CRDT node. Field order MUST match the Kotlin `@Serializable data class Node`+/// declaration order exactly: id, parent, left, kind, payload, deleted, lamport,+/// dev, name, attrLamport, attrDev.+///+/// WIRE FORMAT: the ops/state JSON is signed and exchanged across devices, so+/// serde output must be byte-for-byte identical to kotlinx.serialization. The+/// Kotlin side serializes with `Json { ignoreUnknownKeys = true }`, whose+/// `encodeDefaults` defaults to FALSE — so fields that hold their Kotlin default+/// (`deleted=false`, `name=""`, `attrLamport=0`, `attrDev=""`) are OMITTED.+/// Fields without a Kotlin default (`parent`, `left`, ...) are always emitted,+/// even when empty. `skip_serializing_if` below mirrors that exactly.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Node {+    pub id: String,+    pub parent: String,+    pub left: String,+    pub kind: String,+    pub payload: String,+    #[serde(default, skip_serializing_if = "is_false")]+    pub deleted: bool,+    pub lamport: i64,+    pub dev: String,+    #[serde(default, skip_serializing_if = "String::is_empty")]+    pub name: String,+    #[serde(default, rename = "attrLamport", skip_serializing_if = "is_zero_i64")]+    pub attr_lamport: i64,+    #[serde(default, rename = "attrDev", skip_serializing_if = "String::is_empty")]+    pub attr_dev: String,+}++fn is_false(b: &bool) -> bool {+    !*b+}++fn is_zero_i64(v: &i64) -> bool {+    *v == 0+}++/// Serialized document state. Field order: device, clock, nodes.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct State {+    pub device: String,+    pub clock: i64,+    pub nodes: Vec<Node>,+}++/// A desired child produced by parsing flat XML.+enum Desired {+    /// tag, self_closing, children+    El(String, bool, Vec<Desired>),+    /// text, raw+    Text(String, bool),+}++pub struct DocumentTreeCrdt {+    device: String,+    /// insertion-ordered ids (mirrors Kotlin LinkedHashMap iteration order)+    order: Vec<String>,+    nodes: HashMap<String, Node>,+    /// parent id -> child ids in insertion order (incl. tombstones)+    children_by_parent: HashMap<String, Vec<String>>,+    clock: i64,+}++impl DocumentTreeCrdt {+    pub fn new(device: String) -> Self {+        DocumentTreeCrdt {+            device,+            order: Vec::new(),+            nodes: HashMap::new(),+            children_by_parent: HashMap::new(),+            clock: 0,+        }+    }++    /// Snapshot of the current state (nodes in insertion order).+    pub fn to_state(&self) -> State {+        State {+            device: self.device.clone(),+            clock: self.clock,+            nodes: self.order.iter().map(|id| self.nodes[id].clone()).collect(),+        }+    }++    pub fn load_state(&mut self, json_str: &str) {+        let s: State = match serde_json::from_str(json_str) {+            Ok(v) => v,+            Err(_) => return,+        };+        self.order.clear();+        self.nodes.clear();+        self.children_by_parent.clear();+        for n in s.nodes {+            let c = n.clone();+            self.order.push(c.id.clone());+            self.children_by_parent+                .entry(c.parent.clone())+                .or_default()+                .push(c.id.clone());+            self.nodes.insert(c.id.clone(), c);+        }+        self.clock = s.clock;+    }++    pub fn serialize(&self) -> String {+        serde_json::to_string(&self.to_state()).unwrap_or_default()+    }++    /// Serializes just the node array of the current state (JSON array).+    pub fn to_state_nodes_json(&self) -> String {+        let nodes: Vec<Node> = self.order.iter().map(|id| self.nodes[id].clone()).collect();+        serde_json::to_string(&nodes).unwrap_or_default()+    }++    fn insert_node(&mut self, node: Node) {+        let id = node.id.clone();+        let parent = node.parent.clone();+        if !self.nodes.contains_key(&id) {+            self.order.push(id.clone());+        }+        self.children_by_parent+            .entry(parent)+            .or_default()+            .push(id.clone());+        self.nodes.insert(id, node);+    }++    /// Merges a batch of remote node ops. Commutative + idempotent.+    pub fn apply(&mut self, ops: &[Node]) {+        for op in ops {+            self.clock = self.clock.max(op.lamport.max(op.attr_lamport));+            if !self.nodes.contains_key(&op.id) {+                self.insert_node(op.clone());+            } else {+                let cur = self.nodes.get_mut(&op.id).unwrap();+                if op.deleted {+                    cur.deleted = true;+                }+                if op.kind == "e"+                    && (op.attr_lamport > cur.attr_lamport+                        || (op.attr_lamport == cur.attr_lamport && op.attr_dev > cur.attr_dev))+                {+                    cur.payload = op.payload.clone();+                    cur.attr_lamport = op.attr_lamport;+                    cur.attr_dev = op.attr_dev.clone();+                }+            }+        }+    }++    pub fn render(&self) -> String {+        let mut sb = String::new();+        self.render_children("", &mut sb);+        sb+    }++    fn render_children(&self, parent: &str, sb: &mut String) {+        for id in self.ordered_children(parent) {+            let node = &self.nodes[&id];+            if node.deleted {+                continue;+            }+            if node.kind == "e" {+                sb.push_str(&node.payload);+                self.render_children(&node.id, sb);+                sb.push_str(&close_tag_of(&node.payload));+            } else {+                sb.push_str(&node.payload);+            }+        }+    }++    /// RGA order of a parent's children (incl. tombstones). Returns node ids.+    fn ordered_children(&self, parent: &str) -> Vec<String> {+        let kids = match self.children_by_parent.get(parent) {+            Some(k) => k,+            None => return Vec::new(),+        };+        // group by `left`+        let mut by_left: HashMap<String, Vec<String>> = HashMap::new();+        for id in kids {+            let n = &self.nodes[id];+            by_left.entry(n.left.clone()).or_default().push(id.clone());+        }+        // sort each group: descending lamport, then descending dev+        for group in by_left.values_mut() {+            group.sort_by(|a, b| {+                let na = &self.nodes[a];+                let nb = &self.nodes[b];+                nb.lamport+                    .cmp(&na.lamport)+                    .then_with(|| nb.dev.cmp(&na.dev))+            });+        }+        let mut result: Vec<String> = Vec::with_capacity(kids.len());+        let mut stack: Vec<String> = Vec::new();+        if let Some(roots) = by_left.get("") {+            for id in roots.iter().rev() {+                stack.push(id.clone());+            }+        }+        while let Some(e) = stack.pop() {+            resu

Diff truncated.