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

419 lines
9.9 KiB
Lua

-- The sheet engine: cells, lazy evaluation, ranges and error values.
--
-- A cell holds either a literal (number, boolean, text) or a formula. Formula
-- values are computed on demand, memoised, and cycles are detected with a
-- "visiting" set, so A1 = B1, B1 = A1 yields #CYCLE! instead of hanging.
local parser = require("sheet.parser")
local builtins = require("sheet.builtins")
local format = require("sheet.format")
local M = {}
local Sheet = {}
Sheet.__index = Sheet
local function trim(text)
return string.match(text, "^%s*(.-)%s*$")
end
function M.new(name)
return setmetatable({
name = name or "Sheet1",
cells = {},
values = {},
visiting = {},
stats = { eval = 0, errors = 0, cycles = 0 },
}, Sheet)
end
function Sheet:invalidate()
self.values = {}
self.visiting = {}
self.stats = { eval = 0, errors = 0, cycles = 0 }
end
function Sheet:normalize(address)
local letters, digits = string.match(address, "^%s*%$?([A-Za-z]+)%$?(%d+)%s*$")
if letters == nil then
error("bad cell address: " .. tostring(address), 0)
end
local column = format.column_index(letters)
local row = tonumber(digits)
if row == nil or row < 1 then
error("bad cell address: " .. tostring(address), 0)
end
return format.column_label(column) .. row, column, row
end
function Sheet:set(address, text, number_format)
local key, column, row = self:normalize(address)
local body = trim(tostring(text or ""))
self:invalidate()
if body == "" then
self.cells[key] = nil
return key
end
local cell = { text = body, col = column, row = row, format = number_format }
if string.sub(body, 1, 1) == "=" then
cell.kind = "formula"
local ok, ast = pcall(parser.parse, string.sub(body, 2))
if ok then
cell.ast = ast
else
cell.parse_error = tostring(ast)
end
else
cell.kind = "literal"
local number = tonumber(body)
local upper = string.upper(body)
if number ~= nil then
cell.value = number
elseif upper == "TRUE" then
cell.value = true
elseif upper == "FALSE" then
cell.value = false
else
cell.value = body
end
end
self.cells[key] = cell
return key
end
function Sheet:raw(address)
local key = self:normalize(address)
local cell = self.cells[key]
if cell == nil then
return nil
end
return cell.text
end
-- Internal: evaluates a cell key, raising "#CODE" on failure.
function Sheet:evaluate(key)
local cached = self.values[key]
if cached ~= nil then
if cached.ok then
return cached.value
end
error(cached.err, 0)
end
local cell = self.cells[key]
if cell == nil then
return nil
end
if cell.kind == "literal" then
self.values[key] = { ok = true, value = cell.value }
return cell.value
end
if cell.parse_error ~= nil then
self.stats.errors = self.stats.errors + 1
self.values[key] = { ok = false, err = "#PARSE!", detail = cell.parse_error }
error("#PARSE!", 0)
end
if self.visiting[key] then
self.stats.cycles = self.stats.cycles + 1
error("#CYCLE!", 0)
end
self.visiting[key] = true
self.stats.eval = self.stats.eval + 1
local ok, result = pcall(function()
return self:run(cell.ast)
end)
self.visiting[key] = nil
if ok then
self.values[key] = { ok = true, value = result }
return result
end
local message = tostring(result)
local code = "#VALUE!"
if string.sub(message, 1, 1) == "#" then
code = message
end
self.stats.errors = self.stats.errors + 1
self.values[key] = { ok = false, err = code, detail = message }
error(code, 0)
end
function Sheet:to_number(value)
local kind = type(value)
if kind == "number" then
return value
end
if kind == "string" then
local number = tonumber(value)
if number ~= nil then
return number
end
end
if kind == "boolean" then
if value then
return 1
end
return 0
end
error("#VALUE!", 0)
end
function Sheet:compare(operator, left, right)
if type(left) == "table" or type(right) == "table" then
error("#VALUE!", 0)
end
local a = left
local b = right
local both_numbers = type(a) == "number" and type(b) == "number"
local both_booleans = type(a) == "boolean" and type(b) == "boolean"
if not both_numbers and not both_booleans then
a = format.value(a)
b = format.value(b)
end
if operator == "=" then
return a == b
elseif operator == "<>" then
return a ~= b
elseif operator == "<" then
return a < b
elseif operator == ">" then
return a > b
elseif operator == "<=" then
return a <= b
end
return a >= b
end
function Sheet:binary(operator, left_node, right_node)
if operator == "&" then
local left = format.value(self:run(left_node))
local right = format.value(self:run(right_node))
return left .. right
end
if operator == "=" or operator == "<>" or operator == "<" or operator == ">"
or operator == "<=" or operator == ">=" then
return self:compare(operator, self:run(left_node), self:run(right_node))
end
local a = self:to_number(self:run(left_node))
local b = self:to_number(self:run(right_node))
if operator == "+" then
return a + b
elseif operator == "-" then
return a - b
elseif operator == "*" then
return a * b
elseif operator == "/" then
if b == 0 then
error("#DIV/0!", 0)
end
return a / b
elseif operator == "%" then
if b == 0 then
error("#DIV/0!", 0)
end
return a % b
elseif operator == "^" then
return a ^ b
end
error("#PARSE!", 0)
end
function Sheet:run(node)
local kind = node.k
if kind == "num" or kind == "str" or kind == "bool" then
return node.v
end
if kind == "ref" then
local value = self:evaluate(node.key)
if value == nil then
return 0
end
return value
end
if kind == "range" then
local values = {}
for row = node.r1, node.r2 do
for column = node.c1, node.c2 do
local value = self:evaluate(format.column_label(column) .. row)
if value ~= nil then
values[#values + 1] = value
end
end
end
return {
__range = true,
values = values,
c1 = node.c1, c2 = node.c2, r1 = node.r1, r2 = node.r2,
}
end
if kind == "call" then
local args = {}
for i = 1, #node.args do
args[i] = self:run(node.args[i])
end
return builtins.call(node.name, args)
end
if kind == "un" then
local value = self:to_number(self:run(node.a))
if node.op == "-" then
return -value
end
return value
end
if kind == "bin" then
return self:binary(node.op, node.a, node.b)
end
error("#PARSE!", 0)
end
-- Public accessor: returns value, error_code (nil when the cell is fine).
function Sheet:value(address)
local ok, key = pcall(function()
return self:normalize(address)
end)
if not ok then
return nil, "#REF!"
end
local evaluated, result = pcall(function()
return self:evaluate(key)
end)
if evaluated then
return result, nil
end
return nil, tostring(result)
end
-- What a cell shows: formatted value, or its error code, or "" when blank.
-- A cell declared with the '%' format renders its ratio as a percentage.
function Sheet:display(address)
local value, err = self:value(address)
if err ~= nil then
return err
end
if value == nil then
return ""
end
local ok, key = pcall(function()
return self:normalize(address)
end)
local cell = nil
if ok then
cell = self.cells[key]
end
if cell ~= nil and cell.format == "percent" and type(value) == "number" then
return string.format("%.1f%%", value * 100)
end
return format.value(value)
end
function Sheet:dimensions()
local max_row = 0
local max_col = 0
for _, cell in pairs(self.cells) do
if cell.row > max_row then
max_row = cell.row
end
if cell.col > max_col then
max_col = cell.col
end
end
return max_row, max_col
end
function Sheet:count()
local total = 0
for _ in pairs(self.cells) do
total = total + 1
end
return total
end
-- Named helper (no closure): the generated C++ of a closure capturing a
-- mutated local and a generic for loop is fragile, so pcall gets plain args.
local function evaluate_entry(sheet, key)
return sheet:evaluate(key)
end
function Sheet:evaluate_all()
local keys = {}
for key in pairs(self.cells) do
table.insert(keys, key)
end
table.sort(keys)
for i = 1, #keys do
local key = keys[i]
local ok = pcall(evaluate_entry, self, key)
if not ok then
-- errors are recorded in self.values; keep walking the sheet
local recorded = self.values[key]
if recorded == nil then
self.values[key] = { ok = false, err = "#VALUE!" }
end
end
end
end
function Sheet:errors()
self:evaluate_all()
local found = {}
for key, cached in pairs(self.values) do
if not cached.ok then
local cell = self.cells[key]
found[#found + 1] = {
key = key,
err = cached.err,
detail = cached.detail,
text = cell and cell.text or "",
row = cell and cell.row or 0,
col = cell and cell.col or 0,
}
end
end
table.sort(found, function(a, b)
if a.row ~= b.row then
return a.row < b.row
end
return a.col < b.col
end)
return found
end
-- Reads a tiny worksheet format: one "A1: value" or "B4: =B3*12" per line,
-- '#' comments, blank lines ignored.
function M.from_text(text, name)
local sheet = M.new(name)
local line_number = 0
for line in string.gmatch(text .. "\n", "([^\n]*)\n") do
line_number = line_number + 1
local body = trim(line)
if body ~= "" and string.sub(body, 1, 1) ~= "#" then
local address, marker, content = string.match(body, "^([%$%a%d]+)%s*(%%?)%s*:%s*(.*)$")
if address == nil then
error(string.format("%s line %d: expected 'A1: value'", name or "sheet", line_number), 0)
end
local number_format = nil
if marker == "%" then
number_format = "percent"
end
sheet:set(address, content, number_format)
end
end
return sheet
end
return M