we have persistence. persisting all store values' ASTs to localStorage
parent
1029b1671f
commit
8c3237e0db
@ -0,0 +1,29 @@
|
|||||||
|
import type { AST } from './ast'
|
||||||
|
import type { Store } from './store'
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'cg_store';
|
||||||
|
|
||||||
|
export function saveStore(store: Store) {
|
||||||
|
const data: Record<string, any> = {};
|
||||||
|
for (const [name, entry] of store) {
|
||||||
|
data[name] = {
|
||||||
|
body: entry.body,
|
||||||
|
source: 'file'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadStore(): Record<string, { body: AST, source: string }> | null {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(STORAGE_KEY);
|
||||||
|
if (!raw) return null;
|
||||||
|
return JSON.parse(raw);
|
||||||
|
} catch(e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearStore() {
|
||||||
|
localStorage.remove(STORAGE_KEY);
|
||||||
|
}
|
||||||
@ -0,0 +1,45 @@
|
|||||||
|
import type { AST } from './ast'
|
||||||
|
import type { Value } from './types'
|
||||||
|
|
||||||
|
export function valueToAST(value: Value): AST {
|
||||||
|
switch (value.kind) {
|
||||||
|
case 'int':
|
||||||
|
case 'float':
|
||||||
|
case 'string':
|
||||||
|
return { kind: 'literal', value };
|
||||||
|
|
||||||
|
case 'list':
|
||||||
|
return {
|
||||||
|
kind: 'list',
|
||||||
|
elements: value.elements.map(valueToAST)
|
||||||
|
};
|
||||||
|
|
||||||
|
case 'record':
|
||||||
|
const fields: { [key: string]: AST } = {};
|
||||||
|
for (const [k, v] of Object.entries(value.fields)) {
|
||||||
|
if (value.fieldMeta && value.fieldMeta?.[k]?.dependencies?.size > 0) {
|
||||||
|
fields[k] = value.fieldMeta[k].body;
|
||||||
|
} else {
|
||||||
|
fields[k] = valueToAST(v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { kind: 'record', fields };
|
||||||
|
|
||||||
|
case 'constructor':
|
||||||
|
return {
|
||||||
|
kind: 'constructor',
|
||||||
|
name: value.name
|
||||||
|
};
|
||||||
|
|
||||||
|
case 'closure':
|
||||||
|
return {
|
||||||
|
kind: 'lambda',
|
||||||
|
params: value.params,
|
||||||
|
body: value.body
|
||||||
|
};
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new Error(`Cannot convert ${(value as any).kind} to AST`);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue