1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
mod input_formula;
pub(crate) use input_formula::get_all_vertices_from_ast;
use std::collections::HashSet;
pub use input_formula::{
add_ast_node, convert_cells_to_block, input_block_cell_shadow_template,
input_block_cell_template, input_block_formula, input_ephemeral_formula, input_formula,
rebuild_range_deps, remove_ephemeral_formula, remove_formula,
};
use logisheets_base::{
BlockId, BlockRange, CellId, CubeId, Range, RangeId, SheetId, errors::BasicError,
};
use crate::block_manager::schema_manager::schema::BlockCellRole;
use crate::{Error, edit_action::EditPayload};
use super::{FormulaManager, Vertex, ctx::FormulaExecCtx};
pub struct FormulaExecutor {
pub manager: FormulaManager,
pub dirty_vertices: HashSet<Vertex>,
pub dirty_ranges: HashSet<(SheetId, RangeId)>,
/// Blocks whose structure changed (bind/rebind, row or field added/removed).
/// These translate into `Vertex::BlockAll(sheet, block)` dirty entries.
pub dirty_blocks: HashSet<(SheetId, BlockId)>,
pub dirty_cubes: HashSet<CubeId>,
pub trigger: Option<(SheetId, RangeId)>,
/// Ephemeral (shadow) cells whose formula was just removed — e.g. a
/// per-field validation/editability rule cleared to `None`. Removing the
/// formula only detaches it from the dep graph; the shadow's last computed
/// value lingers in the container (the calc engine never revisits a
/// formula-less cell). Readers that key off shadow-id existence would keep
/// surfacing that stale warning / lock, so the controller purges these from
/// the container after formula execution.
pub ephemeral_shadows_cleared: HashSet<(SheetId, CellId)>,
}
/// True when the cell at `(row, col)` is a block cell whose field carries a
/// value-formula template. The template owns that cell, so user-facing write
/// payloads have to leave it alone.
fn is_templated_at<C: FormulaExecCtx>(
ctx: &mut C,
sheet_idx: usize,
row: usize,
col: usize,
) -> Result<bool, Error> {
let sheet = ctx
.fetch_sheet_id_by_index(sheet_idx)
.map_err(|l| BasicError::SheetIdxExceed(l))?;
match ctx.fetch_cell_id(&sheet, row, col) {
Ok(CellId::BlockCell(bcid)) => Ok(ctx.is_block_cell_templated(sheet, &bcid)),
_ => Ok(false),
}
}
impl FormulaExecutor {
pub fn execute<C: FormulaExecCtx>(
self,
payload: EditPayload,
ctx: &mut C,
) -> Result<Self, Error> {
let executor = match payload {
EditPayload::CellInput(mut cell_input) => {
// A cell in a field with a value-formula template is
// engine-owned. `CellInput` is the grid's write path, so
// this is where a person typing lands: refuse both a plain
// value (which would be overwritten on the next recalc
// anyway) and a literal `=formula` (which would silently
// replace the field's template for this one row). Crafts
// that genuinely want the per-row escape hatch still have
// it through `BlockInput`.
if is_templated_at(ctx, cell_input.sheet_idx, cell_input.row, cell_input.col)? {
return Ok(self);
}
if cell_input.content.starts_with("=") {
let formula = cell_input.content.split_off(1);
input_formula(
self,
cell_input.sheet_idx,
cell_input.row,
cell_input.col,
formula,
ctx,
)
} else {
// Plain value overwriting whatever was here. If the
// cell previously held a formula, drop it — otherwise
// the next recalc re-evaluates the stale formula and
// overwrites the value the user just typed, making
// numeric/text input over a formula cell appear to
// silently do nothing.
let sheet = ctx
.fetch_sheet_id_by_index(cell_input.sheet_idx)
.map_err(|l| BasicError::SheetIdxExceed(l))?;
match ctx.fetch_cell_id(&sheet, cell_input.row, cell_input.col) {
Ok(cell_id) if self.manager.formulas.contains_key(&(sheet, cell_id)) => {
remove_formula(
self,
cell_input.sheet_idx,
cell_input.row,
cell_input.col,
ctx,
)
}
_ => Ok(self),
}
}
}
EditPayload::EphemeralCellInput(mut ephemeral_cell_input) => {
let formula = ephemeral_cell_input.content.split_off(1);
input_ephemeral_formula(
self,
ephemeral_cell_input.sheet_idx,
ephemeral_cell_input.id,
formula,
ctx,
)
}
EditPayload::EphemeralCellRemove(p) => {
remove_ephemeral_formula(self, p.sheet_idx, p.id, ctx)
}
EditPayload::BlockInput(p) => {
// If the player wrote a literal formula (`=…`) into this
// block cell, register it directly. This is the
// per-cell escape hatch from field-level value-formula
// templates: when only a few rows of a column need a
// formula and the rest are plain values, you don't have
// to fold every row's logic into a single templated
// expression — just blockInput `=…` on the cells that
// need it.
//
// Otherwise (no `=` prefix), fall through to the
// templated-field path: if the cell sits in a field
// with a schema-level valueFormula, that template is
// materialized; non-templated cells are a no-op here
// (the container path handles them).
if let Some(formula) = p.input.strip_prefix('=') {
input_block_formula(
self,
p.sheet_idx,
p.block_id,
p.row,
p.col,
formula.to_string(),
ctx,
)
} else {
input_block_cell_template(self, p.sheet_idx, p.block_id, p.row, p.col, ctx)
}
}
EditPayload::InsertRowsInBlock(p) => {
// Newly inserted rows start blank. For each (new row × field)
// we materialize three engine-managed templates:
// 1. value_formula → written as the cell's main
// formula
// 2. validation_formula → installed on the cell's
// ShadowKind::Validation shadow
// (drives the red-marker UX)
// 3. editability_formula → installed on the cell's
// ShadowKind::UserEditable
// shadow (drives the host
// permission gate)
//
// Free-form cells (no template) are no-ops inside each
// helper so the loop stays simple. Block size at this
// point reflects the post-insert state — navigator runs
// before formula_manager.
let sheet_id = ctx
.fetch_sheet_id_by_index(p.sheet_idx)
.map_err(|l| BasicError::SheetIdxExceed(l))?;
let (_, col_cnt) = ctx
.get_block_size(sheet_id, p.block_id)
.map_err(|e: BasicError| -> Error { e.into() })?;
let mut exec = self;
for r in p.start..(p.start + p.cnt as usize) {
for c in 0..col_cnt {
exec = input_block_cell_template(exec, p.sheet_idx, p.block_id, r, c, ctx)?;
exec = input_block_cell_shadow_template(
exec,
p.sheet_idx,
p.block_id,
r,
c,
crate::sid_assigner::ShadowKind::Validation,
ctx,
)?;
exec = input_block_cell_shadow_template(
exec,
p.sheet_idx,
p.block_id,
r,
c,
crate::sid_assigner::ShadowKind::UserEditable,
ctx,
)?;
}
}
Ok(exec)
}
EditPayload::UpsertFieldFormulas(p) => {
// The schema_manager executor has already swapped in the
// new per-field rules. Re-walk every (row × col) and
// re-materialize all three template kinds — that way a
// template change (or clear) propagates uniformly to
// every existing row. Free-form / template-absent paths
// no-op inside the helpers.
let sheet_id = ctx
.fetch_sheet_id_by_index(p.sheet_idx)
.map_err(|l| BasicError::SheetIdxExceed(l))?;
let (row_cnt, col_cnt) = ctx
.get_block_size(sheet_id, p.block_id)
.map_err(|e: BasicError| -> Error { e.into() })?;
let mut exec = self;
for r in 0..row_cnt {
for c in 0..col_cnt {
exec = input_block_cell_template(exec, p.sheet_idx, p.block_id, r, c, ctx)?;
exec = input_block_cell_shadow_template(
exec,
p.sheet_idx,
p.block_id,
r,
c,
crate::sid_assigner::ShadowKind::Validation,
ctx,
)?;
exec = input_block_cell_shadow_template(
exec,
p.sheet_idx,
p.block_id,
r,
c,
crate::sid_assigner::ShadowKind::UserEditable,
ctx,
)?;
}
}
Ok(exec)
}
EditPayload::BindFormSchema(p) => {
// The bind itself happens in the schema_manager
// executor (earlier in the pass order). By the time we
// land here the schema is in place AND the block's rows
// already exist (from a prior CreateBlock). For each
// (row × col) install value / validation / editability
// templates declared on the schema; absent templates
// no-op.
let sheet_id = ctx
.fetch_sheet_id_by_index(p.sheet_idx)
.map_err(|l| BasicError::SheetIdxExceed(l))?;
let (row_cnt, col_cnt) = ctx
.get_block_size(sheet_id, p.block_id)
.map_err(|e: BasicError| -> Error { e.into() })?;
let mut exec = self;
for r in 0..row_cnt {
for c in 0..col_cnt {
exec = input_block_cell_template(exec, p.sheet_idx, p.block_id, r, c, ctx)?;
exec = input_block_cell_shadow_template(
exec,
p.sheet_idx,
p.block_id,
r,
c,
crate::sid_assigner::ShadowKind::Validation,
ctx,
)?;
exec = input_block_cell_shadow_template(
exec,
p.sheet_idx,
p.block_id,
r,
c,
crate::sid_assigner::ShadowKind::UserEditable,
ctx,
)?;
}
}
// Any block that ANALYSES this one has generated formulas that
// name this block's fields as runtime strings. Re-binding here
// may have renamed or dropped one of them, and nothing else
// would re-materialize the analysis — its formula would keep
// naming a field that no longer exists, which a `BLOCKREFS`
// resolves to nothing rather than an error. So regenerate
// them. See `design/block-analysis.md` §4.
for analysis in ctx.analyzed_by(sheet_id, p.block_id) {
let Ok((a_rows, a_cols)) = ctx.get_block_size(sheet_id, analysis) else {
continue;
};
for r in 0..a_rows {
for c in 0..a_cols {
exec =
input_block_cell_template(exec, p.sheet_idx, analysis, r, c, ctx)?;
}
}
}
Ok(exec)
}
EditPayload::ConvertBlock(p) => convert_cells_to_block(
self,
p.sheet_idx,
p.id,
p.master_row,
p.master_col,
p.row_cnt,
p.col_cnt,
ctx,
),
EditPayload::CellClear(p) => {
// Clearing a templated cell must not strip the field's
// formula off that row — the container drops the clear too.
if is_templated_at(ctx, p.sheet_idx, p.row, p.col)? {
return Ok(self);
}
remove_formula(self, p.sheet_idx, p.row, p.col, ctx)
}
EditPayload::CreateLink(_) => {
// Creating a link remaps existing formulas' ranges to the block
// (in the range executor). Their dependency edges were built
// against the OLD literal cells, so rebuild them now — this adds
// the block-field / block-all edges via `get_range_deps`, so the
// formulas track the record column as the block grows.
let mut exec = self;
rebuild_range_deps(&mut exec.manager, ctx);
Ok(exec)
}
_ => Ok(self),
}?;
let FormulaExecutor {
mut manager,
mut dirty_vertices,
dirty_ranges,
dirty_blocks,
dirty_cubes,
trigger,
ephemeral_shadows_cleared,
} = executor;
if let Some((sheet, range)) = trigger {
let trigger_vertex = Vertex::Range(sheet, range);
dirty_vertices.insert(trigger_vertex);
// A block-cell write must also dirty the virtual node(s) for
// that block — BlockRef formulas don't have edges into the
// underlying single-cell range. We always dirty `BlockAll` on
// top of the more specific node because:
// * `BLOCKREFS` (Multi) depends only on BlockAll/BlockKey
// (the parser can't know which fields the runtime
// `field_condition` will pick), so a field-cell change must
// reach it via BlockAll.
// * Over-invalidation is fine; the topo sort still only
// re-runs formulas that subscribed.
if let Some(Range::Block(BlockRange::Single(bcid))) = ctx.lookup_range(sheet, range) {
match ctx.block_cell_role(sheet, &bcid) {
BlockCellRole::Field(field_id) => {
dirty_vertices.insert(Vertex::Block(sheet, bcid.block_id, field_id));
dirty_vertices.insert(Vertex::BlockAll(sheet, bcid.block_id));
}
BlockCellRole::Key => {
dirty_vertices.insert(Vertex::BlockKey(sheet, bcid.block_id));
dirty_vertices.insert(Vertex::BlockAll(sheet, bcid.block_id));
}
// A header cell holds a field NAME. Nothing subscribes
// to it: `BLOCKREFS` filters on names as they are
// declared on the schema, never on what a cell of the
// block happens to say, so changing this cell changes no
// formula's answer.
BlockCellRole::Header => {}
BlockCellRole::None => {}
}
}
}
dirty_ranges
.into_iter()
.map(|(s, r)| Vertex::Range(s, r))
.for_each(|v| {
if let Some((sheet, range)) = trigger {
let trigger_vertex = Vertex::Range(sheet, range);
manager.graph.add_dep(v, trigger_vertex);
} else {
dirty_vertices.insert(v);
}
});
dirty_cubes
.into_iter()
.map(|r| Vertex::Cube(r))
.for_each(|v| {
if let Some((sheet, range)) = trigger {
let trigger_vertex = Vertex::Range(sheet, range);
manager.graph.add_dep(v, trigger_vertex);
} else {
dirty_vertices.insert(v);
}
});
// Structural block changes dirty BlockAll. We don't enumerate Block
// / BlockKey here because BlockAll already covers any formula that
// depends on this block.
for (sheet, block) in dirty_blocks {
dirty_vertices.insert(Vertex::BlockAll(sheet, block));
}
Ok(FormulaExecutor {
manager,
dirty_vertices,
trigger,
dirty_cubes: Default::default(),
dirty_ranges: Default::default(),
dirty_blocks: Default::default(),
ephemeral_shadows_cleared,
})
}
}