Add makeReadOnly codegen into the compiler
Mofei Zhang committed
Oct 3, 2022 at 14:37 UTC
4e0639c2dceef3feca273cf0dadfd4f045826f77
4 files changed
+25
compiler/forget/src/BackEnd/JS.ts
+13
@@ -188,6 +188,19 @@ export class Func {
188
]);
189
}
190
191
+ // Generate calls to utility function that freezes immut objects
192
+ emitMakeReadOnly(val: IR.BindingVal) {
193
+ if (this.context.opts.flags.addFreeze === true) {
194
+ this.code.push(
195
+ t.expressionStatement(
196
+ t.callExpression(t.identifier("useMemoCache.makeReadOnly"), [
197
+ val.binding.identifier,
198
+ ])
199
+ )
200
+ );
201
+ }
202
+ }
203
+
204
/**
205
* Generate code materializing reactions
206
* @returns
compiler/forget/src/BackEnd/JSGen.ts
+5
@@ -85,6 +85,8 @@ export function runFunc(
85
*/
86
function genPrologue(): void {
87
for (const param of irFunc.params) {
88
+ // params are immut
89
+ jsFunc.emitMakeReadOnly(param);
90
if (IR.isReactiveVal(param)) {
91
jsFunc.emitReactiveVal(param);
92
}
@@ -102,6 +104,9 @@ export function runFunc(
104
jsFunc.emit(instr.ast.node);
105
106
for (const decl of instr.ir.decls) {
107
+ if (decl.immutable) {
108
+ jsFunc.emitMakeReadOnly(decl);
109
+ }
110
if (IR.isReactiveVal(decl)) {
111
jsFunc.emitReactiveVal(decl);
112
}
compiler/forget/src/CompilerFlags.ts
+6
@@ -81,6 +81,10 @@ export type CompilerFlags = {
81
* can remove this flag.
82
*/
83
guardThrows: boolean;
84
+ /**
85
+ * Experimental runtime logging to collect data
86
+ */
87
+ addFreeze: boolean;
88
};
89
90
export function createCompilerFlags(): CompilerFlags {
@@ -95,6 +99,7 @@ export function createCompilerFlags(): CompilerFlags {
99
guardReads: false,
100
guardHooks: false,
101
guardThrows: false,
102
+ addFreeze: false,
103
};
104
}
105
@@ -115,6 +120,7 @@ export function parseCompilerFlags(
120
case "guardReads":
121
case "guardHooks":
122
case "guardThrows":
123
+ case "addFreeze":
124
if (typeof value !== "boolean") {
125
throw `Expected boolean for flag '${key}': ${value}`;
126
}
compiler/forget/src/__tests__/CompilerOptions-test.ts
+1
@@ -49,6 +49,7 @@ describe("CompilerOptions", () => {
49
const fullInput = {
50
outputKinds: [OutputKind.JS, OutputKind.LIR],
51
flags: {
52
+ addFreeze: true,
53
condCache: true,
54
guardReads: true,
55
guardHooks: true,