Files
BlackAngelTV e71907ea86 feat(demo): add a spreadsheet engine written in Lua
The demo folder only had a toy todo list, which did not show that a
non-trivial application can be written in Lua and shipped as a single
compiled binary. This adds LuaSheet: a tokenizer, a formula parser, a
lazy evaluator with cycle detection, range-aware builtin functions,
ASCII/CSV rendering and a benchmark, all driven by a CLI entry point.

Everything stays plain Lua under Demo/: no C++ change is needed to
build or run it.
2026-11-18 09:19:32 +01:00

215 lines
9.5 KiB
Lua

-- Self tests for the spreadsheet engine. Returns a summary table:
-- { passed = n, failed = n, failures = { "message", ... } }
local lexer = require("sheet.lexer")
local parser = require("sheet.parser")
local builtins = require("sheet.builtins")
local sheet_module = require("sheet.sheet")
local render = require("sheet.render")
local format = require("sheet.format")
local workbooks = require("sheet.workbooks")
local M = {}
-- Evaluates a single formula on a throw-away sheet and returns what the cell
-- displays (so numbers, booleans and error codes compare as strings).
local function compute(text)
local sheet = sheet_module.new("ad-hoc")
sheet:set("A1", text)
return sheet:display("A1")
end
local function sample(rows)
local sheet = sheet_module.new("case")
for i = 1, #rows do
sheet:set(rows[i][1], rows[i][2])
end
return sheet
end
function M.run()
local passed = 0
local failures = {}
local function check(name, actual, expected)
if actual == expected then
passed = passed + 1
else
failures[#failures + 1] = string.format(
"%s : attendu %s, obtenu %s",
name, tostring(expected), tostring(actual)
)
end
end
local function check_true(name, condition, detail)
if condition then
passed = passed + 1
else
failures[#failures + 1] = name .. " : " .. tostring(detail or "condition fausse")
end
end
-- addresses -----------------------------------------------------------
check("column_label(1)", format.column_label(1), "A")
check("column_label(26)", format.column_label(26), "Z")
check("column_label(27)", format.column_label(27), "AA")
check("column_label(28)", format.column_label(28), "AB")
check("column_label(702)", format.column_label(702), "ZZ")
check("column_label(703)", format.column_label(703), "AAA")
check("column_index(AA)", format.column_index("AA"), 27)
check("column_index(zz)", format.column_index("zz"), 702)
-- lexer ---------------------------------------------------------------
local tokens = lexer.tokenize("A1+2.5*$B$3")
check("lexer token count", #tokens, 6)
check("lexer first kind", tokens[1].kind, "ref")
check("lexer first text", tokens[1].value.text, "A1")
check("lexer number", tokens[3].value, 2.5)
check("lexer absolute ref", tokens[5].value.letters, "B")
local lex_ok, lex_err = pcall(lexer.tokenize, "1 @ 2")
check("lexer rejects @", lex_ok, false)
check_true("lexer error is explicit", string.find(tostring(lex_err), "unexpected") ~= nil, lex_err)
-- parser --------------------------------------------------------------
local parse_ok = pcall(parser.parse, "SUM(")
check("parser rejects unclosed call", parse_ok, false)
check("precedence add/mul", compute("=1+2*3"), "7")
check("precedence parentheses", compute("=(1+2)*3"), "9")
check("power is right assoc", compute("=2^3^2"), "512")
check("unary minus binds tight", compute("=-2^2"), "4")
check("division is float", compute("=10/4"), "2.5")
check("modulo", compute("=7%3"), "1")
check("concat operator", compute("=1&2"), "12")
check("comparison lower", compute("=2<3"), "TRUE")
check("comparison not equal", compute("=3<>3"), "FALSE")
check("string equality", compute('="a"="a"'), "TRUE")
check("string concat", compute('="a"&"b"'), "ab")
check("! = alias", compute("=1!=2"), "TRUE")
-- references and ranges ----------------------------------------------
local sheet = sample({
{ "A1", "1" }, { "A2", "2" }, { "A3", "3" }, { "A4", "texte" },
})
sheet:set("B1", "=SUM(A1:A3)")
sheet:set("B2", "=AVG(A1:A3)")
sheet:set("B3", "=COUNT(A1:A4)")
sheet:set("B4", "=MAX(A1:A4)")
sheet:set("B5", "=MIN(A1:A3)")
sheet:set("B6", "=SUM(A1:A3,B1)")
sheet:set("C1", "=$A$1*10")
sheet:set("C2", "=Z9+1")
sheet:set("C3", "=SUM(A1:A3)")
check("SUM range", sheet:display("B1"), "6")
check("AVG range", sheet:display("B2"), "2")
check("COUNT ignores text", sheet:display("B3"), "3")
check("MAX ignores text", sheet:display("B4"), "3")
check("MIN range", sheet:display("B5"), "1")
check("SUM with scalar cell", sheet:display("B6"), "12")
check("absolute reference", sheet:display("C1"), "10")
check("blank reference is zero", sheet:display("C2"), "1")
check("range order preserved", sheet:display("C3"), "6")
-- functions -----------------------------------------------------------
check("IF true", compute('=IF(1<2,"oui","non")'), "oui")
check("IF false", compute('=IF(1>2,"oui","non")'), "non")
check("ROUND digits", compute("=ROUND(3.14159,2)"), "3.14")
check("ROUND half up", compute("=ROUND(2.5,0)"), "3")
check("ROUND negative half", compute("=ROUND(-2.5,0)"), "-3")
check("ABS", compute("=ABS(-7)"), "7")
check("SQRT", compute("=SQRT(2)*SQRT(2)"), "2")
check("INT", compute("=INT(-2.5)"), "-3")
check("MOD", compute("=MOD(7,3)"), "1")
check("POWER", compute("=POWER(2,10)"), "1024")
check("MEDIAN even", compute("=MEDIAN(4,1,3,2)"), "2.5")
check("CONCAT mixed", compute('=CONCAT("a",1,TRUE)'), "a1TRUE")
check("LEN", compute('=LEN("abc")'), "3")
check("UPPER", compute('=UPPER("lua")'), "LUA")
check("LOWER", compute('=LOWER("LUA")'), "lua")
check("LEFT", compute('=LEFT("abcdef",3)'), "abc")
check("RIGHT", compute('=RIGHT("abcdef",3)'), "def")
check("TRIM", compute('=TRIM(" x ")'), "x")
check("nested calls", compute("=SUM(1,2,MAX(3,4))"), "7")
check_true("builtin registry", builtins.exists("sum") and builtins.exists("Median"), "registry incomplete")
check_true("builtin names sorted", builtins.names()[1], "ABS")
-- errors --------------------------------------------------------------
check("divide by zero", compute("=1/0"), "#DIV/0!")
check("unknown function", compute("=NOPE(1)"), "#NAME?")
check("text in arithmetic", compute('=1+"abc"'), "#VALUE!")
check("syntax error", compute("=SUM("), "#PARSE!")
check("bad operator use", compute("=1+"), "#PARSE!")
local cyclic = sample({ { "A1", "=B1" }, { "B1", "=A1" }, { "C1", "=A1" } })
check("cycle detected", cyclic:display("A1"), "#CYCLE!")
check("cycle back edge", cyclic:display("B1"), "#CYCLE!")
check("cycle propagates", cyclic:display("C1"), "#CYCLE!")
local broken = sample({ { "A1", "=1/0" }, { "B1", "=A1+1" } })
check("error propagates", broken:display("B1"), "#DIV/0!")
-- chains and caching --------------------------------------------------
local chain = sample({
{ "A1", "1" }, { "A2", "=A1+1" }, { "A3", "=A2+1" }, { "A4", "=A3+1" },
})
check("dependency chain", chain:display("A4"), "4")
check_true("evaluation counted", chain.stats.eval >= 3, "stats.eval")
chain:set("A1", "10")
check("recalc after edit", chain:display("A4"), "13")
-- rendering -----------------------------------------------------------
check("fit keeps short text", format.fit("abc", 10), "abc")
check("fit truncates", format.fit("abcdef", 4), "abc~")
check("bar full", render.bar(10, 10, 5), "#####")
check("bar half", render.bar(5, 10, 10), "#####.....")
check("bar minimum", render.bar(1, 1000, 10), "#.........")
local viewed = render.render(sheet)
check_true("render has header", string.find(viewed, "| A") ~= nil, viewed)
check_true("render has separator", string.find(viewed, "%+%-+") ~= nil, viewed)
-- csv -----------------------------------------------------------------
local csv_sheet = sample({ { "A1", "texte, avec virgule" }, { "B1", 'un "guillemet"' } })
local csv = render.csv(csv_sheet)
check_true("csv quotes comma", string.find(csv, '"texte, avec virgule"', 1, true) ~= nil, csv)
check_true("csv doubles quotes", string.find(csv, '""guillemet""', 1, true) ~= nil, csv)
-- worksheet format ----------------------------------------------------
local parsed = sheet_module.from_text("A1: 5\nB1: =A1*2\n# commentaire\n\nA2: =IF(B1>5,\"grand\",\"petit\")\n", "mini")
check("from_text literal", parsed:display("A1"), "5")
check("from_text formula", parsed:display("B1"), "10")
check("from_text if", parsed:display("A2"), "grand")
check("from_text cell count", parsed:count(), 3)
-- workbooks -----------------------------------------------------------
local budget = sheet_module.from_text(workbooks.budget, "Budget")
check("budget charges", budget:display("B11"), "1923")
check("budget annuel", budget:display("C11"), "23076")
check("budget reste", budget:display("B13"), "677")
check("budget objectif", budget:display("C16"), "atteint")
check("budget moyenne", budget:display("B18"), "320.5")
check("budget max", budget:display("B19"), "820")
check("budget count", budget:display("B20"), "6")
check("percent cell", budget:display("D4"), "42.6%")
check("percent total", budget:display("D11"), "100.0%")
check("percent savings", budget:display("B21"), "11.5%")
local ventes = sheet_module.from_text(workbooks.ventes, "Ventes")
check("ventes total", ventes:display("B9"), "44000")
check("ventes statut", ventes:display("E4"), "ok")
check("ventes etiquette", ventes:display("E9"), "total 44000 / 43000")
check("ventes best", ventes:display("B11"), "14300")
local errors_sheet = sheet_module.from_text(workbooks.errors, "Erreurs")
check("errors cycle", errors_sheet:display("A1"), "#CYCLE!")
check("errors div", errors_sheet:display("B1"), "#DIV/0!")
check("errors name", errors_sheet:display("C1"), "#NAME?")
check("errors value", errors_sheet:display("D1"), "#VALUE!")
check("errors parse", errors_sheet:display("E1"), "#PARSE!")
check("errors propagation", errors_sheet:display("F1"), "#CYCLE!")
check("errors blank ref", errors_sheet:display("G1"), "1")
check_true("errors listing", #errors_sheet:errors() >= 6, #errors_sheet:errors())
return { passed = passed, failed = #failures, failures = failures }
end
return M