solve-engine 2.38.13 → 2.38.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{PackageCompatibility-Cu_bHpwY.d.cts → PackageCompatibility-C-3vPMKp.d.cts} +1 -1
- package/dist/{PackageCompatibility-BILTZSHP.d.ts → PackageCompatibility-zdsKvwQI.d.ts} +1 -1
- package/dist/{PackageRegistry-DMKDsYiA.d.ts → PackageRegistry-CStmqgw_.d.ts} +36 -1
- package/dist/{PackageRegistry-wZgm2zzk.d.cts → PackageRegistry-DiHxyxrn.d.cts} +36 -1
- package/dist/{VMBuiltins-D3rXBm2k.d.cts → VMBuiltins-BwqFO2TY.d.cts} +215 -1
- package/dist/{VMBuiltins-Dd0KZR4G.d.ts → VMBuiltins-h09nijID.d.ts} +215 -1
- package/dist/chunk-44BWHZ5V.js +2 -0
- package/dist/chunk-44BWHZ5V.js.map +1 -0
- package/dist/chunk-6UW4JJZV.cjs +3 -0
- package/dist/chunk-6UW4JJZV.cjs.map +1 -0
- package/dist/{chunk-CW623SJ7.cjs → chunk-A3CNNRFM.cjs} +2 -2
- package/dist/{chunk-CW623SJ7.cjs.map → chunk-A3CNNRFM.cjs.map} +1 -1
- package/dist/{chunk-PN6S4SW3.js → chunk-BIV4K7B2.js} +2 -2
- package/dist/{chunk-PN6S4SW3.js.map → chunk-BIV4K7B2.js.map} +1 -1
- package/dist/chunk-ENLFOXF3.js +5 -0
- package/dist/chunk-ENLFOXF3.js.map +1 -0
- package/dist/chunk-HFES6BF5.cjs +2 -0
- package/dist/chunk-HFES6BF5.cjs.map +1 -0
- package/dist/chunk-ZGA7X625.cjs +5 -0
- package/dist/chunk-ZGA7X625.cjs.map +1 -0
- package/dist/chunk-ZYXFJ4X2.js +3 -0
- package/dist/chunk-ZYXFJ4X2.js.map +1 -0
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +4 -4
- package/dist/engine.d.ts +4 -4
- package/dist/engine.js +1 -1
- package/dist/engine.worker.cjs +1 -1
- package/dist/engine.worker.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/language.d.cts +3 -3
- package/dist/language.d.ts +3 -3
- package/dist/packages.d.cts +2 -2
- package/dist/packages.d.ts +2 -2
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +3 -3
- package/dist/testing.d.ts +3 -3
- package/dist/testing.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.cjs.map +1 -1
- package/dist/vm.d.cts +1 -2
- package/dist/vm.d.ts +1 -2
- package/dist/vm.js +1 -1
- package/dist/vm.js.map +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.d.cts +2 -2
- package/dist/worker.d.ts +2 -2
- package/dist/worker.js +1 -1
- package/package.json +1 -1
- package/dist/VMCheckpoints-BXavssWa.d.ts +0 -176
- package/dist/VMCheckpoints-BwLCnV8C.d.cts +0 -176
- package/dist/chunk-3X2DR2QH.js +0 -5
- package/dist/chunk-3X2DR2QH.js.map +0 -1
- package/dist/chunk-QCH4JXSZ.cjs +0 -5
- package/dist/chunk-QCH4JXSZ.cjs.map +0 -1
- package/dist/chunk-SWONJJK3.js +0 -3
- package/dist/chunk-SWONJJK3.js.map +0 -1
- package/dist/chunk-WLY2OSWU.cjs +0 -3
- package/dist/chunk-WLY2OSWU.cjs.map +0 -1
|
@@ -2,7 +2,7 @@ import { a as PrecedenceParser, b as PrefixParselet, I as InfixParselet } from '
|
|
|
2
2
|
import { M as MarkdownLineType, L as Lexer, e as TokenCategory, c as LexerVocabulary } from './Lexer-DPn5dfCH.js';
|
|
3
3
|
import { IAsyncResolver } from './resolvers.js';
|
|
4
4
|
import { T as TokenFusion, c as TokenNormalizer, a as NormalizerRule } from './TokenNormalizer-DAzPp-j1.js';
|
|
5
|
-
import { D as DependencyGraph, V as VM,
|
|
5
|
+
import { b as VMCheckpointer, D as DependencyGraph, V as VM, h as DagSnapshot, i as EngineContext, S as ScopeManager, P as PluginFunctionHandler, A as AsConverter } from './VMBuiltins-h09nijID.js';
|
|
6
6
|
import { V as Value, b as ValueType, D as DatetimeGrain } from './Value-B55Hvn3e.js';
|
|
7
7
|
import { a as BytecodeProgram } from './BytecodeBuilder-DSWKZi4f.js';
|
|
8
8
|
import { C as CalendarBackend } from './CalendarBackend-MdS3Bb4P.js';
|
|
@@ -842,6 +842,23 @@ declare class AsyncResolutionBatcher {
|
|
|
842
842
|
* not register async resolvers at all.
|
|
843
843
|
*/
|
|
844
844
|
onLineResult: ((lineNumber: number, value: Value) => void) | null;
|
|
845
|
+
/**
|
|
846
|
+
* The checkpoint chain to rebuild variable state from, when there is one.
|
|
847
|
+
*
|
|
848
|
+
* A re-run reads whatever the VM currently holds, which after a full pass is
|
|
849
|
+
* the state at the END of the document. That is the right answer only for a
|
|
850
|
+
* name written once. `:x = <fetched>` above `:x = 99` left the fetched value
|
|
851
|
+
* standing at every line below the redefinition, because the line that
|
|
852
|
+
* redefines it was not itself affected and so was not re-run: a line reading
|
|
853
|
+
* `x` below it answered with the value from the top of the document.
|
|
854
|
+
*
|
|
855
|
+
* With a chain, the batch is run as a sweep through the document instead:
|
|
856
|
+
* restore to the line before the first affected one, then walk forward,
|
|
857
|
+
* executing the affected lines and applying the recorded bindings of every
|
|
858
|
+
* writing line passed on the way. Null leaves the previous behaviour exactly
|
|
859
|
+
* as it was, which is what a host driving the batcher on its own gets.
|
|
860
|
+
*/
|
|
861
|
+
checkpointer: VMCheckpointer | null;
|
|
845
862
|
/**
|
|
846
863
|
* Whether {@link warnIfUnwired} has already fired.
|
|
847
864
|
*
|
|
@@ -990,6 +1007,24 @@ declare class AsyncResolutionBatcher {
|
|
|
990
1007
|
* learns about it and stops showing a stale Pending state) and the loop
|
|
991
1008
|
* continues, one line's failure can no longer take out its neighbors.
|
|
992
1009
|
*/
|
|
1010
|
+
/**
|
|
1011
|
+
* Begin a sweep: put the VM into the state the document has just before the
|
|
1012
|
+
* earliest line about to be re-run.
|
|
1013
|
+
*
|
|
1014
|
+
* @param ordered - The lines about to run, in the order they will run.
|
|
1015
|
+
* @returns The sweep's position cursor, or null when there is nothing to do.
|
|
1016
|
+
*/
|
|
1017
|
+
private prepareSweep;
|
|
1018
|
+
/**
|
|
1019
|
+
* Advance the sweep to `lineNumber`, applying every checkpoint passed.
|
|
1020
|
+
*
|
|
1021
|
+
* A line between two affected ones is not re-run, but if it defines
|
|
1022
|
+
* something it still governs what the lines below it read, so its recorded
|
|
1023
|
+
* bindings are put back as the sweep goes by. A line the sweep has already
|
|
1024
|
+
* passed is left alone: the batch runs producers before consumers, and going
|
|
1025
|
+
* backwards would undo a value one of them has just written.
|
|
1026
|
+
*/
|
|
1027
|
+
private sweepTo;
|
|
993
1028
|
private reExecuteMainThread;
|
|
994
1029
|
/**
|
|
995
1030
|
* Notify all consumers of an async resolution event.
|
|
@@ -2,7 +2,7 @@ import { a as PrecedenceParser, b as PrefixParselet, I as InfixParselet } from '
|
|
|
2
2
|
import { M as MarkdownLineType, L as Lexer, e as TokenCategory, c as LexerVocabulary } from './Lexer-DaWkCu84.cjs';
|
|
3
3
|
import { IAsyncResolver } from './resolvers.cjs';
|
|
4
4
|
import { T as TokenFusion, c as TokenNormalizer, a as NormalizerRule } from './TokenNormalizer-D382VSYh.cjs';
|
|
5
|
-
import { D as DependencyGraph, V as VM,
|
|
5
|
+
import { b as VMCheckpointer, D as DependencyGraph, V as VM, h as DagSnapshot, i as EngineContext, S as ScopeManager, P as PluginFunctionHandler, A as AsConverter } from './VMBuiltins-BwqFO2TY.cjs';
|
|
6
6
|
import { V as Value, b as ValueType, D as DatetimeGrain } from './Value-B55Hvn3e.cjs';
|
|
7
7
|
import { a as BytecodeProgram } from './BytecodeBuilder-DSWKZi4f.cjs';
|
|
8
8
|
import { C as CalendarBackend } from './CalendarBackend-MdS3Bb4P.cjs';
|
|
@@ -842,6 +842,23 @@ declare class AsyncResolutionBatcher {
|
|
|
842
842
|
* not register async resolvers at all.
|
|
843
843
|
*/
|
|
844
844
|
onLineResult: ((lineNumber: number, value: Value) => void) | null;
|
|
845
|
+
/**
|
|
846
|
+
* The checkpoint chain to rebuild variable state from, when there is one.
|
|
847
|
+
*
|
|
848
|
+
* A re-run reads whatever the VM currently holds, which after a full pass is
|
|
849
|
+
* the state at the END of the document. That is the right answer only for a
|
|
850
|
+
* name written once. `:x = <fetched>` above `:x = 99` left the fetched value
|
|
851
|
+
* standing at every line below the redefinition, because the line that
|
|
852
|
+
* redefines it was not itself affected and so was not re-run: a line reading
|
|
853
|
+
* `x` below it answered with the value from the top of the document.
|
|
854
|
+
*
|
|
855
|
+
* With a chain, the batch is run as a sweep through the document instead:
|
|
856
|
+
* restore to the line before the first affected one, then walk forward,
|
|
857
|
+
* executing the affected lines and applying the recorded bindings of every
|
|
858
|
+
* writing line passed on the way. Null leaves the previous behaviour exactly
|
|
859
|
+
* as it was, which is what a host driving the batcher on its own gets.
|
|
860
|
+
*/
|
|
861
|
+
checkpointer: VMCheckpointer | null;
|
|
845
862
|
/**
|
|
846
863
|
* Whether {@link warnIfUnwired} has already fired.
|
|
847
864
|
*
|
|
@@ -990,6 +1007,24 @@ declare class AsyncResolutionBatcher {
|
|
|
990
1007
|
* learns about it and stops showing a stale Pending state) and the loop
|
|
991
1008
|
* continues, one line's failure can no longer take out its neighbors.
|
|
992
1009
|
*/
|
|
1010
|
+
/**
|
|
1011
|
+
* Begin a sweep: put the VM into the state the document has just before the
|
|
1012
|
+
* earliest line about to be re-run.
|
|
1013
|
+
*
|
|
1014
|
+
* @param ordered - The lines about to run, in the order they will run.
|
|
1015
|
+
* @returns The sweep's position cursor, or null when there is nothing to do.
|
|
1016
|
+
*/
|
|
1017
|
+
private prepareSweep;
|
|
1018
|
+
/**
|
|
1019
|
+
* Advance the sweep to `lineNumber`, applying every checkpoint passed.
|
|
1020
|
+
*
|
|
1021
|
+
* A line between two affected ones is not re-run, but if it defines
|
|
1022
|
+
* something it still governs what the lines below it read, so its recorded
|
|
1023
|
+
* bindings are put back as the sweep goes by. A line the sweep has already
|
|
1024
|
+
* passed is left alone: the batch runs producers before consumers, and going
|
|
1025
|
+
* backwards would undo a value one of them has just written.
|
|
1026
|
+
*/
|
|
1027
|
+
private sweepTo;
|
|
993
1028
|
private reExecuteMainThread;
|
|
994
1029
|
/**
|
|
995
1030
|
* Notify all consumers of an async resolution event.
|
|
@@ -892,6 +892,220 @@ declare class ScopeManager {
|
|
|
892
892
|
clear(): void;
|
|
893
893
|
}
|
|
894
894
|
|
|
895
|
+
/**
|
|
896
|
+
* A point-in-time snapshot of VM variable state.
|
|
897
|
+
*
|
|
898
|
+
* Each checkpoint holds only the variables that CHANGED at its line, and
|
|
899
|
+
* reaches the rest through its `parent` link. A lookup walks that chain until
|
|
900
|
+
* it finds the name; a restore walks it from the root applying each link's own
|
|
901
|
+
* bindings in turn, so a later line's value naturally overwrites an earlier
|
|
902
|
+
* one's.
|
|
903
|
+
*
|
|
904
|
+
* ```text
|
|
905
|
+
* Checkpoint 0 (root): {} // empty scope
|
|
906
|
+
* Checkpoint 1 (:x=5): { x: 5 } parent → 0
|
|
907
|
+
* Checkpoint 2 (:y=8): { y: 8 } parent → 1
|
|
908
|
+
* Checkpoint 3 (:x=3): { x: 3 } parent → 2 // shadows x=5
|
|
909
|
+
* ```
|
|
910
|
+
*
|
|
911
|
+
* To look up `x` at checkpoint 3: find own `x=3` → done.
|
|
912
|
+
* To look up `y` at checkpoint 3: not own → walk parent to checkpoint 2 → `y=8`.
|
|
913
|
+
* To look up `z` at checkpoint 3: not found anywhere → undefined.
|
|
914
|
+
*
|
|
915
|
+
* **Memory:** O(number of variable definitions) heap, independent of
|
|
916
|
+
* document length. Typical Obsidian documents have < 100 variable defs,
|
|
917
|
+
* so total checkpoint heap is < 10 KB.
|
|
918
|
+
*/
|
|
919
|
+
interface VMCheckpoint {
|
|
920
|
+
/** 1-based line number where this checkpoint was created. */
|
|
921
|
+
lineNumber: number;
|
|
922
|
+
/** Persistent line ID from DocumentModel. */
|
|
923
|
+
lineId: number;
|
|
924
|
+
/**
|
|
925
|
+
* Variable name → Value at this checkpoint.
|
|
926
|
+
* Only the variables set or updated at this line; the rest are reached
|
|
927
|
+
* through {@link VMCheckpoint.parent}.
|
|
928
|
+
*/
|
|
929
|
+
variables: Record<string, Value>;
|
|
930
|
+
/**
|
|
931
|
+
* User-defined-function name → definition at this checkpoint. SEPARATE
|
|
932
|
+
* from `variables` above (not prototypally chained the same way
|
|
933
|
+
* `restoreTo()` replays every checkpoint in the chain in order, so a
|
|
934
|
+
* later redefinition of the same function name naturally overwrites an
|
|
935
|
+
* earlier one during replay, without needing its own prototype walk).
|
|
936
|
+
*
|
|
937
|
+
* Without this field, a function definition's checkpoint entry would be
|
|
938
|
+
* SILENTLY LOST: `snapshot()` used to call `vm.getVar(name)` for every
|
|
939
|
+
* written name, which returns `undefined` for a function name (function
|
|
940
|
+
* defs live in `vm.userFunctions`, not the flat variable store), and a
|
|
941
|
+
* `val !== undefined` guard silently skipped it. A scroll-triggered
|
|
942
|
+
* `restoreTo()` would then reset the VM and replay only `variables`,
|
|
943
|
+
* making a function defined above the new viewport vanish (calling it
|
|
944
|
+
* would throw `UNDEFINED_FUNCTION`) even though the document still
|
|
945
|
+
* shows its definition line as clean/cached.
|
|
946
|
+
*/
|
|
947
|
+
functions: Record<string, UserFunctionDef>;
|
|
948
|
+
/** Parent checkpoint (closer to document start), or null for root. */
|
|
949
|
+
parent: VMCheckpoint | null;
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* Manages VM state checkpoints for the three-tier evaluation strategy.
|
|
953
|
+
*
|
|
954
|
+
* **Checkpoint creation:** After a variable-definition line executes
|
|
955
|
+
* (Tier 1 or Tier 3), `snapshot()` records the current values of the
|
|
956
|
+
* written variables. The checkpoint is linked via prototypal inheritance
|
|
957
|
+
* to the previous checkpoint, so only changed variables consume memory.
|
|
958
|
+
*
|
|
959
|
+
* **Checkpoint restoration:** Before evaluating a viewport whose start line
|
|
960
|
+
* is not line 1, `restoreTo(lineNumber)` resets the VM and replays all
|
|
961
|
+
* variable definitions up to and including that line. This avoids
|
|
962
|
+
* re-evaluating the entire document from line 1 on every scroll.
|
|
963
|
+
*
|
|
964
|
+
* **Thread safety:** Checkpoints are created synchronously on the main
|
|
965
|
+
* thread during evaluation. They are immutable after creation (Value is
|
|
966
|
+
* an immutable type), so no synchronization is needed.
|
|
967
|
+
*
|
|
968
|
+
* **Integration with Phase 5.2e:** `setViewport()` will use `getNearestCheckpoint()`
|
|
969
|
+
* to find the checkpoint just before the new viewport start, then call
|
|
970
|
+
* `restoreTo()` to set up the VM before evaluating only the visible lines.
|
|
971
|
+
* This is the key to O(visible lines) scrolling instead of O(document).
|
|
972
|
+
*/
|
|
973
|
+
declare class VMCheckpointer {
|
|
974
|
+
/** Ordered array of checkpoints (ascending lineNumber). */
|
|
975
|
+
private checkpoints;
|
|
976
|
+
/** The VM instance whose variables are snapshotted/restored. */
|
|
977
|
+
private vm;
|
|
978
|
+
constructor(vm: VM);
|
|
979
|
+
/**
|
|
980
|
+
* Create a checkpoint at the current line, recording the VM values of
|
|
981
|
+
* the specified variables.
|
|
982
|
+
*
|
|
983
|
+
* Records only what this line wrote; the rest is reached through the
|
|
984
|
+
* parent link rather than copied.
|
|
985
|
+
*
|
|
986
|
+
* A line that is snapshotted again drops every checkpoint at or after it
|
|
987
|
+
* first, so the list stays in document order and the new checkpoint
|
|
988
|
+
* inherits from the line before it rather than from one after it. See the
|
|
989
|
+
* body for what went wrong without that.
|
|
990
|
+
*
|
|
991
|
+
* @param lineNumber 1-based line position.
|
|
992
|
+
* @param lineId Persistent line ID from DocumentModel.
|
|
993
|
+
* @param variableNames Names of variables that were written at this line.
|
|
994
|
+
* @returns The new checkpoint, or null if no variable names provided.
|
|
995
|
+
*/
|
|
996
|
+
snapshot(lineNumber: number, lineId: number, variableNames: string[]): VMCheckpoint | null;
|
|
997
|
+
/**
|
|
998
|
+
* Restore the VM to the state at or just after the given line number.
|
|
999
|
+
*
|
|
1000
|
+
* Finds the nearest checkpoint whose `lineNumber <= targetLineNumber`,
|
|
1001
|
+
* then replays all variable definitions from root → that checkpoint
|
|
1002
|
+
* into the VM via `setVar()`. The VM's stack is also reset.
|
|
1003
|
+
*
|
|
1004
|
+
* If no checkpoint exists at or before the target line, the VM is
|
|
1005
|
+
* fully reset (empty scope, empty stack).
|
|
1006
|
+
*
|
|
1007
|
+
* **Performance:** O(total variable definitions before the line), since
|
|
1008
|
+
* each checkpoint in the chain contributes only the names its own line
|
|
1009
|
+
* wrote.
|
|
1010
|
+
*
|
|
1011
|
+
* @param lineNumber Target 1-based line number. The VM will have the
|
|
1012
|
+
* state that existed AFTER evaluating lines up to `lineNumber`.
|
|
1013
|
+
*/
|
|
1014
|
+
restoreTo(lineNumber: number): void;
|
|
1015
|
+
/** The index of the checkpoint recorded exactly at `lineNumber`, or -1. */
|
|
1016
|
+
private indexOfCheckpointAt;
|
|
1017
|
+
/** Where a checkpoint for `lineNumber` belongs, keeping the list in order. */
|
|
1018
|
+
private insertionIndexFor;
|
|
1019
|
+
/**
|
|
1020
|
+
* The index of the last checkpoint at or before `lineNumber`, or -1.
|
|
1021
|
+
*
|
|
1022
|
+
* A binary search rather than a scan. The array is in document order, and
|
|
1023
|
+
* this is asked once per scroll and once per async batch, on a document
|
|
1024
|
+
* that can hold a checkpoint per definition.
|
|
1025
|
+
*/
|
|
1026
|
+
private nearestCheckpointIndex;
|
|
1027
|
+
/**
|
|
1028
|
+
* Record what `lineNumber` has just written, without disturbing the chain
|
|
1029
|
+
* after it.
|
|
1030
|
+
*
|
|
1031
|
+
* {@link snapshot} drops every checkpoint at or after the line, which is
|
|
1032
|
+
* right for a pass running forward in document order: it re-takes them as it
|
|
1033
|
+
* goes. A caller re-running a few lines out of a document does not, and
|
|
1034
|
+
* dropping the entries for lines it will never visit would lose the very
|
|
1035
|
+
* bindings it is sweeping through them to collect. So this overwrites in
|
|
1036
|
+
* place instead.
|
|
1037
|
+
*
|
|
1038
|
+
* Safe against the prototype chain, because it replaces only the
|
|
1039
|
+
* checkpoint's OWN bindings: a later checkpoint that also writes the name
|
|
1040
|
+
* holds its own copy and goes on shadowing this one.
|
|
1041
|
+
*
|
|
1042
|
+
* @param lineNumber 1-based line whose recorded bindings are refreshed.
|
|
1043
|
+
* @param variableNames The names it wrote.
|
|
1044
|
+
* @returns Whether a checkpoint existed at that line to update.
|
|
1045
|
+
*/
|
|
1046
|
+
updateCheckpointAt(lineNumber: number, variableNames: string[]): boolean;
|
|
1047
|
+
/**
|
|
1048
|
+
* Apply the bindings recorded AT `lineNumber`, leaving the rest of the VM
|
|
1049
|
+
* alone.
|
|
1050
|
+
*
|
|
1051
|
+
* {@link restoreTo} rebuilds the whole prefix, which costs the chain every
|
|
1052
|
+
* time it is called. A caller moving forward through the document already
|
|
1053
|
+
* holds the prefix up to the line before, and needs only what this line
|
|
1054
|
+
* added: restoring once and then applying each line in turn as it is passed
|
|
1055
|
+
* costs the chain once rather than once per line.
|
|
1056
|
+
*
|
|
1057
|
+
* @param lineNumber 1-based line whose own bindings are applied.
|
|
1058
|
+
* @returns Whether a checkpoint existed at that line.
|
|
1059
|
+
*/
|
|
1060
|
+
applyCheckpointAt(lineNumber: number): boolean;
|
|
1061
|
+
/**
|
|
1062
|
+
* Find the nearest checkpoint at or before the given line number.
|
|
1063
|
+
*
|
|
1064
|
+
* Uses linear scan (checkpoints are sorted by lineNumber and the list
|
|
1065
|
+
* is short, typically < 20 for Obsidian documents). Can be upgraded
|
|
1066
|
+
* to binary search if needed for documents with 1000+ variable defs.
|
|
1067
|
+
*
|
|
1068
|
+
* @returns The nearest checkpoint, or null if none exists before the line.
|
|
1069
|
+
*/
|
|
1070
|
+
getNearestCheckpoint(lineNumber: number): VMCheckpoint | null;
|
|
1071
|
+
/**
|
|
1072
|
+
* Get a specific checkpoint by its line number.
|
|
1073
|
+
* @returns The checkpoint, or undefined if not found.
|
|
1074
|
+
*/
|
|
1075
|
+
getCheckpointAt(lineNumber: number): VMCheckpoint | undefined;
|
|
1076
|
+
/**
|
|
1077
|
+
* Get the entire checkpoint chain from root to the last checkpoint.
|
|
1078
|
+
* Useful for debugging and serialization.
|
|
1079
|
+
*/
|
|
1080
|
+
getAllCheckpoints(): readonly VMCheckpoint[];
|
|
1081
|
+
/**
|
|
1082
|
+
* Look up a variable's value through the checkpoint chain.
|
|
1083
|
+
*
|
|
1084
|
+
* Walks the prototype chain starting from the most recent checkpoint,
|
|
1085
|
+
* looking for the variable name as an own property. This is O(depth)
|
|
1086
|
+
* where depth is the number of checkpoints since the variable was
|
|
1087
|
+
* last set.
|
|
1088
|
+
*
|
|
1089
|
+
* **Note:** This queries the checkpointer's snapshot, not the VM.
|
|
1090
|
+
* The VM may have been modified since the last snapshot (e.g., by
|
|
1091
|
+
* Tier 2 execution of non-variable-def lines that don't create checkpoints).
|
|
1092
|
+
*
|
|
1093
|
+
* @returns The Value, or undefined if the variable was never set.
|
|
1094
|
+
*/
|
|
1095
|
+
lookupVariable(name: string): Value | undefined;
|
|
1096
|
+
/**
|
|
1097
|
+
* Clear all checkpoints. The underlying VM is NOT reset, call
|
|
1098
|
+
* `vm.reset()` separately if needed.
|
|
1099
|
+
*/
|
|
1100
|
+
clear(): void;
|
|
1101
|
+
/** Number of checkpoints stored. */
|
|
1102
|
+
get count(): number;
|
|
1103
|
+
/** Returns true if no checkpoints have been created. */
|
|
1104
|
+
get isEmpty(): boolean;
|
|
1105
|
+
/** The associated VM instance. */
|
|
1106
|
+
get vmInstance(): VM;
|
|
1107
|
+
}
|
|
1108
|
+
|
|
895
1109
|
/**
|
|
896
1110
|
* Registry of built-in mathematical functions.
|
|
897
1111
|
* Indexed by the number pushed as an operand of OpCode.CALL_BUILTIN.
|
|
@@ -951,4 +1165,4 @@ declare function pluginFunctionIndexFor(qualifiedName: string): number;
|
|
|
951
1165
|
*/
|
|
952
1166
|
type AsConverter = (value: Value, context?: LineExecutionContext) => Value;
|
|
953
1167
|
|
|
954
|
-
export { type AsConverter as A, type Bytecode as B, DependencyGraph as D, type ExpressionRecord as E, type LineExecutionContext as L, OpRegistry as O, type PluginFunctionHandler as P, ScopeManager as S, type VM as V,
|
|
1168
|
+
export { type AsConverter as A, type Bytecode as B, DependencyGraph as D, type ExpressionRecord as E, type LineExecutionContext as L, OpRegistry as O, type PluginFunctionHandler as P, ScopeManager as S, type VM as V, type VMCheckpoint as a, VMCheckpointer as b, allocatePluginFunctionIndex as c, builtinFunctions as d, createVM as e, executeBytecode as f, pluginFunctionRegistry as g, type DagSnapshot as h, type EngineContext as i, pluginFunctionIndexFor as p, sharedOpRegistry as s };
|
|
@@ -892,6 +892,220 @@ declare class ScopeManager {
|
|
|
892
892
|
clear(): void;
|
|
893
893
|
}
|
|
894
894
|
|
|
895
|
+
/**
|
|
896
|
+
* A point-in-time snapshot of VM variable state.
|
|
897
|
+
*
|
|
898
|
+
* Each checkpoint holds only the variables that CHANGED at its line, and
|
|
899
|
+
* reaches the rest through its `parent` link. A lookup walks that chain until
|
|
900
|
+
* it finds the name; a restore walks it from the root applying each link's own
|
|
901
|
+
* bindings in turn, so a later line's value naturally overwrites an earlier
|
|
902
|
+
* one's.
|
|
903
|
+
*
|
|
904
|
+
* ```text
|
|
905
|
+
* Checkpoint 0 (root): {} // empty scope
|
|
906
|
+
* Checkpoint 1 (:x=5): { x: 5 } parent → 0
|
|
907
|
+
* Checkpoint 2 (:y=8): { y: 8 } parent → 1
|
|
908
|
+
* Checkpoint 3 (:x=3): { x: 3 } parent → 2 // shadows x=5
|
|
909
|
+
* ```
|
|
910
|
+
*
|
|
911
|
+
* To look up `x` at checkpoint 3: find own `x=3` → done.
|
|
912
|
+
* To look up `y` at checkpoint 3: not own → walk parent to checkpoint 2 → `y=8`.
|
|
913
|
+
* To look up `z` at checkpoint 3: not found anywhere → undefined.
|
|
914
|
+
*
|
|
915
|
+
* **Memory:** O(number of variable definitions) heap, independent of
|
|
916
|
+
* document length. Typical Obsidian documents have < 100 variable defs,
|
|
917
|
+
* so total checkpoint heap is < 10 KB.
|
|
918
|
+
*/
|
|
919
|
+
interface VMCheckpoint {
|
|
920
|
+
/** 1-based line number where this checkpoint was created. */
|
|
921
|
+
lineNumber: number;
|
|
922
|
+
/** Persistent line ID from DocumentModel. */
|
|
923
|
+
lineId: number;
|
|
924
|
+
/**
|
|
925
|
+
* Variable name → Value at this checkpoint.
|
|
926
|
+
* Only the variables set or updated at this line; the rest are reached
|
|
927
|
+
* through {@link VMCheckpoint.parent}.
|
|
928
|
+
*/
|
|
929
|
+
variables: Record<string, Value>;
|
|
930
|
+
/**
|
|
931
|
+
* User-defined-function name → definition at this checkpoint. SEPARATE
|
|
932
|
+
* from `variables` above (not prototypally chained the same way
|
|
933
|
+
* `restoreTo()` replays every checkpoint in the chain in order, so a
|
|
934
|
+
* later redefinition of the same function name naturally overwrites an
|
|
935
|
+
* earlier one during replay, without needing its own prototype walk).
|
|
936
|
+
*
|
|
937
|
+
* Without this field, a function definition's checkpoint entry would be
|
|
938
|
+
* SILENTLY LOST: `snapshot()` used to call `vm.getVar(name)` for every
|
|
939
|
+
* written name, which returns `undefined` for a function name (function
|
|
940
|
+
* defs live in `vm.userFunctions`, not the flat variable store), and a
|
|
941
|
+
* `val !== undefined` guard silently skipped it. A scroll-triggered
|
|
942
|
+
* `restoreTo()` would then reset the VM and replay only `variables`,
|
|
943
|
+
* making a function defined above the new viewport vanish (calling it
|
|
944
|
+
* would throw `UNDEFINED_FUNCTION`) even though the document still
|
|
945
|
+
* shows its definition line as clean/cached.
|
|
946
|
+
*/
|
|
947
|
+
functions: Record<string, UserFunctionDef>;
|
|
948
|
+
/** Parent checkpoint (closer to document start), or null for root. */
|
|
949
|
+
parent: VMCheckpoint | null;
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* Manages VM state checkpoints for the three-tier evaluation strategy.
|
|
953
|
+
*
|
|
954
|
+
* **Checkpoint creation:** After a variable-definition line executes
|
|
955
|
+
* (Tier 1 or Tier 3), `snapshot()` records the current values of the
|
|
956
|
+
* written variables. The checkpoint is linked via prototypal inheritance
|
|
957
|
+
* to the previous checkpoint, so only changed variables consume memory.
|
|
958
|
+
*
|
|
959
|
+
* **Checkpoint restoration:** Before evaluating a viewport whose start line
|
|
960
|
+
* is not line 1, `restoreTo(lineNumber)` resets the VM and replays all
|
|
961
|
+
* variable definitions up to and including that line. This avoids
|
|
962
|
+
* re-evaluating the entire document from line 1 on every scroll.
|
|
963
|
+
*
|
|
964
|
+
* **Thread safety:** Checkpoints are created synchronously on the main
|
|
965
|
+
* thread during evaluation. They are immutable after creation (Value is
|
|
966
|
+
* an immutable type), so no synchronization is needed.
|
|
967
|
+
*
|
|
968
|
+
* **Integration with Phase 5.2e:** `setViewport()` will use `getNearestCheckpoint()`
|
|
969
|
+
* to find the checkpoint just before the new viewport start, then call
|
|
970
|
+
* `restoreTo()` to set up the VM before evaluating only the visible lines.
|
|
971
|
+
* This is the key to O(visible lines) scrolling instead of O(document).
|
|
972
|
+
*/
|
|
973
|
+
declare class VMCheckpointer {
|
|
974
|
+
/** Ordered array of checkpoints (ascending lineNumber). */
|
|
975
|
+
private checkpoints;
|
|
976
|
+
/** The VM instance whose variables are snapshotted/restored. */
|
|
977
|
+
private vm;
|
|
978
|
+
constructor(vm: VM);
|
|
979
|
+
/**
|
|
980
|
+
* Create a checkpoint at the current line, recording the VM values of
|
|
981
|
+
* the specified variables.
|
|
982
|
+
*
|
|
983
|
+
* Records only what this line wrote; the rest is reached through the
|
|
984
|
+
* parent link rather than copied.
|
|
985
|
+
*
|
|
986
|
+
* A line that is snapshotted again drops every checkpoint at or after it
|
|
987
|
+
* first, so the list stays in document order and the new checkpoint
|
|
988
|
+
* inherits from the line before it rather than from one after it. See the
|
|
989
|
+
* body for what went wrong without that.
|
|
990
|
+
*
|
|
991
|
+
* @param lineNumber 1-based line position.
|
|
992
|
+
* @param lineId Persistent line ID from DocumentModel.
|
|
993
|
+
* @param variableNames Names of variables that were written at this line.
|
|
994
|
+
* @returns The new checkpoint, or null if no variable names provided.
|
|
995
|
+
*/
|
|
996
|
+
snapshot(lineNumber: number, lineId: number, variableNames: string[]): VMCheckpoint | null;
|
|
997
|
+
/**
|
|
998
|
+
* Restore the VM to the state at or just after the given line number.
|
|
999
|
+
*
|
|
1000
|
+
* Finds the nearest checkpoint whose `lineNumber <= targetLineNumber`,
|
|
1001
|
+
* then replays all variable definitions from root → that checkpoint
|
|
1002
|
+
* into the VM via `setVar()`. The VM's stack is also reset.
|
|
1003
|
+
*
|
|
1004
|
+
* If no checkpoint exists at or before the target line, the VM is
|
|
1005
|
+
* fully reset (empty scope, empty stack).
|
|
1006
|
+
*
|
|
1007
|
+
* **Performance:** O(total variable definitions before the line), since
|
|
1008
|
+
* each checkpoint in the chain contributes only the names its own line
|
|
1009
|
+
* wrote.
|
|
1010
|
+
*
|
|
1011
|
+
* @param lineNumber Target 1-based line number. The VM will have the
|
|
1012
|
+
* state that existed AFTER evaluating lines up to `lineNumber`.
|
|
1013
|
+
*/
|
|
1014
|
+
restoreTo(lineNumber: number): void;
|
|
1015
|
+
/** The index of the checkpoint recorded exactly at `lineNumber`, or -1. */
|
|
1016
|
+
private indexOfCheckpointAt;
|
|
1017
|
+
/** Where a checkpoint for `lineNumber` belongs, keeping the list in order. */
|
|
1018
|
+
private insertionIndexFor;
|
|
1019
|
+
/**
|
|
1020
|
+
* The index of the last checkpoint at or before `lineNumber`, or -1.
|
|
1021
|
+
*
|
|
1022
|
+
* A binary search rather than a scan. The array is in document order, and
|
|
1023
|
+
* this is asked once per scroll and once per async batch, on a document
|
|
1024
|
+
* that can hold a checkpoint per definition.
|
|
1025
|
+
*/
|
|
1026
|
+
private nearestCheckpointIndex;
|
|
1027
|
+
/**
|
|
1028
|
+
* Record what `lineNumber` has just written, without disturbing the chain
|
|
1029
|
+
* after it.
|
|
1030
|
+
*
|
|
1031
|
+
* {@link snapshot} drops every checkpoint at or after the line, which is
|
|
1032
|
+
* right for a pass running forward in document order: it re-takes them as it
|
|
1033
|
+
* goes. A caller re-running a few lines out of a document does not, and
|
|
1034
|
+
* dropping the entries for lines it will never visit would lose the very
|
|
1035
|
+
* bindings it is sweeping through them to collect. So this overwrites in
|
|
1036
|
+
* place instead.
|
|
1037
|
+
*
|
|
1038
|
+
* Safe against the prototype chain, because it replaces only the
|
|
1039
|
+
* checkpoint's OWN bindings: a later checkpoint that also writes the name
|
|
1040
|
+
* holds its own copy and goes on shadowing this one.
|
|
1041
|
+
*
|
|
1042
|
+
* @param lineNumber 1-based line whose recorded bindings are refreshed.
|
|
1043
|
+
* @param variableNames The names it wrote.
|
|
1044
|
+
* @returns Whether a checkpoint existed at that line to update.
|
|
1045
|
+
*/
|
|
1046
|
+
updateCheckpointAt(lineNumber: number, variableNames: string[]): boolean;
|
|
1047
|
+
/**
|
|
1048
|
+
* Apply the bindings recorded AT `lineNumber`, leaving the rest of the VM
|
|
1049
|
+
* alone.
|
|
1050
|
+
*
|
|
1051
|
+
* {@link restoreTo} rebuilds the whole prefix, which costs the chain every
|
|
1052
|
+
* time it is called. A caller moving forward through the document already
|
|
1053
|
+
* holds the prefix up to the line before, and needs only what this line
|
|
1054
|
+
* added: restoring once and then applying each line in turn as it is passed
|
|
1055
|
+
* costs the chain once rather than once per line.
|
|
1056
|
+
*
|
|
1057
|
+
* @param lineNumber 1-based line whose own bindings are applied.
|
|
1058
|
+
* @returns Whether a checkpoint existed at that line.
|
|
1059
|
+
*/
|
|
1060
|
+
applyCheckpointAt(lineNumber: number): boolean;
|
|
1061
|
+
/**
|
|
1062
|
+
* Find the nearest checkpoint at or before the given line number.
|
|
1063
|
+
*
|
|
1064
|
+
* Uses linear scan (checkpoints are sorted by lineNumber and the list
|
|
1065
|
+
* is short, typically < 20 for Obsidian documents). Can be upgraded
|
|
1066
|
+
* to binary search if needed for documents with 1000+ variable defs.
|
|
1067
|
+
*
|
|
1068
|
+
* @returns The nearest checkpoint, or null if none exists before the line.
|
|
1069
|
+
*/
|
|
1070
|
+
getNearestCheckpoint(lineNumber: number): VMCheckpoint | null;
|
|
1071
|
+
/**
|
|
1072
|
+
* Get a specific checkpoint by its line number.
|
|
1073
|
+
* @returns The checkpoint, or undefined if not found.
|
|
1074
|
+
*/
|
|
1075
|
+
getCheckpointAt(lineNumber: number): VMCheckpoint | undefined;
|
|
1076
|
+
/**
|
|
1077
|
+
* Get the entire checkpoint chain from root to the last checkpoint.
|
|
1078
|
+
* Useful for debugging and serialization.
|
|
1079
|
+
*/
|
|
1080
|
+
getAllCheckpoints(): readonly VMCheckpoint[];
|
|
1081
|
+
/**
|
|
1082
|
+
* Look up a variable's value through the checkpoint chain.
|
|
1083
|
+
*
|
|
1084
|
+
* Walks the prototype chain starting from the most recent checkpoint,
|
|
1085
|
+
* looking for the variable name as an own property. This is O(depth)
|
|
1086
|
+
* where depth is the number of checkpoints since the variable was
|
|
1087
|
+
* last set.
|
|
1088
|
+
*
|
|
1089
|
+
* **Note:** This queries the checkpointer's snapshot, not the VM.
|
|
1090
|
+
* The VM may have been modified since the last snapshot (e.g., by
|
|
1091
|
+
* Tier 2 execution of non-variable-def lines that don't create checkpoints).
|
|
1092
|
+
*
|
|
1093
|
+
* @returns The Value, or undefined if the variable was never set.
|
|
1094
|
+
*/
|
|
1095
|
+
lookupVariable(name: string): Value | undefined;
|
|
1096
|
+
/**
|
|
1097
|
+
* Clear all checkpoints. The underlying VM is NOT reset, call
|
|
1098
|
+
* `vm.reset()` separately if needed.
|
|
1099
|
+
*/
|
|
1100
|
+
clear(): void;
|
|
1101
|
+
/** Number of checkpoints stored. */
|
|
1102
|
+
get count(): number;
|
|
1103
|
+
/** Returns true if no checkpoints have been created. */
|
|
1104
|
+
get isEmpty(): boolean;
|
|
1105
|
+
/** The associated VM instance. */
|
|
1106
|
+
get vmInstance(): VM;
|
|
1107
|
+
}
|
|
1108
|
+
|
|
895
1109
|
/**
|
|
896
1110
|
* Registry of built-in mathematical functions.
|
|
897
1111
|
* Indexed by the number pushed as an operand of OpCode.CALL_BUILTIN.
|
|
@@ -951,4 +1165,4 @@ declare function pluginFunctionIndexFor(qualifiedName: string): number;
|
|
|
951
1165
|
*/
|
|
952
1166
|
type AsConverter = (value: Value, context?: LineExecutionContext) => Value;
|
|
953
1167
|
|
|
954
|
-
export { type AsConverter as A, type Bytecode as B, DependencyGraph as D, type ExpressionRecord as E, type LineExecutionContext as L, OpRegistry as O, type PluginFunctionHandler as P, ScopeManager as S, type VM as V,
|
|
1168
|
+
export { type AsConverter as A, type Bytecode as B, DependencyGraph as D, type ExpressionRecord as E, type LineExecutionContext as L, OpRegistry as O, type PluginFunctionHandler as P, ScopeManager as S, type VM as V, type VMCheckpoint as a, VMCheckpointer as b, allocatePluginFunctionIndex as c, builtinFunctions as d, createVM as e, executeBytecode as f, pluginFunctionRegistry as g, type DagSnapshot as h, type EngineContext as i, pluginFunctionIndexFor as p, sharedOpRegistry as s };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var f=class{constructor(t){this.checkpoints=[];this.vm=t;}snapshot(t,e,n){if(n.length===0)return null;let i=this.indexOfCheckpointAt(t),s=i>=0?i:this.insertionIndexFor(t),r=s>0?this.checkpoints[s-1]:null,h=Object.create(null),u=Object.create(null);for(let o of n){if(this.vm.hasUserFunction(o)){let l=this.vm.getUserFunction(o);l&&(u[o]=l);continue}let p=this.vm.getVar(o);p!==void 0&&(h[o]=p);}let c={lineNumber:t,lineId:e,variables:h,functions:u,parent:r};i>=0?this.checkpoints[i]=c:this.checkpoints.splice(s,0,c);let a=this.checkpoints[s+1];return a!==void 0&&(a.parent=c),c}restoreTo(t){let e=this.nearestCheckpointIndex(t);this.vm.reset();for(let n=0;n<=e;n++){let i=this.checkpoints[n];for(let s of Object.keys(i.variables))this.vm.setVar(s,i.variables[s]);for(let s of Object.keys(i.functions)){let r=i.functions[s];this.vm.defineUserFunction(r.name,r.params,r.program);}}}indexOfCheckpointAt(t){let e=this.nearestCheckpointIndex(t);return e>=0&&this.checkpoints[e].lineNumber===t?e:-1}insertionIndexFor(t){return this.nearestCheckpointIndex(t)+1}nearestCheckpointIndex(t){let e=0,n=this.checkpoints.length-1,i=-1;for(;e<=n;){let s=e+n>>1;this.checkpoints[s].lineNumber<=t?(i=s,e=s+1):n=s-1;}return i}updateCheckpointAt(t,e){let n=this.getCheckpointAt(t);if(!n)return false;for(let i of e){if(this.vm.hasUserFunction(i)){let r=this.vm.getUserFunction(i);r&&(n.functions[i]=r);continue}let s=this.vm.getVar(i);s!==void 0&&(n.variables[i]=s);}return true}applyCheckpointAt(t){let e=this.getCheckpointAt(t);if(!e)return false;for(let n of Object.keys(e.variables))this.vm.setVar(n,e.variables[n]);for(let n of Object.keys(e.functions)){let i=e.functions[n];this.vm.defineUserFunction(i.name,i.params,i.program);}return true}getNearestCheckpoint(t){let e=this.nearestCheckpointIndex(t);return e<0?null:this.checkpoints[e]}getCheckpointAt(t){let e=this.nearestCheckpointIndex(t);if(e<0)return;let n=this.checkpoints[e];return n.lineNumber===t?n:void 0}getAllCheckpoints(){return this.checkpoints}lookupVariable(t){if(this.checkpoints.length===0)return;let e=this.checkpoints[this.checkpoints.length-1];for(;e;){if(Object.prototype.hasOwnProperty.call(e.variables,t))return e.variables[t];e=e.parent;}}clear(){this.checkpoints=[];}get count(){return this.checkpoints.length}get isEmpty(){return this.checkpoints.length===0}get vmInstance(){return this.vm}};export{f as a};//# sourceMappingURL=chunk-44BWHZ5V.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-44BWHZ5V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vm/VMCheckpoints.ts"],"names":["VMCheckpointer","vm","lineNumber","lineId","variableNames","existing","insertAt","parent","variables","functions","name","fn","val","checkpoint","next","targetIndex","i","cp","key","index","low","high","result","mid","value","candidate"],"mappings":"AAuFO,IAAMA,CAAAA,CAAN,KAAqB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A,cAAA,CAAef,CAAAA,CAAiC,CAC/C,GAAI,IAAA,CAAK,WAAA,CAAY,MAAA,GAAW,CAAA,CAAG,OAEnC,IAAIG,CAAAA,CAAkC,IAAA,CAAK,WAAA,CAAY,IAAA,CAAK,WAAA,CAAY,MAAA,CAAS,CAAC,CAAA,CAClF,KAAOA,CAAAA,EAAY,CAClB,GAAI,MAAA,CAAO,SAAA,CAAU,cAAA,CAAe,IAAA,CAAKA,CAAAA,CAAW,SAAA,CAAWH,CAAI,CAAA,CAClE,OAAOG,CAAAA,CAAW,SAAA,CAAUH,CAAI,CAAA,CAEjCG,CAAAA,CAAaA,EAAW,OACzB,CAED,CAQA,KAAA,EAAc,CACb,IAAA,CAAK,WAAA,CAAc,GACpB,CAGA,IAAI,KAAA,EAAgB,CACnB,OAAO,IAAA,CAAK,WAAA,CAAY,MACzB,CAGA,IAAI,OAAA,EAAmB,CACtB,OAAO,IAAA,CAAK,WAAA,CAAY,MAAA,GAAW,CACpC,CAGA,IAAI,UAAA,EAAiB,CACpB,OAAO,IAAA,CAAK,EACb,CACD","file":"chunk-44BWHZ5V.js","sourcesContent":["import { Value } from \"@solve-js/vm/Value\";\nimport type { VM } from \"@solve-js/vm/OpRegistry\";\nimport type { UserFunctionDef } from \"@solve-js/parser/BytecodeBuilder\";\n\n// ── VMCheckpoint ────────────────────────────────────────────────────────\n\n/**\n * A point-in-time snapshot of VM variable state.\n *\n * Each checkpoint holds only the variables that CHANGED at its line, and\n * reaches the rest through its `parent` link. A lookup walks that chain until\n * it finds the name; a restore walks it from the root applying each link's own\n * bindings in turn, so a later line's value naturally overwrites an earlier\n * one's.\n *\n * ```text\n * Checkpoint 0 (root): {} // empty scope\n * Checkpoint 1 (:x=5): { x: 5 } parent → 0\n * Checkpoint 2 (:y=8): { y: 8 } parent → 1\n * Checkpoint 3 (:x=3): { x: 3 } parent → 2 // shadows x=5\n * ```\n *\n * To look up `x` at checkpoint 3: find own `x=3` → done.\n * To look up `y` at checkpoint 3: not own → walk parent to checkpoint 2 → `y=8`.\n * To look up `z` at checkpoint 3: not found anywhere → undefined.\n *\n * **Memory:** O(number of variable definitions) heap, independent of\n * document length. Typical Obsidian documents have < 100 variable defs,\n * so total checkpoint heap is < 10 KB.\n */\nexport interface VMCheckpoint {\n\t/** 1-based line number where this checkpoint was created. */\n\tlineNumber: number;\n\t/** Persistent line ID from DocumentModel. */\n\tlineId: number;\n\t/**\n\t * Variable name → Value at this checkpoint.\n\t * Only the variables set or updated at this line; the rest are reached\n\t * through {@link VMCheckpoint.parent}.\n\t */\n\tvariables: Record<string, Value>;\n\t/**\n\t * User-defined-function name → definition at this checkpoint. SEPARATE\n\t * from `variables` above (not prototypally chained the same way\n\t * `restoreTo()` replays every checkpoint in the chain in order, so a\n\t * later redefinition of the same function name naturally overwrites an\n\t * earlier one during replay, without needing its own prototype walk).\n\t *\n\t * Without this field, a function definition's checkpoint entry would be\n\t * SILENTLY LOST: `snapshot()` used to call `vm.getVar(name)` for every\n\t * written name, which returns `undefined` for a function name (function\n\t * defs live in `vm.userFunctions`, not the flat variable store), and a\n\t * `val !== undefined` guard silently skipped it. A scroll-triggered\n\t * `restoreTo()` would then reset the VM and replay only `variables`,\n\t * making a function defined above the new viewport vanish (calling it\n\t * would throw `UNDEFINED_FUNCTION`) even though the document still\n\t * shows its definition line as clean/cached.\n\t */\n\tfunctions: Record<string, UserFunctionDef>;\n\t/** Parent checkpoint (closer to document start), or null for root. */\n\tparent: VMCheckpoint | null;\n}\n\n// ── VMCheckpointer ──────────────────────────────────────────────────────\n\n/**\n * Manages VM state checkpoints for the three-tier evaluation strategy.\n *\n * **Checkpoint creation:** After a variable-definition line executes\n * (Tier 1 or Tier 3), `snapshot()` records the current values of the\n * written variables. The checkpoint is linked via prototypal inheritance\n * to the previous checkpoint, so only changed variables consume memory.\n *\n * **Checkpoint restoration:** Before evaluating a viewport whose start line\n * is not line 1, `restoreTo(lineNumber)` resets the VM and replays all\n * variable definitions up to and including that line. This avoids\n * re-evaluating the entire document from line 1 on every scroll.\n *\n * **Thread safety:** Checkpoints are created synchronously on the main\n * thread during evaluation. They are immutable after creation (Value is\n * an immutable type), so no synchronization is needed.\n *\n * **Integration with Phase 5.2e:** `setViewport()` will use `getNearestCheckpoint()`\n * to find the checkpoint just before the new viewport start, then call\n * `restoreTo()` to set up the VM before evaluating only the visible lines.\n * This is the key to O(visible lines) scrolling instead of O(document).\n */\nexport class VMCheckpointer {\n\t/** Ordered array of checkpoints (ascending lineNumber). */\n\tprivate checkpoints: VMCheckpoint[] = [];\n\t/** The VM instance whose variables are snapshotted/restored. */\n\tprivate vm: VM;\n\n\tconstructor(vm: VM) {\n\t\tthis.vm = vm;\n\t}\n\n\t// ── Snapshot ─────────────────────────────────────────────────────\n\n\t/**\n\t * Create a checkpoint at the current line, recording the VM values of\n\t * the specified variables.\n\t *\n\t * Records only what this line wrote; the rest is reached through the\n\t * parent link rather than copied.\n\t *\n\t * A line that is snapshotted again drops every checkpoint at or after it\n\t * first, so the list stays in document order and the new checkpoint\n\t * inherits from the line before it rather than from one after it. See the\n\t * body for what went wrong without that.\n\t *\n\t * @param lineNumber 1-based line position.\n\t * @param lineId Persistent line ID from DocumentModel.\n\t * @param variableNames Names of variables that were written at this line.\n\t * @returns The new checkpoint, or null if no variable names provided.\n\t */\n\tsnapshot(\n\t\tlineNumber: number,\n\t\tlineId: number,\n\t\tvariableNames: string[]\n\t): VMCheckpoint | null {\n\t\tif (variableNames.length === 0) return null;\n\n\t\t// This line's own entry is replaced, and nothing else is touched.\n\t\t//\n\t\t// The list is a sequence of document positions and `restoreTo` reads it\n\t\t// as one, so a re-run must not append after entries that come later in\n\t\t// the document: editing line 2 of a document whose lines 1, 2 and 3 each\n\t\t// define something left the list as [1, 2, 3, 2], and a restore to line\n\t\t// 2 then found the stale entry.\n\t\t//\n\t\t// Replacing rather than truncating is the part that took a second go.\n\t\t// Dropping every entry at or after the line is sound only for a pass\n\t\t// running from line 1, which re-takes them as it continues. A pass\n\t\t// limited to a viewport does not: it re-snapshots the top of the\n\t\t// document and never reaches the definitions below its end line, so the\n\t\t// chain lost them, and `restoreTo` then RESET the VM and replayed a\n\t\t// prefix that no longer mentioned them. A line further down reading one\n\t\t// answered `Undefined variable` where it had answered a number. Absent\n\t\t// is worse than stale here: a stale entry is what the document is\n\t\t// currently showing anyway, and the pass corrects it when it reaches\n\t\t// that line.\n\t\tconst existing = this.indexOfCheckpointAt(lineNumber);\n\t\tconst insertAt = existing >= 0 ? existing : this.insertionIndexFor(lineNumber);\n\t\tconst parent = insertAt > 0 ? this.checkpoints[insertAt - 1] : null;\n\n\t\t// Each checkpoint holds only what its line wrote, and reaches the rest\n\t\t// through `parent`. It used to reach it through the prototype chain\n\t\t// instead, which held the same entries and cost the same memory, and\n\t\t// made the chain as deep as the document has definitions: a null\n\t\t// prototype is a flat object, and one per definition is a chain two\n\t\t// thousand deep on a document of two thousand definitions. Creating and\n\t\t// reading those took a pass over such a document from 6.0 ms to 23.1 ms.\n\t\t//\n\t\t// Nothing needed the inheritance. `restoreTo` walks `parent` and applies\n\t\t// each checkpoint's OWN keys, which is the same set either way, and the\n\t\t// one reader that did walk the prototype now walks `parent` too.\n\t\t//\n\t\t// Null-prototyped rather than `{}`, so a variable named `constructor` or\n\t\t// `toString` is a key like any other.\n\t\tconst variables: Record<string, Value> = Object.create(null) as Record<string, Value>;\n\t\tconst functions: Record<string, UserFunctionDef> = Object.create(null) as Record<string, UserFunctionDef>;\n\n\t\t// Record current VM values for the written names, routing each into\n\t\t// the right bag (a name is either a variable or a user-defined\n\t\t// function, never both; see VMCheckpoint.functions's doc comment for\n\t\t// why this dispatch is required, not optional).\n\t\tfor (const name of variableNames) {\n\t\t\tif (this.vm.hasUserFunction(name)) {\n\t\t\t\tconst fn = this.vm.getUserFunction(name);\n\t\t\t\tif (fn) functions[name] = fn;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst val = this.vm.getVar(name);\n\t\t\tif (val !== undefined) {\n\t\t\t\tvariables[name] = val;\n\t\t\t}\n\t\t}\n\n\t\tconst checkpoint: VMCheckpoint = {\n\t\t\tlineNumber,\n\t\t\tlineId,\n\t\t\tvariables,\n\t\t\tfunctions,\n\t\t\tparent,\n\t\t};\n\t\tif (existing >= 0) this.checkpoints[existing] = checkpoint;\n\t\telse this.checkpoints.splice(insertAt, 0, checkpoint);\n\t\t// The entry after this one now follows a different object.\n\t\tconst next = this.checkpoints[insertAt + 1];\n\t\tif (next !== undefined) next.parent = checkpoint;\n\t\treturn checkpoint;\n\t}\n\n\t// ── Restore ──────────────────────────────────────────────────────\n\n\t/**\n\t * Restore the VM to the state at or just after the given line number.\n\t *\n\t * Finds the nearest checkpoint whose `lineNumber <= targetLineNumber`,\n\t * then replays all variable definitions from root → that checkpoint\n\t * into the VM via `setVar()`. The VM's stack is also reset.\n\t *\n\t * If no checkpoint exists at or before the target line, the VM is\n\t * fully reset (empty scope, empty stack).\n\t *\n\t * **Performance:** O(total variable definitions before the line), since\n\t * each checkpoint in the chain contributes only the names its own line\n\t * wrote.\n\t *\n\t * @param lineNumber Target 1-based line number. The VM will have the\n\t * state that existed AFTER evaluating lines up to `lineNumber`.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\t// The chain from the root to the target IS the array up to that index.\n\t\t//\n\t\t// Every checkpoint is created with the one before it in the array as its\n\t\t// parent (see {@link snapshot}), and the array is kept in document\n\t\t// order, so walking parent links would visit exactly these entries in\n\t\t// exactly this order. Reading the array instead of the links costs no\n\t\t// allocation, and it was the links that made this quadratic: the walk\n\t\t// runs target-to-root, so the chain was assembled by `unshift`ing each\n\t\t// entry onto the front, which shifts every entry already there. A\n\t\t// document with two thousand definitions did four million shifts per\n\t\t// restore, and a scroll restores.\n\t\t//\n\t\t// `CheckpointsStayInDocumentOrder.spec.ts` asserts the invariant this\n\t\t// relies on, so a change that broke it would fail there rather than\n\t\t// quietly restoring the wrong state here.\n\t\tconst targetIndex = this.nearestCheckpointIndex(lineNumber);\n\n\t\tthis.vm.reset();\n\t\tfor (let i = 0; i <= targetIndex; i++) {\n\t\t\tconst cp = this.checkpoints[i];\n\t\t\t// Only the names this checkpoint's own line wrote; the ones before\n\t\t\t// it are applied by their own entries earlier in this same walk.\n\t\t\tfor (const key of Object.keys(cp.variables)) {\n\t\t\t\tthis.vm.setVar(key, cp.variables[key]);\n\t\t\t}\n\t\t\t// Replay function definitions the same way, a later checkpoint's\n\t\t\t// redefinition of the same name naturally overwrites an earlier\n\t\t\t// one since the walk runs root-to-target.\n\t\t\tfor (const key of Object.keys(cp.functions)) {\n\t\t\t\tconst fn = cp.functions[key];\n\t\t\t\tthis.vm.defineUserFunction(fn.name, fn.params, fn.program);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The index of the checkpoint recorded exactly at `lineNumber`, or -1. */\n\tprivate indexOfCheckpointAt(lineNumber: number): number {\n\t\tconst index = this.nearestCheckpointIndex(lineNumber);\n\t\treturn index >= 0 && this.checkpoints[index].lineNumber === lineNumber ? index : -1;\n\t}\n\n\t/** Where a checkpoint for `lineNumber` belongs, keeping the list in order. */\n\tprivate insertionIndexFor(lineNumber: number): number {\n\t\treturn this.nearestCheckpointIndex(lineNumber) + 1;\n\t}\n\n\t/**\n\t * The index of the last checkpoint at or before `lineNumber`, or -1.\n\t *\n\t * A binary search rather than a scan. The array is in document order, and\n\t * this is asked once per scroll and once per async batch, on a document\n\t * that can hold a checkpoint per definition.\n\t */\n\tprivate nearestCheckpointIndex(lineNumber: number): number {\n\t\tlet low = 0;\n\t\tlet high = this.checkpoints.length - 1;\n\t\tlet result = -1;\n\t\twhile (low <= high) {\n\t\t\tconst mid = (low + high) >> 1;\n\t\t\tif (this.checkpoints[mid].lineNumber <= lineNumber) {\n\t\t\t\tresult = mid;\n\t\t\t\tlow = mid + 1;\n\t\t\t} else {\n\t\t\t\thigh = mid - 1;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Record what `lineNumber` has just written, without disturbing the chain\n\t * after it.\n\t *\n\t * {@link snapshot} drops every checkpoint at or after the line, which is\n\t * right for a pass running forward in document order: it re-takes them as it\n\t * goes. A caller re-running a few lines out of a document does not, and\n\t * dropping the entries for lines it will never visit would lose the very\n\t * bindings it is sweeping through them to collect. So this overwrites in\n\t * place instead.\n\t *\n\t * Safe against the prototype chain, because it replaces only the\n\t * checkpoint's OWN bindings: a later checkpoint that also writes the name\n\t * holds its own copy and goes on shadowing this one.\n\t *\n\t * @param lineNumber 1-based line whose recorded bindings are refreshed.\n\t * @param variableNames The names it wrote.\n\t * @returns Whether a checkpoint existed at that line to update.\n\t */\n\tupdateCheckpointAt(lineNumber: number, variableNames: string[]): boolean {\n\t\tconst checkpoint = this.getCheckpointAt(lineNumber);\n\t\tif (!checkpoint) return false;\n\t\tfor (const name of variableNames) {\n\t\t\tif (this.vm.hasUserFunction(name)) {\n\t\t\t\tconst fn = this.vm.getUserFunction(name);\n\t\t\t\tif (fn) checkpoint.functions[name] = fn;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst value = this.vm.getVar(name);\n\t\t\tif (value !== undefined) checkpoint.variables[name] = value;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Apply the bindings recorded AT `lineNumber`, leaving the rest of the VM\n\t * alone.\n\t *\n\t * {@link restoreTo} rebuilds the whole prefix, which costs the chain every\n\t * time it is called. A caller moving forward through the document already\n\t * holds the prefix up to the line before, and needs only what this line\n\t * added: restoring once and then applying each line in turn as it is passed\n\t * costs the chain once rather than once per line.\n\t *\n\t * @param lineNumber 1-based line whose own bindings are applied.\n\t * @returns Whether a checkpoint existed at that line.\n\t */\n\tapplyCheckpointAt(lineNumber: number): boolean {\n\t\tconst checkpoint = this.getCheckpointAt(lineNumber);\n\t\tif (!checkpoint) return false;\n\t\tfor (const key of Object.keys(checkpoint.variables)) {\n\t\t\tthis.vm.setVar(key, checkpoint.variables[key]);\n\t\t}\n\t\tfor (const key of Object.keys(checkpoint.functions)) {\n\t\t\tconst fn = checkpoint.functions[key];\n\t\t\tthis.vm.defineUserFunction(fn.name, fn.params, fn.program);\n\t\t}\n\t\treturn true;\n\t}\n\n\t// ── Queries ──────────────────────────────────────────────────────\n\n\t/**\n\t * Find the nearest checkpoint at or before the given line number.\n\t *\n\t * Uses linear scan (checkpoints are sorted by lineNumber and the list\n\t * is short, typically < 20 for Obsidian documents). Can be upgraded\n\t * to binary search if needed for documents with 1000+ variable defs.\n\t *\n\t * @returns The nearest checkpoint, or null if none exists before the line.\n\t */\n\tgetNearestCheckpoint(lineNumber: number): VMCheckpoint | null {\n\t\tconst index = this.nearestCheckpointIndex(lineNumber);\n\t\treturn index < 0 ? null : this.checkpoints[index];\n\t}\n\n\t/**\n\t * Get a specific checkpoint by its line number.\n\t * @returns The checkpoint, or undefined if not found.\n\t */\n\tgetCheckpointAt(lineNumber: number): VMCheckpoint | undefined {\n\t\t// Searched, not scanned: the async sweep asks this once for every line\n\t\t// it walks past, and a scan would make that walk quadratic.\n\t\tconst index = this.nearestCheckpointIndex(lineNumber);\n\t\tif (index < 0) return undefined;\n\t\tconst candidate = this.checkpoints[index];\n\t\treturn candidate.lineNumber === lineNumber ? candidate : undefined;\n\t}\n\n\t/**\n\t * Get the entire checkpoint chain from root to the last checkpoint.\n\t * Useful for debugging and serialization.\n\t */\n\tgetAllCheckpoints(): readonly VMCheckpoint[] {\n\t\treturn this.checkpoints;\n\t}\n\n\t/**\n\t * Look up a variable's value through the checkpoint chain.\n\t *\n\t * Walks the prototype chain starting from the most recent checkpoint,\n\t * looking for the variable name as an own property. This is O(depth)\n\t * where depth is the number of checkpoints since the variable was\n\t * last set.\n\t *\n\t * **Note:** This queries the checkpointer's snapshot, not the VM.\n\t * The VM may have been modified since the last snapshot (e.g., by\n\t * Tier 2 execution of non-variable-def lines that don't create checkpoints).\n\t *\n\t * @returns The Value, or undefined if the variable was never set.\n\t */\n\tlookupVariable(name: string): Value | undefined {\n\t\tif (this.checkpoints.length === 0) return undefined;\n\n\t\tlet checkpoint: VMCheckpoint | null = this.checkpoints[this.checkpoints.length - 1];\n\t\twhile (checkpoint) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(checkpoint.variables, name)) {\n\t\t\t\treturn checkpoint.variables[name];\n\t\t\t}\n\t\t\tcheckpoint = checkpoint.parent;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// ── Lifecycle ────────────────────────────────────────────────────\n\n\t/**\n\t * Clear all checkpoints. The underlying VM is NOT reset, call\n\t * `vm.reset()` separately if needed.\n\t */\n\tclear(): void {\n\t\tthis.checkpoints = [];\n\t}\n\n\t/** Number of checkpoints stored. */\n\tget count(): number {\n\t\treturn this.checkpoints.length;\n\t}\n\n\t/** Returns true if no checkpoints have been created. */\n\tget isEmpty(): boolean {\n\t\treturn this.checkpoints.length === 0;\n\t}\n\n\t/** The associated VM instance. */\n\tget vmInstance(): VM {\n\t\treturn this.vm;\n\t}\n}\n"]}
|