Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate a monomorphic version of .createReadOnly and .instantiate for each class model #74

Merged
merged 1 commit into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 5 additions & 18 deletions src/class-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,25 +252,7 @@ export function register<Instance, Klass extends { new (...args: any[]): Instanc
klass.volatiles = mstVolatiles;

// conform to the API that the other MQT types expect for creating instances
klass.instantiate = (snapshot, context, parent) => new klass(snapshot, context, parent);
(klass as any).is = (value: any) => value instanceof klass || klass.mstType.is(value);
klass.create = (snapshot, env) => klass.mstType.create(snapshot, env);
klass.createReadOnly = (snapshot, env) => {
const context: InstantiateContext = {
referenceCache: new Map(),
referencesToResolve: [],
env,
};

const instance = new klass(snapshot, context, null) as any;

for (const resolver of context.referencesToResolve) {
resolver();
}

return instance;
};

klass.schemaHash = memoize(async () => {
const props = Object.entries(klass.properties as Record<string, IAnyType>).sort(([key1], [key2]) => key1.localeCompare(key2));
const propHashes = await Promise.all(props.map(async ([key, prop]) => `${key}:${await prop.schemaHash()}`));
Expand All @@ -288,7 +270,12 @@ export function register<Instance, Klass extends { new (...args: any[]): Instanc
(klass as any).mstType = (klass as any).mstType.volatile((self: any) => initializeVolatiles({}, self, mstVolatiles));
}

// define the class constructor and the following hot path functions dynamically
// .createReadOnly
// .is
// .instantiate
klass = buildFastInstantiator(klass);

(klass as any)[$registered] = true;

return klass as any;
Expand Down
49 changes: 42 additions & 7 deletions src/fast-instantiator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,40 @@ class InstantiatorBuilder<T extends IClassModelType<Record<string, IAnyType>, an
`);
}

let className = this.model.name;
if (!className || className.trim().length == 0) {
className = "AnonymousModel";
}

const defineClassStatement = `
return class ${this.model.name} extends model {
return class ${className} extends model {
[$memos] = null;
[$memoizedKeys] = null;

static createReadOnly = (snapshot, env) => {
const context = {
referenceCache: new Map(),
referencesToResolve: [],
env,
};

const instance = new ${className}(snapshot, context, null);

for (const resolver of context.referencesToResolve) {
resolver();
}

return instance;
};

static instantiate(snapshot, context, parent) {
return new ${className}(snapshot, context, parent);
};

static is(value) {
return (value instanceof ${className}) || ${className}.mstType.is(value);
};

constructor(
snapshot,
context,
Expand Down Expand Up @@ -119,13 +148,19 @@ class InstantiatorBuilder<T extends IClassModelType<Record<string, IAnyType>, an

// console.log(`function for ${this.model.name}`, "\n\n\n", aliasFuncBody, "\n\n\n");

// build a function that closes over a bunch of aliased expressions
// evaluate the inner function source code in this closure to return the function
// eslint-disable-next-line @typescript-eslint/no-implied-eval
const aliasFunc = new Function("model", "imports", aliasFuncBody);
try {
// build a function that closes over a bunch of aliased expressions
// evaluate the inner function source code in this closure to return the function
// eslint-disable-next-line @typescript-eslint/no-implied-eval
const aliasFunc = new Function("model", "imports", aliasFuncBody);

// evaluate aliases and get created inner function
return aliasFunc(this.model, { $identifier, $env, $parent, $memos, $memoizedKeys, $readOnly, $type, QuickMap, QuickArray }) as T;
// evaluate aliases and get created inner function
return aliasFunc(this.model, { $identifier, $env, $parent, $memos, $memoizedKeys, $readOnly, $type, QuickMap, QuickArray }) as T;
} catch (e) {
console.warn("failed to build fast instantiator for", this.model.name);
console.warn("dynamic source code:", aliasFuncBody);
throw e;
}
}

private expressionForDirectlyAssignableType(key: string, type: DirectlyAssignableType) {
Expand Down