diff --git a/benchmark/package.json b/benchmark/package.json index 3fcb88ae2e..fb7174da43 100644 --- a/benchmark/package.json +++ b/benchmark/package.json @@ -1,6 +1,6 @@ { "name": "glimmer-benchmark", - "version": "0.59.0", + "version": "0.60.0", "private": true, "dependencies": { "@glimmer/benchmark-env": "*", diff --git a/lib/local-linker/package.json b/lib/local-linker/package.json index e1b085174f..5bd8f0849a 100644 --- a/lib/local-linker/package.json +++ b/lib/local-linker/package.json @@ -1,6 +1,6 @@ { "name": "local-linker", - "version": "0.59.0", + "version": "0.60.0", "private": true, "keywords": [ "ember-addon" diff --git a/packages/@glimmer/benchmark-env/package.json b/packages/@glimmer/benchmark-env/package.json index 374dc345a8..bf49d74826 100644 --- a/packages/@glimmer/benchmark-env/package.json +++ b/packages/@glimmer/benchmark-env/package.json @@ -5,6 +5,7 @@ "repository": "https://github.com/glimmerjs/glimmer-vm/tree/master/packages/@glimmer/benchmark-env", "dependencies": { "@glimmer/global-context": "^0.60.0", + "@glimmer/program": "^0.60.0", "@glimmer/reference": "^0.60.0", "@glimmer/runtime": "^0.60.0", "@glimmer/validator": "^0.60.0", diff --git a/packages/@glimmer/benchmark-env/src/benchmark/create-registry.ts b/packages/@glimmer/benchmark-env/src/benchmark/create-registry.ts index f6510c1d73..b004129ee8 100644 --- a/packages/@glimmer/benchmark-env/src/benchmark/create-registry.ts +++ b/packages/@glimmer/benchmark-env/src/benchmark/create-registry.ts @@ -8,8 +8,10 @@ import { ModifierManager, CompilableProgram, Dict, + PartialDefinition, } from '@glimmer/interfaces'; -import { JitContext } from '@glimmer/opcode-compiler'; +import { syntaxCompilationContext } from '@glimmer/opcode-compiler'; +import { artifacts } from '@glimmer/program'; import { SimpleComponentManager } from '@glimmer/runtime'; import { SimpleElement } from '@simple-dom/interface'; @@ -128,10 +130,13 @@ export default function createRegistry(): Registry { ); }, render: (entry, args, element, isIteractive) => { - const context = JitContext({ - lookupHelper: (name) => helpers.get(name)?.handle, - lookupModifier: (name) => modifiers.get(name)?.handle, - lookupComponent: (name) => components.get(name), + const sharedArtifacts = artifacts(); + const context = syntaxCompilationContext(sharedArtifacts, { + lookupHelper: (name) => helpers.get(name)?.handle ?? null, + lookupModifier: (name) => modifiers.get(name)?.handle ?? null, + lookupComponent: (name) => components.get(name) ?? null, + lookupPartial: () => null, + resolve: () => null, }); const component = components.get(entry); if (!component) { @@ -139,9 +144,19 @@ export default function createRegistry(): Registry { } return renderBenchmark( + sharedArtifacts, context, { - resolve: (handle) => values[handle].definition, + resolve( + handle: number + ): U { + return values[handle].definition as U; + }, + lookupComponent: () => null, + lookupPartial: () => null, + compilable() { + throw new Error('not implemented'); + }, }, component.definition, component.compilable, diff --git a/packages/@glimmer/benchmark-env/src/benchmark/render-benchmark.ts b/packages/@glimmer/benchmark-env/src/benchmark/render-benchmark.ts index 5db2d41166..7e4ddeb227 100644 --- a/packages/@glimmer/benchmark-env/src/benchmark/render-benchmark.ts +++ b/packages/@glimmer/benchmark-env/src/benchmark/render-benchmark.ts @@ -1,26 +1,23 @@ import { SimpleElement } from '@simple-dom/interface'; import { Dict, - RuntimeResolverDelegate, + RuntimeResolver, + SyntaxCompilationContext, ComponentDefinition, CompilableProgram, + RuntimeArtifacts, } from '@glimmer/interfaces'; import { createConstRef, Reference, childRefFor } from '@glimmer/reference'; -import { - NewElementBuilder, - JitRuntime, - JitSyntaxCompilationContext, - renderSync, - renderJitComponent, -} from '@glimmer/runtime'; +import { NewElementBuilder, runtimeContext, renderComponent, renderSync } from '@glimmer/runtime'; import createEnvDelegate, { registerResult } from './create-env-delegate'; import { measureRender } from './util'; import { UpdateBenchmark } from '../interfaces'; export default async function renderBenchmark( - context: JitSyntaxCompilationContext, - runtimeResolverDelegate: RuntimeResolverDelegate, + artifacts: RuntimeArtifacts, + context: SyntaxCompilationContext, + runtimeResolver: RuntimeResolver, component: ComponentDefinition, layout: CompilableProgram, root: Dict, @@ -32,13 +29,13 @@ export default async function renderBenchmark( await measureRender('render', 'renderStart', 'renderEnd', () => { const document = element.ownerDocument; const envDelegate = createEnvDelegate(isInteractive); - const runtime = JitRuntime( + const runtime = runtimeContext( { document, }, envDelegate, - context, - runtimeResolverDelegate + artifacts, + runtimeResolver ); const env = runtime.env; const cursor = { element, nextSibling: null }; @@ -52,7 +49,7 @@ export default async function renderBenchmark( const result = renderSync( env, - renderJitComponent(runtime, treeBuilder, context, component, layout, args) + renderComponent(runtime, treeBuilder, context, component, layout, args) ); registerResult(result, () => { diff --git a/packages/@glimmer/benchmark-env/src/benchmark/util.ts b/packages/@glimmer/benchmark-env/src/benchmark/util.ts index cbac1f386a..84ef430451 100644 --- a/packages/@glimmer/benchmark-env/src/benchmark/util.ts +++ b/packages/@glimmer/benchmark-env/src/benchmark/util.ts @@ -5,7 +5,7 @@ import { } from '@glimmer/interfaces'; import { unwrapTemplate, unwrapHandle } from '@glimmer/util'; import { templateFactory } from '@glimmer/opcode-compiler'; -import { JitSyntaxCompilationContext } from '@glimmer/interfaces'; +import { SyntaxCompilationContext } from '@glimmer/interfaces'; export function createProgram( template: SerializedTemplateWithLazyBlock @@ -13,7 +13,7 @@ export function createProgram( return unwrapTemplate(templateFactory(template).create()).asLayout(); } -export function compileEntry(entry: CompileTimeComponent, context: JitSyntaxCompilationContext) { +export function compileEntry(entry: CompileTimeComponent, context: SyntaxCompilationContext) { return unwrapHandle(entry.compilable!.compile(context)); } diff --git a/packages/@glimmer/bundle-compiler/.npmignore b/packages/@glimmer/bundle-compiler/.npmignore deleted file mode 100644 index 65e3ba2eda..0000000000 --- a/packages/@glimmer/bundle-compiler/.npmignore +++ /dev/null @@ -1 +0,0 @@ -test/ diff --git a/packages/@glimmer/bundle-compiler/index.ts b/packages/@glimmer/bundle-compiler/index.ts deleted file mode 100644 index bbdb5885ba..0000000000 --- a/packages/@glimmer/bundle-compiler/index.ts +++ /dev/null @@ -1,14 +0,0 @@ -export { - default as BundleCompiler, - BundleCompilerOptions, - BundleCompileOptions, - PartialTemplateLocator, - BundleCompilationResult, - normalizeLocator, -} from './lib/bundle-compiler'; - -export { default as CompilerDelegate } from './lib/delegate'; -export { default as BundleCompilerLookup } from './lib/lookup'; -export { default as ModuleLocatorMap } from './lib/module-locator-map'; -export { default as DebugConstants } from './lib/debug-constants'; -export { default as ExternalModuleTable } from './lib/external-module-table'; diff --git a/packages/@glimmer/bundle-compiler/lib/bundle-compiler.ts b/packages/@glimmer/bundle-compiler/lib/bundle-compiler.ts deleted file mode 100644 index 5e81fad4b0..0000000000 --- a/packages/@glimmer/bundle-compiler/lib/bundle-compiler.ts +++ /dev/null @@ -1,267 +0,0 @@ -import { ASTPluginBuilder, preprocess } from '@glimmer/syntax'; -import { TemplateCompiler } from '@glimmer/compiler'; -import { expect } from '@glimmer/util'; -import { - ProgramSymbolTable, - ModuleLocator, - CompilableProgram, - CompilableTemplate, - SerializedHeap, - ConstantPool, - SerializedTemplateBlock, - CompileMode, - WholeProgramCompilationContext, - STDLib, - CompileTimeHeap, - SyntaxCompilationContext, - CompileTimeConstants, - Macros, - Option, - EncoderError, - HandleResult, -} from '@glimmer/interfaces'; -import { compileStd, compilable, MacrosImpl } from '@glimmer/opcode-compiler'; - -import ModuleLocatorMap from './module-locator-map'; -import DebugConstants from './debug-constants'; -import ExternalModuleTable from './external-module-table'; -import BundleCompilerDelegate from './delegate'; -import BundleCompilerLookup from './lookup'; -import { HeapImpl } from '@glimmer/program'; -import { syntaxCompilationContext } from '@glimmer/opcode-compiler'; - -export interface BundleCompileOptions { - plugins: ASTPluginBuilder[]; -} - -export interface BundleCompilerOptions { - macros?: Macros; - constants?: CompileTimeConstants; - plugins?: ASTPluginBuilder[]; -} - -/** - * ModuleLocatorepresents the results of a bundle compilation. - */ -export interface BundleCompilationResult { - /** - * The VM handle corresponding to the program entry point. This is the heap - * offset where execution will begin when the program starts. - */ - main: number; - - /** - * The final result of program compilation, including the binary bytecode. - */ - heap: SerializedHeap; - - /** - * A JSON-ready data structure containing constant values generated during - * compilation. - */ - pool: ConstantPool; - - /** - * A table mapping modules locators to their associated handles, and vice - * versa. - */ - table: ExternalModuleTable; - - /** - * A mapping of module locators to compiled template symbol tables. - */ - symbolTables: ModuleLocatorMap; -} - -export interface PartialTemplateLocator extends ModuleLocator { - meta: M; - kind?: 'template'; -} - -// to make --declaration happy -export { CompilableTemplate }; - -export class BundleCompilerCompilationContext implements WholeProgramCompilationContext { - readonly compilableTemplates = new ModuleLocatorMap(); - readonly compiledBlocks = new ModuleLocatorMap(); - readonly meta = new ModuleLocatorMap(); - - // implement WholeProgramCompilationContext - readonly constants: CompileTimeConstants; - readonly resolverDelegate: BundleCompilerLookup = new BundleCompilerLookup( - this.delegate, - this.compilableTemplates, - this.meta - ); - readonly heap: CompileTimeHeap = new HeapImpl(); - readonly mode = CompileMode.aot; - readonly stdlib: STDLib; - - constructor( - readonly delegate: BundleCompilerDelegate, - options: BundleCompilerOptions - ) { - if (options.constants) { - this.constants = options.constants; - } else { - this.constants = new DebugConstants(); - } - - this.stdlib = compileStd(this); - } -} - -/** - * The BundleCompiler is used to compile all of the component templates in a - * Glimmer program into binary bytecode. - * - * First, you must call `add()` to push each component's template into the - * bundle. Once every template in the program has been registered, the last step - * is to call `compile()`, which begins eager compilation of the entire program - * into the heap. - * - * At the end of compilation, the heap plus additional metadata is produced, - * which is suitable for serialization into bytecode and JavaScript assets that - * can be loaded and run in the browser. - */ -export default class BundleCompiler { - protected macros: Macros; - protected plugins: ASTPluginBuilder[]; - - private context: BundleCompilerCompilationContext; - - constructor( - delegate: BundleCompilerDelegate, - options: BundleCompilerOptions = {} - ) { - this.context = new BundleCompilerCompilationContext(delegate, options); - - this.macros = options.macros || new MacrosImpl(); - this.plugins = options.plugins || []; - } - - get syntaxContext(): SyntaxCompilationContext { - return { - program: this.context, - macros: this.macros, - }; - } - - /** - * Adds the template source code for a component to the bundle. - */ - addTemplateSource(_locator: ModuleLocator, templateSource: string): SerializedTemplateBlock { - let locator = normalizeLocator(_locator); - - let block = this.preprocess(locator, templateSource); - this.context.compiledBlocks.set(locator, block); - - let layout = { - block, - referrer: locator, - asPartial: false, - }; - - let template = compilable(layout); - - this.addCompilableTemplate(locator, template); - - return block; - } - - /** - * Adds a custom CompilableTemplate instance to the bundle. - */ - addCompilableTemplate(locator: ModuleLocator, template: CompilableProgram): void { - this.context.meta.set(locator, locator); - this.context.compilableTemplates.set(locator, template); - } - - getTemplate(locator: ModuleLocator): Option { - return this.context.compilableTemplates.get(locator) || null; - } - - /** - * Compiles all of the templates added to the bundle. Once compilation - * completes, the results of the compilation are returned, which includes - * everything needed to serialize the Glimmer program into binary bytecode and - * data segment. - */ - compile(): BundleCompilationResult { - let symbolTables = new ModuleLocatorMap(); - - this.context.compilableTemplates.forEach((template, locator) => { - this.compileTemplate(locator); - symbolTables.set(locator, template.symbolTable); - }); - - return { - main: this.context.stdlib.main, - heap: this.context.heap.capture(this.context.stdlib) as SerializedHeap, - pool: this.context.constants.toPool(), - table: this.compilerModuleLocatorResolver().getTable(), - symbolTables, - }; - } - - preprocess(locator: ModuleLocator, input: string): SerializedTemplateBlock { - let options = { meta: locator, plugins: { ast: this.plugins } }; - let ast = preprocess(input, options); - let template = TemplateCompiler.compile(ast, input); - return template.toJSON(); - } - - compilerModuleLocatorResolver(): BundleCompilerLookup { - return this.context.resolverDelegate; - } - - /** - * Performs the actual compilation of the template identified by the passed - * locator into the Program. ModuleLocatoreturns the VM handle for the compiled template. - */ - protected compileTemplate(locator: ModuleLocator): HandleResult { - // If this locator already has an assigned VM handle, it means we've already - // compiled it. We need to skip compiling it again and just return the same - // VM handle. - let vmHandle: - | number - | { handle: number; errors: EncoderError[] } - | undefined = this.compilerModuleLocatorResolver().getHandleByLocator(locator); - if (vmHandle !== undefined) return vmHandle; - - // It's an error to try to compile a template that wasn't first added to the - // bundle via the add() or addCompilableTemplate() methods. - let compilableTemplate = expect( - this.context.compilableTemplates.get(locator), - `Can't compile a template that wasn't already added to the bundle (${locator.name} @ ${locator.module})` - ); - - // Compile the template, which writes opcodes to the heap and returns the VM - // handle (the address of the compiled program in the heap). - vmHandle = compilableTemplate.compile(syntaxCompilationContext(this.context, this.macros)); - - if (typeof vmHandle !== 'number') { - return vmHandle; - } - - // Index the locator by VM handle and vice versa for easy lookups. - this.compilerModuleLocatorResolver().setHandleByLocator(locator, vmHandle); - - return vmHandle; - } -} - -/** - * For developer convenience, we allow users to pass partially populated - * TemplateLocator objects as identifiers for a given template. Because it is - * always a TemplateLocator added to a bundle, we can populate missing fields - * like the `kind` with the appropriate value and avoid boilerplate on the part - * of API consumers. - */ -export function normalizeLocator(l: ModuleLocator): ModuleLocator { - let { module, name } = l; - return { - module, - name, - }; -} diff --git a/packages/@glimmer/bundle-compiler/lib/debug-constants.ts b/packages/@glimmer/bundle-compiler/lib/debug-constants.ts deleted file mode 100644 index 52f8bfa267..0000000000 --- a/packages/@glimmer/bundle-compiler/lib/debug-constants.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { WriteOnlyConstants } from '@glimmer/program'; -import { RuntimeConstants } from '@glimmer/interfaces'; - -export default class DebugConstants extends WriteOnlyConstants implements RuntimeConstants { - getValue(handle: number) { - return this.values[handle] as T; - } - - getArray(value: number): T[] { - let handles = this.getValue(value) as number[]; - let reified: T[] = new Array(handles.length); - - for (let i = 0; i < handles.length; i++) { - let n = handles[i]; - reified[i] = this.getValue(n); - } - - return reified; - } - - getSerializable(s: number): T { - return JSON.parse(this.values[s] as string) as T; - } -} diff --git a/packages/@glimmer/bundle-compiler/lib/delegate.ts b/packages/@glimmer/bundle-compiler/lib/delegate.ts deleted file mode 100644 index c17eea26cc..0000000000 --- a/packages/@glimmer/bundle-compiler/lib/delegate.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { ComponentCapabilities, ModuleLocator } from '@glimmer/interfaces'; - -/** - * A CompilerDelegate helps the BundleCompiler map external references it finds - * in a template, such as other components and helpers, to their corresponding - * implementation. - * - * For example, if the compiler comes across the string `` - * in a template, it needs to know what template and component class on disk - * `MyOtherComponent` refers to. By moving this decision-making to the delegate, - * host environments can implement their own resolution semantics rather than - * having resolution hardcoded into Glimmer. - * - * Because resolution often depends on where a component was invoked, many hooks - * take a referrer, or the module locator for the template where the invocation - * was found, as the second argument. - * - * For example, if the template with the locator `{ module: - * 'src/ui/components/MyComponent.js', name: 'template' }` contains the string - * ``, the compiler would invoke `hasComponentInScope` with - * `'MyOtherComponent'` as the first argument and this locator as the second - * argument. - * - * The CompilerDelegate is also responsible for describing the capabilities of a - * particular component by returning a ComponentCapabilities descriptor. Glimmer - * uses this information to perform additional optimizations during the - * compilation phase. - */ -export default interface BundleCompilerDelegate { - /** - * During compilation, the compiler will ask the delegate about each component - * invocation found in the passed template. If the component exists in scope, - * the delegate should return `true`. If the component does not exist in - * scope, return `false`. Note that returning `false` will cause the - * compilation process to fail. - */ - hasComponentInScope(componentName: string, referrer: R): boolean; - - /** - * If the delegate returns `true` from `hasComponentInScope()`, the compiler - * will next ask the delegate to provide the module location for the named - * component. By resolving symbolic component names into unique module - * locations, the compiler avoids having to compile the same component - * multiple times if invoked from different templates. - */ - resolveComponent(componentName: string, referrer: R): ModuleLocator; - - /** - * The compiler calls this hook with the return value of `resolveComponent`, - * and it should return the required capabilities for the given component via - * a ComponentCapabilities descriptor. - */ - getComponentCapabilities(templateMeta: R): ComponentCapabilities; - - /** - * During compilation, the compiler will ask the delegate about each possible - * helper invocation found in the passed template. If the helper exists in - * scope, the delegate should return `true`. If the helper does not exist - * in scope, return `false`. - * - * Unlike with component resolution, note that returning `false` from this - * hook does not always cause compilation to fail. That's because helpers may - * be ambiguous with value expressions. - * - * For example, if the compiler encounters `{{currentTime}}` in a template, it - * will call `hasHelperInScope` with `'currentTime'` as the first argument. If - * `hasHelperInScope` returns `false`, the compiler will treat `currentTime` - * as a value rather than a helper. - */ - hasHelperInScope(helperName: string, referrer: R): boolean; - - /** - * If the delegate returns `true` from `hasHelperInScope()`, the compiler will - * next ask the delegate to provide a module locator corresponding to the helper function. - */ - resolveHelper(helperName: string, referrer: R): ModuleLocator; - - /** - * During compilation, the compiler will ask the delegate about each element - * modifier invocation found in the passed template. Element modifiers are - * mustaches that appear in the attribute position of elements, like - * `
`. - * - * If the modifier exists in scope, the delegate should return `true`. If the - * modifier does not exist in scope, return `false`. Note that returning - * `false` will cause the compilation process to fail. - */ - hasModifierInScope(modifierName: string, referrer: R): boolean; - - /** - * If the delegate returns `true` from `hasModifierInScope()`, the compiler - * will next ask the delegate to provide a module locator corresponding to the - * element modifier function. - */ - resolveModifier(modifierName: string, referrer: R): ModuleLocator; - - /** - * During compilation, the compiler will ask the delegate about each partial - * invocation found in the passed template. Partials are invoked with a - * special `partial` helper, like `{{partial "partialName"}}`. - * - * If the partial exists in scope, the delegate should return `true`. If the - * partial does not exist in scope, return `false`. Note that returning - * `false` will cause the compilation process to fail. - * - * Partials should be avoided because they disable many compiler - * optimizations. Only legacy environments with backwards-compatibility - * constraints should implement partials. New environments should always - * return `false` from `hasPartialInScope` to disable the feature entirely. - * Components replace all use cases for partials with better performance. - */ - hasPartialInScope(partialName: string, referrer: R): boolean; - - /** - * If the delegate returns `true` from `hasPartialInScope()`, the compiler - * will next ask the delegate to provide a module locator corresponding to the - * partial template. - */ - resolvePartial(partialName: string, referrer: R): ModuleLocator; -} diff --git a/packages/@glimmer/bundle-compiler/lib/external-module-table.ts b/packages/@glimmer/bundle-compiler/lib/external-module-table.ts deleted file mode 100644 index 01c3a7a318..0000000000 --- a/packages/@glimmer/bundle-compiler/lib/external-module-table.ts +++ /dev/null @@ -1,40 +0,0 @@ -import ModuleLocatorMap from './module-locator-map'; -import { ModuleLocator } from '@glimmer/interfaces'; - -/** - * Maps ModuleLocators to their associated handles, and vice versa. The table - * tracks both application handles (used to map symbolic references at compile - * time into concrete objects at runtime) and VM handles (used to track the - * offset of a compiled template in the binary program). - * - * Host environments can use this module table, provided at the end of - * compilation, to codegen a similar data structure in the compiled JavaScript - * output that allows the resolver to exchange handles for concrete module - * values at runtime. - */ -export default class ExternalModuleTable { - public byModuleLocator = new ModuleLocatorMap(); - public byHandle = new Map(); - - public vmHandleByModuleLocator = new ModuleLocatorMap(); - public byVMHandle = new Map(); - - /** - * Returns the handle (unique integer id) for the provided module locator. If - * the locator has not been seen before, a new handle is assigned. Otherwise, - * the same handle is always returned for a given locator. - */ - public handleForModuleLocator(locator: ModuleLocator): number { - let { byModuleLocator, byHandle } = this; - - let handle = byModuleLocator.get(locator); - - if (handle === undefined) { - handle = byHandle.size; - byHandle.set(handle, locator); - byModuleLocator.set(locator, handle); - } - - return handle; - } -} diff --git a/packages/@glimmer/bundle-compiler/lib/lookup.ts b/packages/@glimmer/bundle-compiler/lib/lookup.ts deleted file mode 100644 index 24e3a3c4c1..0000000000 --- a/packages/@glimmer/bundle-compiler/lib/lookup.ts +++ /dev/null @@ -1,108 +0,0 @@ -import CompilerDelegate from './delegate'; -import ExternalModuleTable from './external-module-table'; -import { - ComponentCapabilities, - CompilableProgram, - CompileTimeResolverDelegate, - ModuleLocator, - CompileTimeComponent, -} from '@glimmer/interfaces'; -import { expect, Option } from '@glimmer/util'; -import { ModuleLocatorMap } from '..'; - -/** - * The BundleCompilerResolver resolves references to objects inside a template into - * handles that can be redeemed for concrete objects at runtime. - * - * For example, if the `translate` helper is used in a template (`{{translate - * someText}}`), the compiler will invoke the resolver's `lookupHelper` method - * with the name of the helper ("translate") and the locator for the template - * that contained the invocation. - * - * The resolver is responsible for assigning a unique handle to this `translate` - * helper and ensuring that any future calls to `lookupHelper` that refer to the - * same helper return the same handle. - */ -export default class BundleCompilerLookup implements CompileTimeResolverDelegate { - private table = new ExternalModuleTable(); - - constructor( - private delegate: CompilerDelegate, - private compilableTemplates: ModuleLocatorMap, - private meta: ModuleLocatorMap - ) {} - - resolve(handle: number): ModuleLocator { - return expect(this.table.byHandle.get(handle), `Passed an invalid handle to resolve`); - } - - getTable(): ExternalModuleTable { - return this.table; - } - - getHandleByLocator(locator: ModuleLocator): number | undefined { - return this.table.vmHandleByModuleLocator.get(locator); - } - - setHandleByLocator(locator: ModuleLocator, handle: number): void { - this.table.byVMHandle.set(handle, locator); - this.table.vmHandleByModuleLocator.set(locator, handle); - - // We also make sure to assign a non-VM application handle to every - // top-level component as well, so any associated component classes appear - // in the module map. - this.table.handleForModuleLocator(locator); - } - - getCapabilities(handle: number): ComponentCapabilities { - let l = expect( - this.table.byHandle.get(handle), - `BUG: Shouldn't call getCapabilities if a handle has no associated locator` - ); - let meta = expect(this.meta.get(l), `could not find template metadata for module ${l.module}`); - return this.delegate.getComponentCapabilities(meta); - } - - getLayout(handle: number): Option { - let locator = expect( - this.table.byHandle.get(handle), - `BUG: Shouldn't call getLayout if a handle has no associated locator` - ); - return this.compilableTemplates.get(locator) || null; - } - - lookupHelper(name: string, referrer: R): Option { - if (this.delegate.hasHelperInScope(name, referrer)) { - let locator = this.delegate.resolveHelper(name, referrer); - return this.table.handleForModuleLocator(locator); - } else { - return null; - } - } - - lookupComponent(name: string, referrer: R): Option { - if (this.delegate.hasComponentInScope(name, referrer)) { - let locator = this.delegate.resolveComponent(name, referrer); - let handle = this.table.handleForModuleLocator(locator); - let capabilities = this.getCapabilities(handle); - let compilable = this.getLayout(handle); - - return { handle, capabilities, compilable }; - } else { - return null; - } - } - - lookupModifier(name: string, referrer: R): Option { - if (this.delegate.hasModifierInScope(name, referrer)) { - let locator = this.delegate.resolveModifier(name, referrer); - return this.table.handleForModuleLocator(locator); - } else { - return null; - } - } - - lookupPartial(_name: string, _meta: R): Option { - throw new Error('Method not implemented.'); - } -} diff --git a/packages/@glimmer/bundle-compiler/lib/module-locator-map.ts b/packages/@glimmer/bundle-compiler/lib/module-locator-map.ts deleted file mode 100644 index 409237751a..0000000000 --- a/packages/@glimmer/bundle-compiler/lib/module-locator-map.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { ModuleLocator } from '@glimmer/interfaces'; - -type ByModule = Map>; -type ByName = Map; - -/** - * The ModuleLocatorMap is a map-like data structure that accepts a - * ModuleLocator as the key. Instead of relying on a locator's identity to - * determine uniqueness, it instead indexes values based on the locator's - * `module` and `name` properties. - * - * This means you can use different object literals as locators to get and set - * values from the map, even if though they do not share identity: - * - * ```ts - * let map = new ModuleLocatorMap; - * map.set({ module: 'foo', name: 'default' }, 123); - * map.get({ module: 'foo', name: 'default' }); // returns 123 - * ``` - */ -export default class ModuleLocatorMap { - private byModule: ByModule = new Map(); - private locators = new Set(); - - set(locator: K, value: V): this { - let { module, name } = locator; - this._byName(module).set(name, value); - this.locators.add(locator); - return this; - } - - get({ module, name }: K): V | undefined { - return this._byName(module).get(name); - } - - forEach(cb: (value: V, key: K) => void): void { - this.locators.forEach((locator) => { - cb(this.get(locator)!, locator); - }); - } - - private _byName(module: string): ByName { - let byName = this.byModule.get(module); - - if (!byName) { - byName = new Map(); - this.byModule.set(module, byName); - } - - return byName; - } -} diff --git a/packages/@glimmer/bundle-compiler/package.json b/packages/@glimmer/bundle-compiler/package.json deleted file mode 100644 index 3dbb133402..0000000000 --- a/packages/@glimmer/bundle-compiler/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "@glimmer/bundle-compiler", - "version": "0.60.0", - "repository": "https://github.com/glimmerjs/glimmer-vm/tree/master/packages/@glimmer/bundle-compiler", - "dependencies": { - "@glimmer/syntax": "^0.60.0", - "@glimmer/util": "^0.60.0", - "@glimmer/wire-format": "^0.60.0", - "@glimmer/interfaces": "^0.60.0", - "@glimmer/program": "^0.60.0", - "@glimmer/compiler": "^0.60.0", - "@glimmer/opcode-compiler": "^0.60.0" - }, - "devDependencies": { - "@glimmer/runtime": "^0.60.0" - } -} diff --git a/packages/@glimmer/bundle-compiler/test/compiler-delegate-test.ts b/packages/@glimmer/bundle-compiler/test/compiler-delegate-test.ts deleted file mode 100644 index 4f1277eb62..0000000000 --- a/packages/@glimmer/bundle-compiler/test/compiler-delegate-test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { BundleCompiler } from '..'; -import { ComponentCapabilities, ModuleLocator } from '@glimmer/interfaces'; -import { MINIMAL_CAPABILITIES } from '@glimmer/opcode-compiler'; -import { assign } from '@glimmer/util'; - -const { test } = QUnit; - -export const BASIC_CAPABILITIES: ComponentCapabilities = assign({}, MINIMAL_CAPABILITIES, { - createInstance: true, -}); - -export interface WrappedLocator { - locator: ModuleLocator; -} - -QUnit.module('[glimmer-bundle-compiler] CompilerDelegate'); - -function locatorFor(locator: ModuleLocator): ModuleLocator { - let { module, name } = locator; - - return { - module, - name, - }; -} - -test('correct referrer is passed during component lookup', function (assert) { - let inScopeReferrers: ModuleLocator[] = []; - let resolveComponentReferrers: ModuleLocator[] = []; - - // This partial implementation of CompilerDelegate tracks what referrers are - // passed to hasComponentInScope and resolveComponent so that they - // can be verified after compilation has finished. - class TestDelegate { - hasComponentInScope(_componentName: string, referrer: ModuleLocator): boolean { - inScopeReferrers.push(referrer); - return true; - } - - resolveComponent(componentName: string, referrer: ModuleLocator): ModuleLocator { - resolveComponentReferrers.push(referrer); - return { module: componentName, name: 'default' }; - } - - getComponentCapabilities(): ComponentCapabilities { - return MINIMAL_CAPABILITIES; - } - } - - let bundleCompiler = new BundleCompiler(new TestDelegate() as any); - - bundleCompiler.addTemplateSource( - locatorFor({ module: 'UserNav', name: 'default' }), - '
' - ); - bundleCompiler.addTemplateSource(locatorFor({ module: 'Main', name: 'default' }), ''); - bundleCompiler.addTemplateSource( - locatorFor({ module: 'SideBar', name: 'default' }), - '' - ); - bundleCompiler.compile(); - - assert.deepEqual(inScopeReferrers, [ - { module: 'Main', name: 'default' }, - { module: 'SideBar', name: 'default' }, - ]); - - assert.deepEqual(resolveComponentReferrers, [ - { module: 'Main', name: 'default' }, - { module: 'SideBar', name: 'default' }, - ]); -}); diff --git a/packages/@glimmer/debug/lib/debug.ts b/packages/@glimmer/debug/lib/debug.ts index 7921999ff4..2a88f2d2d9 100644 --- a/packages/@glimmer/debug/lib/debug.ts +++ b/packages/@glimmer/debug/lib/debug.ts @@ -36,7 +36,7 @@ export function debugSlice(context: TemplateCompilationContext, start: number, e opcode.offset = i; let [name, params] = debug( context.syntax.program.constants as Recast, - context.syntax.program.resolverDelegate, + context.syntax.program.resolver, opcode, opcode.isMachine )!; diff --git a/packages/@glimmer/debug/lib/opcode-metadata.ts b/packages/@glimmer/debug/lib/opcode-metadata.ts index a7ed244a25..891c9bfa2b 100644 --- a/packages/@glimmer/debug/lib/opcode-metadata.ts +++ b/packages/@glimmer/debug/lib/opcode-metadata.ts @@ -165,24 +165,9 @@ METADATA[Op.SetVariable] = { check: true, }; -METADATA[Op.SetAotBlock] = { - name: 'SetAotBlock', - mnemonic: 'sbblock', - before: null, - stackChange: -3, - ops: [ - { - name: 'symbol', - type: 'u32', - }, - ], - operands: 1, - check: true, -}; - -METADATA[Op.SetJitBlock] = { - name: 'SetJitBlock', - mnemonic: 'sjblock', +METADATA[Op.SetBlock] = { + name: 'SetBlock', + mnemonic: 'sblock', before: null, stackChange: -3, ops: [ @@ -240,8 +225,8 @@ METADATA[Op.GetBlock] = { check: true, }; -METADATA[Op.JitSpreadBlock] = { - name: 'JitSpreadBlock', +METADATA[Op.SpreadBlock] = { + name: 'SpreadBlock', mnemonic: 'blockspread', before: null, stackChange: 2, @@ -1133,24 +1118,9 @@ METADATA[Op.GetComponentTagName] = { check: true, }; -METADATA[Op.GetAotComponentLayout] = { - name: 'GetAotComponentLayout', - mnemonic: 'comp_alayoutload', - before: null, - stackChange: 2, - ops: [ - { - name: 'state', - type: 'register', - }, - ], - operands: 1, - check: true, -}; - -METADATA[Op.GetJitComponentLayout] = { - name: 'GetJitComponentLayout', - mnemonic: 'comp_jlayoutload', +METADATA[Op.GetComponentLayout] = { + name: 'GetComponentLayout', + mnemonic: 'comp_layoutload', before: null, stackChange: 2, ops: [ diff --git a/packages/@glimmer/integration-tests/index.ts b/packages/@glimmer/integration-tests/index.ts index f630a737aa..a9b333fab3 100644 --- a/packages/@glimmer/integration-tests/index.ts +++ b/packages/@glimmer/integration-tests/index.ts @@ -5,7 +5,6 @@ export * from './lib/dom/assertions'; export * from './lib/dom/blocks'; export * from './lib/dom/simple-utils'; export * from './lib/markers'; -export * from './lib/modes/aot/delegate'; export * from './lib/modes/jit/delegate'; export * from './lib/modes/jit/register'; export * from './lib/modes/node/env'; diff --git a/packages/@glimmer/integration-tests/lib/components/basic.ts b/packages/@glimmer/integration-tests/lib/components/basic.ts index 59630537b5..59821a6c7e 100644 --- a/packages/@glimmer/integration-tests/lib/components/basic.ts +++ b/packages/@glimmer/integration-tests/lib/components/basic.ts @@ -1,16 +1,13 @@ import { Bounds, - WithJitStaticLayout, - WithAotStaticLayout, - AotRuntimeResolver, - JitRuntimeResolver, + WithStaticLayout, + RuntimeResolver, Environment, CompilableProgram, - Invocation, ComponentCapabilities, } from '@glimmer/interfaces'; import { TestComponentDefinitionState } from './test-component'; -import { unreachable, expect, unwrapTemplate } from '@glimmer/util'; +import { unreachable, unwrapTemplate } from '@glimmer/util'; import { Reference, createConstRef } from '@glimmer/reference'; export interface BasicComponentFactory { @@ -23,9 +20,7 @@ export class BasicComponent { } export class BasicComponentManager - implements - WithJitStaticLayout, - WithAotStaticLayout { + implements WithStaticLayout { getCapabilities(state: TestComponentDefinitionState): ComponentCapabilities { return state.capabilities; } @@ -43,25 +38,13 @@ export class BasicComponentManager return state.name; } - getJitStaticLayout( + getStaticLayout( state: TestComponentDefinitionState, - resolver: JitRuntimeResolver + resolver: RuntimeResolver ): CompilableProgram { return unwrapTemplate(resolver.compilable(state.locator)).asLayout(); } - getAotStaticLayout( - state: TestComponentDefinitionState, - resolver: AotRuntimeResolver - ): Invocation { - // For the case of dynamically invoking (via `{{component}}`) in eager - // mode, we need to exchange the module locator for the handle to the - // compiled layout (which was provided at bundle compilation time and - // stashed in the component definition state). - let locator = expect(state.locator, 'component definition state should include module locator'); - return resolver.getInvocation(locator); - } - getSelf(component: BasicComponent): Reference { return createConstRef(component, 'this'); } diff --git a/packages/@glimmer/integration-tests/lib/components/emberish-curly.ts b/packages/@glimmer/integration-tests/lib/components/emberish-curly.ts index 5892d3623e..eec4aa5ffb 100644 --- a/packages/@glimmer/integration-tests/lib/components/emberish-curly.ts +++ b/packages/@glimmer/integration-tests/lib/components/emberish-curly.ts @@ -3,12 +3,9 @@ import { CapturedNamedArguments, Bounds, WithDynamicTagName, - WithJitDynamicLayout, - WithAotStaticLayout, + WithDynamicLayout, ModuleLocator, ProgramSymbolTable, - AotRuntimeResolver, - Invocation, Template, VMArguments, PreparedArguments, @@ -18,7 +15,7 @@ import { Destroyable, Dict, ComponentCapabilities, - JitRuntimeResolver, + RuntimeResolver, } from '@glimmer/interfaces'; import { Attrs, AttrsDiff } from './emberish-glimmer'; import { @@ -127,12 +124,7 @@ export interface EmberishCurlyComponentDefinitionState { export class EmberishCurlyComponentManager implements WithDynamicTagName, - WithJitDynamicLayout, - WithAotStaticLayout< - EmberishCurlyComponentState, - EmberishCurlyComponentDefinitionState, - AotRuntimeResolver - > { + WithDynamicLayout { constructor(private registry?: TestJitRegistry) {} getDebugName(state: TestComponentDefinitionState) { @@ -143,16 +135,9 @@ export class EmberishCurlyComponentManager return state.capabilities; } - getAotStaticLayout( - state: EmberishCurlyComponentDefinitionState, - resolver: AotRuntimeResolver - ): Invocation { - return resolver.getInvocation(state.locator); - } - - getJitDynamicLayout( + getDynamicLayout( { component: { layout } }: EmberishCurlyComponentState, - resolver: JitRuntimeResolver + resolver: RuntimeResolver ): Template { if (!this.registry) { throw new Error( diff --git a/packages/@glimmer/integration-tests/lib/components/emberish-glimmer.ts b/packages/@glimmer/integration-tests/lib/components/emberish-glimmer.ts index 51b1fe94fc..b6712cb6c8 100644 --- a/packages/@glimmer/integration-tests/lib/components/emberish-glimmer.ts +++ b/packages/@glimmer/integration-tests/lib/components/emberish-glimmer.ts @@ -6,16 +6,13 @@ import { Bounds, CapturedNamedArguments, ComponentManager, - WithJitStaticLayout, - JitRuntimeResolver, - AotRuntimeResolver, - WithAotStaticLayout, + WithStaticLayout, + RuntimeResolver, ComponentCapabilities, Environment, VMArguments, DynamicScope, CompilableProgram, - Invocation, Destroyable, } from '@glimmer/interfaces'; import { keys, assign, unwrapTemplate } from '@glimmer/util'; @@ -89,16 +86,7 @@ export interface EmberishGlimmerComponentState { export class EmberishGlimmerComponentManager implements ComponentManager, - WithJitStaticLayout< - EmberishGlimmerComponentState, - TestComponentDefinitionState, - JitRuntimeResolver - >, - WithAotStaticLayout< - EmberishGlimmerComponentState, - TestComponentDefinitionState, - AotRuntimeResolver - > { + WithStaticLayout { getCapabilities(state: TestComponentDefinitionState): ComponentCapabilities { return state.capabilities; } @@ -138,22 +126,13 @@ export class EmberishGlimmerComponentManager return { args, component, selfRef }; } - getJitStaticLayout( + getStaticLayout( state: TestComponentDefinitionState, - resolver: JitRuntimeResolver + resolver: RuntimeResolver ): CompilableProgram { return unwrapTemplate(resolver.compilable(state.locator)).asLayout(); } - getAotStaticLayout( - state: TestComponentDefinitionState, - resolver: AotRuntimeResolver - ): Invocation { - let { locator } = state; - - return resolver.getInvocation(locator); - } - getSelf({ selfRef }: EmberishGlimmerComponentState): Reference { return selfRef; } diff --git a/packages/@glimmer/integration-tests/lib/modes/aot/compiler-delegate.ts b/packages/@glimmer/integration-tests/lib/modes/aot/compiler-delegate.ts deleted file mode 100644 index 365cda1fc3..0000000000 --- a/packages/@glimmer/integration-tests/lib/modes/aot/compiler-delegate.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { CompilerDelegate } from '@glimmer/bundle-compiler'; -import { ComponentCapabilities, ModuleLocator } from '@glimmer/interfaces'; -import { AotCompilerRegistry } from './registry'; - -export interface CapabilitiesState { - capabilities: ComponentCapabilities; -} - -export default class AotCompilerDelegate implements CompilerDelegate { - constructor(private registry: AotCompilerRegistry) {} - - hasComponentInScope(componentName: string, referrer: ModuleLocator): boolean { - let name = this.registry.resolve(componentName, referrer, { - root: 'ui/components', - expected: 'component', - }); - return !!name; - } - - resolveComponent(componentName: string, referrer: ModuleLocator): ModuleLocator { - return { - module: this.registry.resolve(componentName, referrer, { root: 'ui/components' })!, - name: 'default', - }; - } - - getComponentCapabilities(meta: ModuleLocator): ComponentCapabilities { - return this.registry.getComponentCapabilities(meta); - } - - hasHelperInScope(helperName: string, referrer: ModuleLocator): boolean { - return !!this.registry.resolve(helperName, referrer, { expected: 'helper' }); - } - - resolveHelper(helperName: string, referrer: ModuleLocator): ModuleLocator { - return { module: this.registry.resolve(helperName, referrer)!, name: 'default' }; - } - - hasModifierInScope(modifierName: string, referrer: ModuleLocator): boolean { - return !!this.registry.resolve(modifierName, referrer, { expected: 'modifier' }); - } - - resolveModifier(modifierName: string, referrer: ModuleLocator): ModuleLocator { - return { - module: this.registry.resolve(modifierName, referrer, { root: 'ui/components' })!, - name: 'default', - }; - } - - hasPartialInScope(_partialName: string, _referrer: ModuleLocator): boolean { - return false; - } - - resolvePartial(_partialName: string, _referrer: ModuleLocator): ModuleLocator { - throw new Error('Method not implemented.'); - } -} diff --git a/packages/@glimmer/integration-tests/lib/modes/aot/delegate.ts b/packages/@glimmer/integration-tests/lib/modes/aot/delegate.ts deleted file mode 100644 index 6b6fd4a51d..0000000000 --- a/packages/@glimmer/integration-tests/lib/modes/aot/delegate.ts +++ /dev/null @@ -1,355 +0,0 @@ -import { PrecompileOptions } from '@glimmer/compiler'; -import { - BundleCompiler, - DebugConstants, - ModuleLocatorMap, - normalizeLocator, - BundleCompilationResult, -} from '@glimmer/bundle-compiler'; -import { - ComponentCapabilities, - ComponentDefinition, - ComponentManager, - Cursor, - Dict, - Environment, - Helper as GlimmerHelper, - ModuleLocator, - ProgramSymbolTable, - RenderResult, - AotRuntimeContext, - ConstantPool, - ElementBuilder, - DynamicScope, -} from '@glimmer/interfaces'; -import { WrappedBuilder, PartialDefinitionImpl } from '@glimmer/opcode-compiler'; -import { createConstRef, Reference } from '@glimmer/reference'; -import { - clientBuilder, - getDynamicVar, - renderAotComponent, - renderAotMain, - renderSync, - AotRuntime, - EnvironmentDelegate, -} from '@glimmer/runtime'; -import { ASTPluginBuilder } from '@glimmer/syntax'; -import { assert, assign, expect, Option } from '@glimmer/util'; -import { - SimpleElement, - SimpleDocument, - SimpleText, - ElementNamespace, - SimpleDocumentFragment, -} from '@simple-dom/interface'; -import { BasicComponent, BasicComponentManager } from '../../components/basic'; -import { - EmberishCurlyComponent, - EmberishCurlyComponentManager, -} from '../../components/emberish-curly'; -import { - EmberishGlimmerComponent, - EmberishGlimmerComponentManager, - EMBERISH_GLIMMER_CAPABILITIES, -} from '../../components/emberish-glimmer'; -import RenderDelegate, { RenderDelegateOptions } from '../../render-delegate'; -import { TestComponentDefinitionState } from '../../components/test-component'; -import { ComponentKind } from '../../components/types'; -import { BASIC_CAPABILITIES, EMBERISH_CURLY_CAPABILITIES } from '../../components/capabilities'; -import { AotCompilerRegistry, Modules } from './registry'; -import { locatorFor } from '../../locator'; -import { UserHelper, createHelperRef } from '../../helpers'; -import { - TestModifierConstructor, - TestModifierDefinitionState, - TestModifierManager, -} from '../../modifiers'; -import AotRuntimeResolverImpl from './resolver'; -import { TestMacros } from '../../compile/macros'; -import AotCompilerDelegate from './compiler-delegate'; -import { preprocess } from '../../compile'; -import { BaseEnv } from '../env'; - -export type RenderDelegateComponentDefinition = ComponentDefinition; - -type Entries = { [F in ComponentKind]: Option }; - -const COMPONENT_CLASSES: Entries = { - Basic: BasicComponent, - Glimmer: EmberishGlimmerComponent, - Dynamic: EmberishCurlyComponent, - Curly: EmberishCurlyComponent, - Fragment: null, -}; - -const COMPONENT_MANAGERS: Entries = { - Basic: new BasicComponentManager(), - Glimmer: new EmberishGlimmerComponentManager(), - Dynamic: new EmberishCurlyComponentManager(), - Curly: new EmberishCurlyComponentManager(), - Fragment: null, -}; - -const COMPONENT_CAPABILITIES: Entries = { - Basic: BASIC_CAPABILITIES, - Glimmer: EMBERISH_GLIMMER_CAPABILITIES, - Dynamic: EMBERISH_CURLY_CAPABILITIES, - Curly: EMBERISH_CURLY_CAPABILITIES, - Fragment: null, -}; - -export class AotRenderDelegate implements RenderDelegate { - static readonly isEager = true; - static style = 'aot'; - - private plugins: ASTPluginBuilder[] = []; - protected registry = new AotCompilerRegistry(); - protected compileTimeModules = new Modules(); - protected symbolTables = new ModuleLocatorMap(); - public constants!: DebugConstants; - private doc: SimpleDocument; - private env: EnvironmentDelegate; - - constructor(options?: RenderDelegateOptions) { - this.registerInternalHelper('-get-dynamic-var', getDynamicVar); - this.env = assign(options?.env ?? {}, BaseEnv); - this.doc = options?.doc || (document as SimpleDocument); - } - - getElementBuilder(env: Environment, cursor: Cursor): ElementBuilder { - return clientBuilder(env, cursor); - } - - getInitialElement(): SimpleElement { - return this.doc.createElement('div'); - } - - createElement(tagName: string): SimpleElement { - return this.doc.createElement(tagName); - } - - createTextNode(content: string): SimpleText { - return this.doc.createTextNode(content); - } - - createElementNS(namespace: ElementNamespace, tagName: string): SimpleElement { - return this.doc.createElementNS(namespace, tagName); - } - - createDocumentFragment(): SimpleDocumentFragment { - return this.doc.createDocumentFragment(); - } - - registerPlugin(plugin: ASTPluginBuilder): void { - this.plugins.push(plugin); - } - - registerComponent( - type: ComponentKind, - testType: ComponentKind, - name: string, - template: string, - Class?: unknown - ): void { - let module = `ui/components/${name}`; - - let ComponentClass = Class || COMPONENT_CLASSES[type]; - let manager = COMPONENT_MANAGERS[type]; - let capabilities = COMPONENT_CAPABILITIES[type]; - - if (!manager || !capabilities) { - throw new Error(`Not implemented in the Bundle Compiler yet: ${type}`); - } - - let hasSymbolTable = testType === 'Dynamic'; - - let state: TestComponentDefinitionState = { - name, - type, - template, - capabilities, - hasSymbolTable, - ComponentClass, - locator: locatorFor({ module, name: 'default' }), - // Populated by the Bundle Compiler in eager mode - layout: null, - }; - - this.registry.addComponent(module, manager, state); - } - - getSelf(context: object) { - return createConstRef(context, 'this'); - } - - registerHelper(name: string, helper: UserHelper): void { - let glimmerHelper: GlimmerHelper = (args) => createHelperRef(helper, args.capture()); - this.registry.register(name, 'helper', { default: glimmerHelper }); - } - - registerInternalHelper(name: string, helper: GlimmerHelper) { - this.registry.register(name, 'helper', { default: helper }); - } - - registerPartial(name: string, source: string) { - let definition = new PartialDefinitionImpl( - name, - preprocess(source, undefined, this.precompileOptions) - ); - this.registry.register(name, 'partial', { default: definition }); - } - - registerModifier(name: string, ModifierClass: TestModifierConstructor): void { - let state = new TestModifierDefinitionState(ModifierClass); - let manager = new TestModifierManager(); - this.registry.register(name, 'modifier', { default: { manager, state } }); - } - - private get precompileOptions(): PrecompileOptions { - return { - plugins: { - ast: this.plugins, - }, - }; - } - - private addRegisteredComponents(bundleCompiler: BundleCompiler): void { - let { registry, compileTimeModules } = this; - Object.keys(registry.components).forEach((key) => { - assert( - key.indexOf('ui/components') !== -1, - `Expected component key to start with ui/components, got ${key}.` - ); - - let { state, manager } = registry.components[key]; - - let locator = locatorFor({ module: key, name: 'default' }); - - let block; - let symbolTable; - - if (state.type === 'Curly' || state.type === 'Dynamic') { - let block = bundleCompiler.preprocess(locator, state.template!); - let parsedLayout = { block, referrer: locator, asPartial: false }; - let wrapped = new WrappedBuilder(parsedLayout); - bundleCompiler.addCompilableTemplate(normalizeLocator(locator), wrapped); - - compileTimeModules.register(key, 'other', { - default: wrapped.symbolTable, - }); - - symbolTable = wrapped.symbolTable; - - this.symbolTables.set(locator, symbolTable); - } else { - block = bundleCompiler.addTemplateSource( - locator, - expect(state.template, 'expected component definition state to have template') - ); - symbolTable = { - hasEval: block.hasEval, - symbols: block.symbols, - }; - - this.symbolTables.set(locator, symbolTable); - - compileTimeModules.register(key, 'other', { - default: symbolTable, - }); - } - - if (state.hasSymbolTable) { - registry.register(key, 'component', { - default: { - state: assign({}, state, { symbolTable }), - manager, - }, - }); - } else { - registry.register(key, 'component', { - default: { - state, - manager, - }, - }); - } - }); - } - - private getBundleCompiler(): BundleCompiler { - let { compiler, constants } = getBundleCompiler(this.registry, this.plugins); - this.constants = constants; - - return compiler; - } - - getConstants(): ConstantPool { - return this.constants.toPool(); - } - - private getRuntimeContext({ table, pool, heap }: BundleCompilationResult): AotRuntimeContext { - let resolver = new AotRuntimeResolverImpl(table, this.registry.modules, this.symbolTables); - - return AotRuntime({ document: this.doc }, { constants: pool, heap }, resolver, this.env); - } - - renderComponent( - name: string, - args: Dict>, - element: SimpleElement, - dyanmicScope?: DynamicScope - ): RenderResult { - let bundleCompiler = this.getBundleCompiler(); - this.addRegisteredComponents(bundleCompiler); - let compilationResult = bundleCompiler.compile(); - - let cursor = { element, nextSibling: null }; - let runtime = this.getRuntimeContext(compilationResult); - let builder = this.getElementBuilder(runtime.env, cursor); - let iterator = renderAotComponent( - runtime, - builder, - compilationResult.main, - name, - args, - dyanmicScope - ); - - return renderSync(runtime.env, iterator); - } - - renderTemplate(template: string, context: Dict, element: SimpleElement): RenderResult { - this.registerComponent('Glimmer', 'Glimmer', 'main', template); - let bundleCompiler = this.getBundleCompiler(); - let locator = locatorFor({ module: 'ui/components/main', name: 'default' }); - // bundleCompiler.add(locator, template); - this.addRegisteredComponents(bundleCompiler); - - let compilationResult = bundleCompiler.compile(); - - let handle = compilationResult.table.vmHandleByModuleLocator.get(locator)!; - - let cursor = { element, nextSibling: null }; - let runtime = this.getRuntimeContext(compilationResult); - let builder = this.getElementBuilder(runtime.env, cursor); - let self = this.getSelf(context); - - let iterator = renderAotMain(runtime, self, builder, handle); - - return renderSync(runtime.env, iterator); - } -} - -function getBundleCompiler( - registry: AotCompilerRegistry, - plugins?: ASTPluginBuilder[] -): { compiler: BundleCompiler; constants: DebugConstants } { - let delegate: AotCompilerDelegate = new AotCompilerDelegate(registry); - let constants = new DebugConstants(); - let compiler = new BundleCompiler(delegate, { - macros: new TestMacros(), - constants, - plugins, - }); - return { constants, compiler }; -} diff --git a/packages/@glimmer/integration-tests/lib/modes/aot/registry.ts b/packages/@glimmer/integration-tests/lib/modes/aot/registry.ts deleted file mode 100644 index 8028fde2c5..0000000000 --- a/packages/@glimmer/integration-tests/lib/modes/aot/registry.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { CompilerDelegate } from '@glimmer/bundle-compiler'; -import { - ComponentCapabilities, - ComponentDefinition, - ComponentManager, - Dict, - ModuleLocator, - Option, -} from '@glimmer/interfaces'; -import { assert, dict } from '@glimmer/util'; -import { TestComponentDefinitionState } from '../../components/test-component'; - -export class Modules { - private registry = dict(); - - has(name: string): boolean { - return name in this.registry; - } - - get(name: string): Module { - return this.registry[name]; - } - - type(name: string): ModuleType { - let module = this.registry[name]; - return module.type; - } - - register(name: string, type: ModuleType, value: Dict) { - assert(name.indexOf('ui/components/ui') === -1, `BUG: ui/components/ui shouldn't be a prefix`); - assert(!name.match(/^[A-Z]/), 'BUG: Components should be nested under ui/components'); - this.registry[name] = new Module(value, type); - } - - resolve(name: string, referrer: ModuleLocator, defaultRoot?: string): Option { - let local = - referrer && referrer.module && referrer.module.replace(/^((.*)\/)?([^\/]*)$/, `$1${name}`); - if (local && this.registry[local]) { - return local; - } else if (defaultRoot && this.registry[`${defaultRoot}/${name}`]) { - return `${defaultRoot}/${name}`; - } else if (this.registry[name]) { - return name; - } else { - return null; - } - } -} - -export type ModuleType = 'component' | 'helper' | 'modifier' | 'partial' | 'other'; - -export class Module { - constructor(private dict: Dict, public type: ModuleType) { - Object.freeze(this.dict); - } - - has(key: string) { - return key in this.dict; - } - - get(key: string): unknown { - return this.dict[key]; - } -} - -export interface CapabilitiesState { - capabilities: ComponentCapabilities; -} - -export class AotCompilerRegistry { - constructor( - readonly components: Dict> = dict(), - readonly modules: Modules = new Modules() - ) {} - - register(name: string, type: ModuleType, value: Dict) { - this.modules.register(name, type, value); - } - - addComponent(name: string, manager: ComponentManager, state: TestComponentDefinitionState) { - this.components[name] = { manager, state }; - } - - resolve( - name: string, - referrer: ModuleLocator, - { expected, root }: { expected?: ModuleType; root?: string } = {} - ): Option { - let moduleName = this.modules.resolve(name, referrer, root); - if (moduleName === null) return null; - - let type = this.modules.type(moduleName); - - if (expected === undefined || type === expected) { - return moduleName; - } else { - return null; - } - } - - get(name: string): Module { - return this.modules.get(name); - } - - type(name: string): ModuleType { - return this.modules.type(name); - } - - getComponentCapabilities(meta: ModuleLocator): ComponentCapabilities { - return this.components[meta.module].state.capabilities; - } -} - -export default class EagerCompilerDelegate implements CompilerDelegate { - constructor(private registry: AotCompilerRegistry) {} - - hasComponentInScope(componentName: string, referrer: ModuleLocator): boolean { - let name = this.registry.resolve(componentName, referrer, { - root: 'ui/components', - expected: 'component', - }); - return !!name; - } - - resolveComponent(componentName: string, referrer: ModuleLocator): ModuleLocator { - return { - module: this.registry.resolve(componentName, referrer, { root: 'ui/components' })!, - name: 'default', - }; - } - - getComponentCapabilities(meta: ModuleLocator): ComponentCapabilities { - return this.registry.getComponentCapabilities(meta); - } - - hasHelperInScope(helperName: string, referrer: ModuleLocator): boolean { - return !!this.registry.resolve(helperName, referrer, { expected: 'helper' }); - } - - resolveHelper(helperName: string, referrer: ModuleLocator): ModuleLocator { - return { module: this.registry.resolve(helperName, referrer)!, name: 'default' }; - } - - hasModifierInScope(modifierName: string, referrer: ModuleLocator): boolean { - return !!this.registry.resolve(modifierName, referrer, { expected: 'modifier' }); - } - - resolveModifier(modifierName: string, referrer: ModuleLocator): ModuleLocator { - return { - module: this.registry.resolve(modifierName, referrer, { root: 'ui/components' })!, - name: 'default', - }; - } - - hasPartialInScope(_partialName: string, _referrer: ModuleLocator): boolean { - return false; - } - - resolvePartial(_partialName: string, _referrer: ModuleLocator): ModuleLocator { - throw new Error('Method not implemented.'); - } -} diff --git a/packages/@glimmer/integration-tests/lib/modes/aot/resolver.ts b/packages/@glimmer/integration-tests/lib/modes/aot/resolver.ts deleted file mode 100644 index 0baae44c29..0000000000 --- a/packages/@glimmer/integration-tests/lib/modes/aot/resolver.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { ExternalModuleTable, ModuleLocatorMap } from '@glimmer/bundle-compiler'; -import { Modules } from './registry'; -import { - ProgramSymbolTable, - Option, - ComponentDefinition, - ModuleLocator, - Invocation, - Template, - AotRuntimeResolver, -} from '@glimmer/interfaces'; -import { expect } from '@glimmer/util'; - -export default class AotRuntimeResolverImpl implements AotRuntimeResolver { - constructor( - private table: ExternalModuleTable, - private modules: Modules, - public symbolTables: ModuleLocatorMap - ) {} - - lookupHelper(_name: string, _meta: unknown): Option { - throw new Error('Method not implemented.'); - } - - lookupModifier(_name: string, _meta: unknown): Option { - throw new Error('Method not implemented.'); - } - - lookupComponent(name: string, referrer: Option): Option { - if (referrer === null) return null; - - let moduleName = this.modules.resolve(name, referrer, 'ui/components'); - - if (!moduleName) return null; - - let module = this.modules.get(moduleName); - return module.get('default') as ComponentDefinition; - } - - lookupPartial(_name: string, _meta: unknown): Option { - throw new Error('Method not implemented.'); - } - - resolve(handle: number): U { - let module = this.table.byHandle.get(handle)!; - return this.modules.get(module.module).get('default') as U; - } - - getInvocation(locator: ModuleLocator): Invocation { - let handle = this.getVMHandle(locator); - let symbolTable = expect( - this.symbolTables.get(locator), - `expected symbol table for module ${locator}` - ); - - return { - handle, - symbolTable, - }; - } - - compilable(_locator: ModuleLocator): Template { - throw new Error(`Unimplemented; AOT#compilable`); - } - - getVMHandle(locator: ModuleLocator): number { - let handle = expect( - this.table.vmHandleByModuleLocator.get(locator), - `could not find handle for module ${locator}` - ); - return handle; - } -} diff --git a/packages/@glimmer/integration-tests/lib/modes/jit/compilation-context.ts b/packages/@glimmer/integration-tests/lib/modes/jit/compilation-context.ts index aac8f0f763..abb0d3dfc4 100644 --- a/packages/@glimmer/integration-tests/lib/modes/jit/compilation-context.ts +++ b/packages/@glimmer/integration-tests/lib/modes/jit/compilation-context.ts @@ -1,5 +1,5 @@ import { - CompileTimeResolverDelegate, + CompileTimeResolver, ComponentCapabilities, Option, ComponentDefinition, @@ -10,7 +10,7 @@ import { TestJitRegistry } from './registry'; import { unwrapTemplate } from '@glimmer/util'; import TestJitRuntimeResolver from './resolver'; -export default class JitCompileTimeLookup implements CompileTimeResolverDelegate { +export default class JitCompileTimeLookup implements CompileTimeResolver { constructor(private resolver: TestJitRuntimeResolver, private registry: TestJitRegistry) {} resolve(handle: number): T { diff --git a/packages/@glimmer/integration-tests/lib/modes/jit/delegate.ts b/packages/@glimmer/integration-tests/lib/modes/jit/delegate.ts index 2c98d0c20c..f69c79a884 100644 --- a/packages/@glimmer/integration-tests/lib/modes/jit/delegate.ts +++ b/packages/@glimmer/integration-tests/lib/modes/jit/delegate.ts @@ -1,6 +1,6 @@ import { PrecompileOptions } from '@glimmer/compiler'; import { - JitRuntimeContext, + RuntimeContext, SyntaxCompilationContext, Environment, Cursor, @@ -10,6 +10,8 @@ import { Option, Helper, HandleResult, + DynamicScope, + ComponentDefinition, } from '@glimmer/interfaces'; import { SimpleDocument, @@ -22,10 +24,13 @@ import { TestJitRegistry } from './registry'; import { getDynamicVar, clientBuilder, - JitRuntime, EnvironmentDelegate, CurriedComponentDefinition, + runtimeContext, + renderSync, + renderComponent, } from '@glimmer/runtime'; +import { artifacts } from '@glimmer/program'; import { registerInternalHelper, registerStaticTaglessComponent, @@ -50,13 +55,13 @@ import { TestModifierConstructor } from '../../modifiers'; import { UserHelper } from '../../helpers'; import { createConstRef, Reference } from '@glimmer/reference'; import { renderTemplate } from './render'; -import { JitContext } from '@glimmer/opcode-compiler'; +import { syntaxCompilationContext } from '@glimmer/opcode-compiler'; import { preprocess } from '../../compile'; import { unwrapTemplate, assign } from '@glimmer/util'; import { BaseEnv } from '../env'; export interface JitTestDelegateContext { - runtime: JitRuntimeContext; + runtime: RuntimeContext; syntax: SyntaxCompilationContext; } @@ -67,8 +72,13 @@ export function JitDelegateContext( env: EnvironmentDelegate ): JitTestDelegateContext { registerInternalHelper(registry, '-get-dynamic-var', getDynamicVar); - let context = JitContext(new JitCompileTimeLookup(resolver, registry), new TestMacros()); - let runtime = JitRuntime({ document: doc }, env, context, resolver); + let sharedArtifacts = artifacts(); + let context = syntaxCompilationContext( + sharedArtifacts, + new JitCompileTimeLookup(resolver, registry), + new TestMacros() + ); + let runtime = runtimeContext({ document: doc }, env, sharedArtifacts, resolver); return { runtime, syntax: context }; } @@ -226,6 +236,32 @@ export class JitRenderDelegate implements RenderDelegate { ); } + renderComponent( + name: string, + args: Dict>, + element: SimpleElement, + dyanmicScope?: DynamicScope + ): RenderResult { + let cursor = { element, nextSibling: null }; + let { syntax, runtime } = this.context; + let builder = this.getElementBuilder(runtime.env, cursor); + + let { handle, compilable } = this.registry.lookupCompileTimeComponent(name, null)!; + let component = this.registry.resolve(handle); + + let iterator = renderComponent( + runtime, + builder, + syntax, + component, + compilable!, + args, + dyanmicScope + ); + + return renderSync(runtime.env, iterator); + } + private get precompileOptions(): PrecompileOptions { return { plugins: { diff --git a/packages/@glimmer/integration-tests/lib/modes/jit/render.ts b/packages/@glimmer/integration-tests/lib/modes/jit/render.ts index c68f1e23f0..a7dbdbec7d 100644 --- a/packages/@glimmer/integration-tests/lib/modes/jit/render.ts +++ b/packages/@glimmer/integration-tests/lib/modes/jit/render.ts @@ -3,7 +3,7 @@ import { PrecompileOptions } from '@glimmer/compiler'; import { Reference } from '@glimmer/reference'; import { ElementBuilder, RenderResult } from '@glimmer/interfaces'; import { preprocess } from '../../compile'; -import { renderJitMain, renderSync } from '@glimmer/runtime'; +import { renderMain, renderSync } from '@glimmer/runtime'; import { unwrapTemplate, unwrapHandle } from '@glimmer/util'; export function renderTemplate( @@ -16,6 +16,6 @@ export function renderTemplate( let template = preprocess(src, undefined, options); let handle = unwrapTemplate(template).asLayout().compile(syntax); - let iterator = renderJitMain(runtime, syntax, self, builder, unwrapHandle(handle)); + let iterator = renderMain(runtime, syntax, self, builder, unwrapHandle(handle)); return renderSync(runtime.env, iterator); } diff --git a/packages/@glimmer/integration-tests/lib/modes/jit/resolver.ts b/packages/@glimmer/integration-tests/lib/modes/jit/resolver.ts index 91f7619ec9..3dfe2481f9 100644 --- a/packages/@glimmer/integration-tests/lib/modes/jit/resolver.ts +++ b/packages/@glimmer/integration-tests/lib/modes/jit/resolver.ts @@ -1,5 +1,5 @@ import { - JitRuntimeResolver, + RuntimeResolver, AnnotatedModuleLocator, Option, ComponentDefinition, @@ -9,7 +9,7 @@ import { import { LookupType, TestJitRegistry } from './registry'; import { createTemplate } from '../../compile'; -export default class TestJitRuntimeResolver implements JitRuntimeResolver { +export default class TestJitRuntimeResolver implements RuntimeResolver { readonly registry = new TestJitRegistry(); lookup( diff --git a/packages/@glimmer/integration-tests/lib/modes/node/env.ts b/packages/@glimmer/integration-tests/lib/modes/node/env.ts index 68ff9b9425..262df21e2c 100644 --- a/packages/@glimmer/integration-tests/lib/modes/node/env.ts +++ b/packages/@glimmer/integration-tests/lib/modes/node/env.ts @@ -2,7 +2,6 @@ import { GlimmerTreeChanges, GlimmerTreeConstruction } from '@glimmer/interfaces import createHTMLDocument from '@simple-dom/document'; import { SimpleDocument } from '@simple-dom/interface'; import { JitRenderDelegate } from '../jit/delegate'; -import { AotRenderDelegate } from '../aot/delegate'; import { RenderTest } from '../../render-test'; import RenderDelegate, { RenderDelegateOptions } from '../../render-delegate'; import { toInnerHTML, assertElement } from '../../dom/simple-utils'; @@ -22,15 +21,6 @@ export class NodeJitRenderDelegate extends JitRenderDelegate { } } -export class NodeAotRenderDelegate extends AotRenderDelegate { - static style = 'node aot'; - - constructor(options: RenderDelegateOptions = {}) { - options.doc = options.doc || createHTMLDocument(); - super(options); - } -} - export class AbstractNodeTest extends RenderTest { constructor(delegate: RenderDelegate) { super(delegate); @@ -54,10 +44,3 @@ export class AbstractNodeTest extends RenderTest { this.assert.equal(serialized, html); } } - -export class NodeRenderDelegate extends AotRenderDelegate { - constructor(options: RenderDelegateOptions = {}) { - options.doc = options.doc ?? createHTMLDocument(); - super(options); - } -} diff --git a/packages/@glimmer/integration-tests/lib/render-delegate.ts b/packages/@glimmer/integration-tests/lib/render-delegate.ts index 8e22683cba..089d20f0d8 100644 --- a/packages/@glimmer/integration-tests/lib/render-delegate.ts +++ b/packages/@glimmer/integration-tests/lib/render-delegate.ts @@ -1,4 +1,3 @@ -import { DebugConstants } from '@glimmer/bundle-compiler'; import { SimpleElement, SimpleText, @@ -26,7 +25,6 @@ export interface RenderDelegateOptions { } export default interface RenderDelegate { - constants?: DebugConstants; getInitialElement(): SimpleElement; createElement(tagName: string): SimpleElement; createTextNode(content: string): SimpleText; diff --git a/packages/@glimmer/integration-tests/lib/suites.ts b/packages/@glimmer/integration-tests/lib/suites.ts index 2b6d553c57..59300c5aa0 100644 --- a/packages/@glimmer/integration-tests/lib/suites.ts +++ b/packages/@glimmer/integration-tests/lib/suites.ts @@ -11,6 +11,5 @@ export * from './suites/shadowing'; export * from './suites/with-dynamic-vars'; export * from './suites/yield'; export * from './suites/ssr'; -export * from './suites/bundle-compiler'; export * from './suites/entry-point'; export * from './suites/custom-dom-helper'; diff --git a/packages/@glimmer/integration-tests/lib/suites/bundle-compiler.ts b/packages/@glimmer/integration-tests/lib/suites/bundle-compiler.ts deleted file mode 100644 index c6ce9af060..0000000000 --- a/packages/@glimmer/integration-tests/lib/suites/bundle-compiler.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { EmberishComponentTests } from './emberish-components'; -import { AotRenderDelegate } from '../modes/aot/delegate'; -import { test } from '../test-decorator'; -import { EmberishGlimmerComponent } from '../components/emberish-glimmer'; - -export class BundleCompilerEmberTests extends EmberishComponentTests { - protected delegate!: AotRenderDelegate; - - @test({ kind: 'glimmer' }) - 'should not serialize the locator with static component helpers'() { - this.registerComponent( - 'Glimmer', - 'A', - '{{component "B" foo=@bar}} {{component "B" foo=2}} {{component "B" foo=3}}' - ); - this.registerComponent('Glimmer', 'B', 'B {{@foo}}'); - this.render(' {{component "B" foo=4}}'); - let ALocator = JSON.stringify({ module: 'ui/components/A', name: 'default' }); - let MainLocator = JSON.stringify({ - module: 'ui/components/main', - name: 'default', - }); - let values = this.delegate.getConstants(); - this.assert.equal(values.indexOf(ALocator), -1); - this.assert.equal(values.indexOf(MainLocator), -1); - this.assertHTML('B 1 B 2 B 3 B 4'); - this.assertStableRerender(); - } - - @test({ kind: 'glimmer' }) - 'should not serialize if there are no args'() { - class B extends EmberishGlimmerComponent { - bar = 1; - } - this.registerComponent('Glimmer', 'A', '{{component "B"}}'); - this.registerComponent('Glimmer', 'B', 'B {{bar}}', B); - this.render(' {{component "B"}}'); - let ALocator = JSON.stringify({ locator: { module: 'ui/components/A', name: 'default' } }); - let MainLocator = JSON.stringify({ - locator: { module: 'ui/components/main', name: 'default' }, - }); - let values = this.delegate.constants!.toPool(); - this.assert.equal(values.indexOf(ALocator), -1); - this.assert.equal(values.indexOf(MainLocator), -1); - this.assertHTML('B 1 B 1'); - this.assertStableRerender(); - } -} diff --git a/packages/@glimmer/integration-tests/lib/suites/custom-dom-helper.ts b/packages/@glimmer/integration-tests/lib/suites/custom-dom-helper.ts index 489a607813..3f9f94bcd2 100644 --- a/packages/@glimmer/integration-tests/lib/suites/custom-dom-helper.ts +++ b/packages/@glimmer/integration-tests/lib/suites/custom-dom-helper.ts @@ -1,4 +1,4 @@ -import { AbstractNodeTest, NodeJitRenderDelegate, NodeAotRenderDelegate } from '../modes/node/env'; +import { AbstractNodeTest, NodeJitRenderDelegate } from '../modes/node/env'; import { test } from '../test-decorator'; import { NodeDOMTreeConstruction, serializeBuilder } from '@glimmer/node'; import { RenderTest } from '../render-test'; @@ -43,12 +43,6 @@ export class JitSerializationDelegate extends NodeJitRenderDelegate { } } -export class AotSerializationDelegate extends NodeAotRenderDelegate { - getElementBuilder(env: Environment, cursor: Cursor) { - return serializeBuilder(env, cursor); - } -} - export class SerializedDOMHelperTests extends DOMHelperTests { static suiteName = 'Server-side rendering in Node.js (serialize)'; diff --git a/packages/@glimmer/integration-tests/lib/suites/entry-point.ts b/packages/@glimmer/integration-tests/lib/suites/entry-point.ts index 55743ef2b5..15b2eed15a 100644 --- a/packages/@glimmer/integration-tests/lib/suites/entry-point.ts +++ b/packages/@glimmer/integration-tests/lib/suites/entry-point.ts @@ -3,7 +3,7 @@ import { createPrimitiveRef } from '@glimmer/reference'; import { RenderTest, Count } from '../render-test'; import { ComponentKind } from '../components/types'; import { test } from '../test-decorator'; -import { AotRenderDelegate } from '../modes/aot/delegate'; +import { JitRenderDelegate } from '../modes/jit/delegate'; export class EntryPointTest extends RenderTest { static suiteName = 'entry points'; @@ -14,7 +14,7 @@ export class EntryPointTest extends RenderTest { @test 'an entry point'() { - let delegate = new AotRenderDelegate(); + let delegate = new JitRenderDelegate(); delegate.registerComponent('Basic', 'Basic', 'Title', `

hello {{@title}}

`); let element = delegate.getInitialElement(); @@ -26,7 +26,7 @@ export class EntryPointTest extends RenderTest { @test 'does not leak args between invocations'() { - let delegate = new AotRenderDelegate(); + let delegate = new JitRenderDelegate(); delegate.registerComponent('Basic', 'Basic', 'Title', `

hello {{@title}}

`); let element = delegate.getInitialElement(); @@ -42,7 +42,7 @@ export class EntryPointTest extends RenderTest { @test 'can render different components per call'() { - let delegate = new AotRenderDelegate(); + let delegate = new JitRenderDelegate(); delegate.registerComponent('Basic', 'Basic', 'Title', `

hello {{@title}}

`); delegate.registerComponent('Basic', 'Basic', 'Body', `

body {{@body}}

`); @@ -59,7 +59,7 @@ export class EntryPointTest extends RenderTest { @test 'supports passing in an initial dynamic context'() { - let delegate = new AotRenderDelegate(); + let delegate = new JitRenderDelegate(); delegate.registerComponent('Basic', 'Basic', 'Locale', `{{-get-dynamic-var "locale"}}`); let element = delegate.getInitialElement(); diff --git a/packages/@glimmer/integration-tests/lib/test-helpers/module.ts b/packages/@glimmer/integration-tests/lib/test-helpers/module.ts index bc2c985e26..635970dead 100644 --- a/packages/@glimmer/integration-tests/lib/test-helpers/module.ts +++ b/packages/@glimmer/integration-tests/lib/test-helpers/module.ts @@ -4,9 +4,8 @@ import { JitRenderDelegate } from '../modes/jit/delegate'; import { keys } from '@glimmer/util'; import { DeclaredComponentKind } from '../test-decorator'; import { ComponentKind } from '../components'; -import { AotRenderDelegate } from '../modes/aot/delegate'; -import { NodeRenderDelegate } from '../modes/node/env'; -import { JitSerializationDelegate, AotSerializationDelegate } from '../suites/custom-dom-helper'; +import { NodeJitRenderDelegate } from '../modes/node/env'; +import { JitSerializationDelegate } from '../suites/custom-dom-helper'; import { EnvironmentDelegate } from '@glimmer/runtime'; export interface RenderTestConstructor { @@ -25,13 +24,13 @@ export function nodeSuite( klass: RenderTestConstructor, options = { componentModule: false } ): void { - return suite(klass, NodeRenderDelegate, options); + return suite(klass, NodeJitRenderDelegate, options); } export function nodeComponentSuite( klass: RenderTestConstructor ): void { - return suite(klass, NodeRenderDelegate, { componentModule: true }); + return suite(klass, NodeJitRenderDelegate, { componentModule: true }); } export function jitComponentSuite( @@ -40,19 +39,6 @@ export function jitComponentSuite( return suite(klass, JitRenderDelegate, { componentModule: true }); } -export function aotSuite( - klass: RenderTestConstructor, - options = { componentModule: false } -): void { - return suite(klass, AotRenderDelegate, options); -} - -export function aotComponentSuite( - klass: RenderTestConstructor -): void { - return suite(klass, AotRenderDelegate, { componentModule: true }); -} - export function jitSerializeSuite( klass: RenderTestConstructor, options = { componentModule: false } @@ -60,13 +46,6 @@ export function jitSerializeSuite( return suite(klass, JitSerializationDelegate, options); } -export function aotSerializeSuite( - klass: RenderTestConstructor, - options = { componentModule: false } -): void { - return suite(klass, AotSerializationDelegate, options); -} - export interface RenderDelegateConstructor { readonly isEager: boolean; readonly style: string; diff --git a/packages/@glimmer/integration-tests/test/aot-suites-test.ts b/packages/@glimmer/integration-tests/test/aot-suites-test.ts deleted file mode 100644 index 506aaf9ce7..0000000000 --- a/packages/@glimmer/integration-tests/test/aot-suites-test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { - aotComponentSuite, - aotSuite, - BasicComponents, - BundleCompilerEmberTests, - DebuggerSuite, - EachSuite, - EmberishComponentTests, - FragmentComponents, - HasBlockParamsHelperSuite, - HasBlockSuite, - InElementSuite, - InitialRenderSuite, - ScopeSuite, - ShadowingSuite, - WithDynamicVarsSuite, - YieldSuite, - EntryPointTest, -} from '..'; - -aotSuite(DebuggerSuite); -aotSuite(EachSuite); -aotSuite(InElementSuite); -aotSuite(InitialRenderSuite); -aotSuite(EntryPointTest); - -aotComponentSuite(BasicComponents); -aotComponentSuite(FragmentComponents); -aotComponentSuite(EmberishComponentTests); -aotComponentSuite(HasBlockSuite); -aotComponentSuite(HasBlockParamsHelperSuite); -aotComponentSuite(ScopeSuite); -aotComponentSuite(ShadowingSuite); -aotComponentSuite(WithDynamicVarsSuite); -aotComponentSuite(YieldSuite); -aotComponentSuite(BundleCompilerEmberTests); diff --git a/packages/@glimmer/integration-tests/test/node-suites-node-test.ts b/packages/@glimmer/integration-tests/test/node-suites-node-test.ts index bae91d85df..91d2a86ef5 100644 --- a/packages/@glimmer/integration-tests/test/node-suites-node-test.ts +++ b/packages/@glimmer/integration-tests/test/node-suites-node-test.ts @@ -6,24 +6,17 @@ import { suite, DOMHelperTests, NodeJitRenderDelegate, - NodeAotRenderDelegate, SerializedDOMHelperTests, JitSerializationDelegate, - AotSerializationDelegate, CompilationTests, - componentSuite, } from '..'; nodeSuite(ServerSideSuite); nodeComponentSuite(ServerSideComponentSuite); suite(DOMHelperTests, NodeJitRenderDelegate); -suite(DOMHelperTests, NodeAotRenderDelegate); suite(SerializedDOMHelperTests, JitSerializationDelegate); -suite(SerializedDOMHelperTests, AotSerializationDelegate); if (typeof process !== 'undefined') { suite(CompilationTests, NodeJitRenderDelegate); } - -componentSuite(ServerSideComponentSuite, NodeAotRenderDelegate); diff --git a/packages/@glimmer/integration-tests/test/smoke-test.ts b/packages/@glimmer/integration-tests/test/smoke-test.ts index f510d4e522..726fff0bd9 100644 --- a/packages/@glimmer/integration-tests/test/smoke-test.ts +++ b/packages/@glimmer/integration-tests/test/smoke-test.ts @@ -1,4 +1,4 @@ -import { RenderTest, test, jitSuite, aotSuite } from '..'; +import { RenderTest, test, jitSuite } from '..'; class SmokeTests extends RenderTest { static suiteName = 'Smoke Tests'; @@ -19,4 +19,3 @@ class SmokeTests extends RenderTest { } jitSuite(SmokeTests); -aotSuite(SmokeTests); diff --git a/packages/@glimmer/interfaces/lib/compile/encoder.d.ts b/packages/@glimmer/interfaces/lib/compile/encoder.d.ts index c5ac02153f..43b52f7647 100644 --- a/packages/@glimmer/interfaces/lib/compile/encoder.d.ts +++ b/packages/@glimmer/interfaces/lib/compile/encoder.d.ts @@ -32,8 +32,6 @@ export interface AllOpMap { Option: OptionOp; StartLabels: StartLabelsOp; StopLabels: StopLabelsOp; - JitCompileBlock: JitCompileBlockOp; - GetComponentLayout: GetComponentLayoutOp; IfResolved: IfResolvedOp; Expr: ExprOp; @@ -43,10 +41,6 @@ export interface AllOpMap { CompileInline: CompileInlineOp; CompileBlock: CompileBlockOp; - SetBlock: SetBlockOp; - InvokeStatic: InvokeStaticOp; - PushCompilable: PushCompilableOp; - Args: ArgsOp; IfResolvedComponent: IfResolvedComponentOp; DynamicComponent: DynamicComponentOp; @@ -64,18 +58,12 @@ export const enum HighLevelBuilderOpcode { Option = 'Option', StartLabels = 'StartLabels', StopLabels = 'StopLabels', - JitCompileBlock = 'JitCompileBlock', - GetComponentLayout = 'GetComponentLayout', - SetBlock = 'SetBlock', } // Must be kept in sync with isCompileOpcode in encoder.ts export const enum HighLevelCompileOpcode { CompileInline = 'CompileInline', CompileBlock = 'CompileBlock', - InvokeStatic = 'InvokeStatic', - PushCompilable = 'PushCompilable', - Args = 'Args', IfResolvedComponent = 'IfResolvedComponent', DynamicComponent = 'DynamicComponent', } @@ -105,12 +93,6 @@ export const enum ResolveHandle { ComponentDefinition = 'ComponentDefinition', } -export interface InvokeStaticOp { - type: 'Compile'; - op: HighLevelCompileOpcode.InvokeStatic; - op1: CompilableTemplate; -} - export interface CompileInlineOp { type: 'Compile'; op: HighLevelCompileOpcode.CompileInline; @@ -133,18 +115,6 @@ export interface ArgsOptions { atNames: boolean; } -export interface ArgsOp { - type: 'Compile'; - op: HighLevelCompileOpcode.Args; - op1: ArgsOptions; -} - -export interface PushCompilableOp { - type: 'Compile'; - op: HighLevelCompileOpcode.PushCompilable; - op1: Option; -} - export interface IfResolvedOp { type: 'Resolution'; op: HighLevelResolutionOpcode.IfResolved; @@ -203,9 +173,6 @@ export interface DynamicComponentOp { export type HighLevelCompileOp = | CompileInlineOp | CompileBlockOp - | InvokeStaticOp - | ArgsOp - | PushCompilableOp | IfResolvedComponentOp | DynamicComponentOp; @@ -242,12 +209,6 @@ export interface OptionOp { op1: Option; } -export interface SetBlockOp { - type: 'Simple'; - op: HighLevelBuilderOpcode.SetBlock; - op1: number; -} - export interface StartLabelsOp { type: 'Simple'; op: HighLevelBuilderOpcode.StartLabels; @@ -260,12 +221,6 @@ export interface StopLabelsOp { op1: undefined; } -export interface JitCompileBlockOp { - type: 'Simple'; - op: HighLevelBuilderOpcode.JitCompileBlock; - op1: undefined; -} - export interface LabelOp { type: 'Simple'; op: HighLevelBuilderOpcode.Label; @@ -303,12 +258,6 @@ export interface ResolveContextualFreeOp { }; } -export interface GetComponentLayoutOp { - type: 'Simple'; - op: HighLevelBuilderOpcode.GetComponentLayout; - op1: number; -} - export interface CompileErrorOp { type: 'Error'; op: ErrorOpcode.Error; @@ -319,14 +268,7 @@ export interface CompileErrorOp { }; } -export type HighLevelBuilderOp = - | LabelOp - | OptionOp - | JitCompileBlockOp - | StartLabelsOp - | StopLabelsOp - | GetComponentLayoutOp - | SetBlockOp; +export type HighLevelBuilderOp = LabelOp | OptionOp | StartLabelsOp | StopLabelsOp; export type HighLevelBuilderOperands = [HighLevelBuilderOp['op1']]; @@ -350,11 +292,6 @@ export interface NestedExpressionCompileActions export type ExpressionCompileActions = NestedExpressionCompileActions | ExpressionCompileAction; -export const enum CompileMode { - aot = 'aot', - jit = 'jit', -} - export interface EncoderError { problem: string; span: { diff --git a/packages/@glimmer/interfaces/lib/compile/macros.d.ts b/packages/@glimmer/interfaces/lib/compile/macros.d.ts index 9be144beb6..0919ae85f8 100644 --- a/packages/@glimmer/interfaces/lib/compile/macros.d.ts +++ b/packages/@glimmer/interfaces/lib/compile/macros.d.ts @@ -2,7 +2,7 @@ import * as WireFormat from './wire-format'; import { NamedBlocks, ContainingMetadata, Unhandled } from '../template'; import { TemplateCompilationContext } from '../program'; import { StatementCompileActions } from './encoder'; -import { CompileTimeResolverDelegate } from '../serialize'; +import { CompileTimeResolver } from '../serialize'; import { Option } from '../core'; export interface Macros { @@ -11,7 +11,7 @@ export interface Macros { } export interface MacroContext { - resolver: CompileTimeResolverDelegate; + resolver: CompileTimeResolver; meta: ContainingMetadata; } diff --git a/packages/@glimmer/interfaces/lib/components/component-manager.d.ts b/packages/@glimmer/interfaces/lib/components/component-manager.d.ts index 16f3934c45..b0a83c5ef6 100644 --- a/packages/@glimmer/interfaces/lib/components/component-manager.d.ts +++ b/packages/@glimmer/interfaces/lib/components/component-manager.d.ts @@ -8,7 +8,7 @@ import { Bounds } from '../dom/bounds'; import { VMArguments } from '../runtime/arguments'; import { ElementOperations } from '../runtime/element'; import { Environment } from '../runtime/environment'; -import { RuntimeResolverDelegate, JitRuntimeResolver, RuntimeResolver } from '../serialize'; +import { RuntimeResolver } from '../serialize'; import { CompilableProgram, Template } from '../template'; import { ProgramSymbolTable } from '../tier1/symbol-table'; import { DynamicScope } from '../runtime/scope'; @@ -79,34 +79,15 @@ export interface WithUpdateHook update(state: ComponentInstanceState, dynamicScope: Option): void; } -export interface WithAotStaticLayout< +export interface WithStaticLayout< I = ComponentInstanceState, D = ComponentDefinitionState, - R extends RuntimeResolverDelegate = RuntimeResolverDelegate -> extends ComponentManager { - getAotStaticLayout(state: D, resolver: R): Invocation; -} - -export interface WithJitStaticLayout< - I = ComponentInstanceState, - D = ComponentDefinitionState, - R extends JitRuntimeResolver = JitRuntimeResolver + R extends RuntimeResolver = RuntimeResolver > extends ComponentManager { - getJitStaticLayout(state: D, resolver: R): CompilableProgram; -} - -export interface WithJitDynamicLayout< - I = ComponentInstanceState, - R extends RuntimeResolverDelegate = RuntimeResolverDelegate -> extends ComponentManager { - // Return the compiled layout to use for this component. This is called - // *after* the component instance has been created, because you might - // want to return a different layout per-instance for optimization reasons - // or to implement features like Ember's "late-bound" layouts. - getJitDynamicLayout(component: I, resolver: R): Template; + getStaticLayout(state: D, resolver: R): CompilableProgram; } -export interface WithAotDynamicLayout< +export interface WithDynamicLayout< I = ComponentInstanceState, R extends RuntimeResolver = RuntimeResolver > extends ComponentManager { @@ -114,7 +95,7 @@ export interface WithAotDynamicLayout< // *after* the component instance has been created, because you might // want to return a different layout per-instance for optimization reasons // or to implement features like Ember's "late-bound" layouts. - getAotDynamicLayout(component: I, resolver: R): Invocation; + getDynamicLayout(component: I, resolver: R): Template; } export interface WithDynamicTagName diff --git a/packages/@glimmer/interfaces/lib/program.d.ts b/packages/@glimmer/interfaces/lib/program.d.ts index 0251cd6ece..e43f8a3351 100644 --- a/packages/@glimmer/interfaces/lib/program.d.ts +++ b/packages/@glimmer/interfaces/lib/program.d.ts @@ -1,7 +1,7 @@ import { STDLib, ContainingMetadata, HandleResult } from './template'; -import { StdlibOperand, CompileMode, Encoder, Macros } from './compile'; +import { StdlibOperand, Encoder, Macros } from './compile'; import { Op } from './vm-opcodes'; -import { CompileTimeResolverDelegate } from './serialize'; +import { CompileTimeResolver } from './serialize'; export interface RuntimeOp { offset: number; @@ -44,7 +44,7 @@ export interface RuntimeHeap extends OpcodeHeap { scopesizeof(handle: number): number; } -export interface WholeProgramCompilationContext { +export interface CompileTimeCompilationContext { // The offsets to stdlib functions readonly stdlib: STDLib; @@ -52,13 +52,10 @@ export interface WholeProgramCompilationContext { readonly constants: CompileTimeConstants; // The mechanism of resolving names to values at compile-time - readonly resolverDelegate: CompileTimeResolverDelegate; + readonly resolver: CompileTimeResolver; // The heap that the program is serializing into readonly heap: CompileTimeHeap; - - // The mode: AOT or JIT - readonly mode: CompileMode; } /** @@ -68,7 +65,7 @@ export interface WholeProgramCompilationContext { * of templates that use different macros. */ export interface SyntaxCompilationContext { - readonly program: WholeProgramCompilationContext; + readonly program: CompileTimeCompilationContext; readonly macros: Macros; } @@ -113,12 +110,7 @@ export interface RuntimeConstants { getSerializable(handle: number): T; } -export interface JitProgramCompilationContext extends WholeProgramCompilationContext { - readonly constants: CompileTimeConstants & RuntimeConstants; - readonly heap: CompileTimeHeap & RuntimeHeap; -} - -export interface JitSyntaxCompilationContext extends SyntaxCompilationContext { - readonly program: JitProgramCompilationContext; - readonly macros: Macros; +export interface CompileTimeArtifacts { + heap: CompileTimeHeap; + constants: CompileTimeConstants; } diff --git a/packages/@glimmer/interfaces/lib/runtime/arguments.d.ts b/packages/@glimmer/interfaces/lib/runtime/arguments.d.ts index 12d3b33dc6..5488511436 100644 --- a/packages/@glimmer/interfaces/lib/runtime/arguments.d.ts +++ b/packages/@glimmer/interfaces/lib/runtime/arguments.d.ts @@ -3,7 +3,7 @@ import { Reference } from '@glimmer/reference'; // eslint-disable-next-line node/no-extraneous-import import { Tag } from '@glimmer/validator'; import { Dict, Option } from '../core'; -import { ScopeBlock, JitOrAotBlock } from './scope'; +import { ScopeBlock, Block } from './scope'; declare const CAPTURED_ARGS: unique symbol; @@ -40,11 +40,11 @@ export interface NamedArguments { capture(): CapturedNamedArguments; } -export interface BlockArguments { +export interface BlockArguments { names: string[]; length: number; has(name: string): boolean; - get(name: string): Option>; + get(name: string): Option; capture(): CapturedBlockArguments; } diff --git a/packages/@glimmer/interfaces/lib/runtime/runtime.d.ts b/packages/@glimmer/interfaces/lib/runtime/runtime.d.ts index a1599cfd45..c1012b41f3 100644 --- a/packages/@glimmer/interfaces/lib/runtime/runtime.d.ts +++ b/packages/@glimmer/interfaces/lib/runtime/runtime.d.ts @@ -1,6 +1,6 @@ import { Environment } from './environment'; import { RuntimeHeap, RuntimeConstants, RuntimeOp } from '../program'; -import { RuntimeResolver, JitRuntimeResolver, AotRuntimeResolver } from '../serialize'; +import { RuntimeResolver } from '../serialize'; /** The Runtime is the set of static structures that contain the compiled @@ -15,19 +15,14 @@ export interface RuntimeContext { resolver: RuntimeResolver; } -export interface AotRuntimeContext { - env: Environment; - program: RuntimeProgram; - resolver: AotRuntimeResolver; -} - -export interface JitRuntimeContext extends RuntimeContext { - resolver: JitRuntimeResolver; -} - export interface RuntimeProgram { readonly constants: RuntimeConstants; readonly heap: RuntimeHeap; opcode(offset: number): RuntimeOp; } + +export interface RuntimeArtifacts { + readonly constants: RuntimeConstants; + readonly heap: RuntimeHeap; +} diff --git a/packages/@glimmer/interfaces/lib/runtime/scope.d.ts b/packages/@glimmer/interfaces/lib/runtime/scope.d.ts index 159c89db46..9c6e099fbc 100644 --- a/packages/@glimmer/interfaces/lib/runtime/scope.d.ts +++ b/packages/@glimmer/interfaces/lib/runtime/scope.d.ts @@ -4,46 +4,32 @@ import { Reference } from '@glimmer/reference'; import { Option, Dict } from '../core'; import { BlockSymbolTable } from '../tier1/symbol-table'; -export type JitOrAotBlock = CompilableBlock | number; +export type Block = CompilableBlock | number; -export type JitScopeBlock = [CompilableBlock, Scope, BlockSymbolTable]; -export type JitBlockValue = JitScopeBlock[0 | 1 | 2]; -export type JitScopeSlot = Option | Option; +export type ScopeBlock = [CompilableBlock, Scope, BlockSymbolTable]; +export type BlockValue = ScopeBlock[0 | 1 | 2]; +export type ScopeSlot = Reference | ScopeBlock | null; -export type AotScopeBlock = [number, Scope, BlockSymbolTable]; -export type AotBlockValue = AotScopeBlock[0 | 1 | 2]; -export type AotScopeSlot = Option | Option; - -export type ScopeBlock = C extends CompilableBlock - ? JitScopeBlock - : AotScopeBlock; - -export type BlockValue = C extends CompilableBlock - ? JitBlockValue - : AotBlockValue; - -export type ScopeSlot = Option | Reference>; - -export interface Scope { +export interface Scope { // for debug only - readonly slots: Array>; + readonly slots: Array; getSelf(): Reference; getSymbol(symbol: number): Reference; - getBlock(symbol: number): Option>; - getEvalScope(): Option>>; + getBlock(symbol: number): Option; + getEvalScope(): Option>; getPartialMap(): Option>; - bind(symbol: number, value: ScopeSlot): void; + bind(symbol: number, value: ScopeSlot): void; bindSelf(self: Reference): void; bindSymbol(symbol: number, value: Reference): void; - bindBlock(symbol: number, value: Option>): void; - bindEvalScope(map: Option>>): void; + bindBlock(symbol: number, value: Option): void; + bindEvalScope(map: Option>): void; bindPartialMap(map: Dict): void; - child(): Scope; + child(): Scope; } -export interface PartialScope extends Scope { - bindEvalScope(scope: Option>>): void; +export interface PartialScope extends Scope { + bindEvalScope(scope: Option>): void; } export interface DynamicScope { diff --git a/packages/@glimmer/interfaces/lib/serialize.d.ts b/packages/@glimmer/interfaces/lib/serialize.d.ts index 3110a5559b..bf3d08f3d9 100644 --- a/packages/@glimmer/interfaces/lib/serialize.d.ts +++ b/packages/@glimmer/interfaces/lib/serialize.d.ts @@ -74,7 +74,7 @@ export interface CompileTimeComponent { compilable: Option; } -export interface CompileTimeResolverDelegate extends HandleResolver { +export interface CompileTimeResolver extends HandleResolver { lookupHelper(name: string, referrer: M): Option; lookupModifier(name: string, referrer: M): Option; lookupComponent(name: string, referrer: M): Option; @@ -98,25 +98,5 @@ export interface RuntimeResolver extends HandleResolver { lookupComponent(name: string, referrer?: Option): Option; lookupPartial(name: string, referrer?: Option): Option; resolve(handle: number): U; -} - -export interface JitRuntimeResolver extends RuntimeResolver { compilable(locator: R): Template; } - -export interface AotRuntimeResolver extends RuntimeResolver { - // for {{component}} support - getInvocation(locator: R): Invocation; -} - -export interface RuntimeResolverDelegate { - lookupComponent?(name: string, referrer?: Option): Option | void; - lookupPartial?(name: string, referrer?: Option): Option | void; - resolve?(handle: number): ResolvedValue | void; - compilable?(locator: R): Template; - getInvocation?(locator: R): Invocation; -} - -export interface JitRuntimeResolverOptions extends RuntimeResolverDelegate { - compilable?(locator: R): Template; -} diff --git a/packages/@glimmer/interfaces/lib/template.d.ts b/packages/@glimmer/interfaces/lib/template.d.ts index 3efdfc3e85..2c2ebd98da 100644 --- a/packages/@glimmer/interfaces/lib/template.d.ts +++ b/packages/@glimmer/interfaces/lib/template.d.ts @@ -1,9 +1,9 @@ import { Operand, SerializedTemplateBlock, SerializedInlineBlock } from './compile'; -import { CompileMode, EncoderError } from './compile/encoder'; +import { EncoderError } from './compile/encoder'; import ComponentCapabilities from './component-capabilities'; import { Option } from './core'; import { ConstantPool, SerializedHeap, SyntaxCompilationContext } from './program'; -import { CompileTimeResolverDelegate } from './serialize'; +import { CompileTimeResolver } from './serialize'; import { BlockSymbolTable, ProgramSymbolTable, SymbolTable } from './tier1/symbol-table'; export type CompilableProgram = CompilableTemplate; @@ -110,11 +110,6 @@ export interface CompilerArtifacts { constants: ConstantPool; } -export interface CompileTime { - readonly resolver: CompileTimeResolverDelegate; - readonly mode: CompileMode; -} - export interface Unhandled { 'not-handled': true; } diff --git a/packages/@glimmer/interfaces/lib/vm-opcodes.d.ts b/packages/@glimmer/interfaces/lib/vm-opcodes.d.ts index 0da1309ba2..060e65aad3 100644 --- a/packages/@glimmer/interfaces/lib/vm-opcodes.d.ts +++ b/packages/@glimmer/interfaces/lib/vm-opcodes.d.ts @@ -16,12 +16,11 @@ export const enum Op { SetNamedVariables = 17, SetBlocks = 18, SetVariable = 19, - SetAotBlock = 20, - SetJitBlock = 21, + SetBlock = 21, GetVariable = 22, GetProperty = 23, GetBlock = 24, - JitSpreadBlock = 25, + SpreadBlock = 25, HasBlock = 26, HasBlockParams = 27, Concat = 28, @@ -88,8 +87,7 @@ export const enum Op { PutComponentOperations = 89, GetComponentSelf = 90, GetComponentTagName = 91, - GetAotComponentLayout = 92, - GetJitComponentLayout = 93, + GetComponentLayout = 93, BindEvalScope = 94, SetupForEval = 95, PopulateLayout = 96, diff --git a/packages/@glimmer/opcode-compiler/lib/opcode-builder/context.ts b/packages/@glimmer/opcode-compiler/lib/opcode-builder/context.ts index f54fbedc37..18aacc33b3 100644 --- a/packages/@glimmer/opcode-compiler/lib/opcode-builder/context.ts +++ b/packages/@glimmer/opcode-compiler/lib/opcode-builder/context.ts @@ -1,53 +1,21 @@ import { + CompileTimeResolver, ContainingMetadata, SyntaxCompilationContext, TemplateCompilationContext, - JitSyntaxCompilationContext, - WholeProgramCompilationContext, - CompileMode, + CompileTimeArtifacts, } from '@glimmer/interfaces'; import { EncoderImpl } from './encoder'; import { MacrosImpl } from '../syntax/macros'; -import { ProgramCompilationContext, JitProgramCompilationContext } from '../program-context'; -import { DefaultCompileTimeResolverDelegate, ResolverDelegate } from './delegate'; +import { CompileTimeCompilationContextImpl } from '../program-context'; export function syntaxCompilationContext( - program: WholeProgramCompilationContext, - macros: MacrosImpl -): SyntaxCompilationContext { - return { - program, - macros, - }; -} - -export function Context( - resolver: ResolverDelegate = {}, - mode: CompileMode = CompileMode.aot, - macros = new MacrosImpl() -) { - return { - program: new ProgramCompilationContext(new DefaultCompileTimeResolverDelegate(resolver), mode), - macros, - }; -} - -export function JitContext( - resolver: ResolverDelegate = {}, + artifacts: CompileTimeArtifacts, + resolver: CompileTimeResolver, macros = new MacrosImpl() -): JitSyntaxCompilationContext { - return { - program: new JitProgramCompilationContext(new DefaultCompileTimeResolverDelegate(resolver)), - macros, - }; -} - -export function AotContext(resolver: ResolverDelegate = {}, macros = new MacrosImpl()) { +): SyntaxCompilationContext { return { - program: new ProgramCompilationContext( - new DefaultCompileTimeResolverDelegate(resolver), - CompileMode.aot - ), + program: new CompileTimeCompilationContextImpl(artifacts, resolver), macros, }; } diff --git a/packages/@glimmer/opcode-compiler/lib/opcode-builder/delegate.ts b/packages/@glimmer/opcode-compiler/lib/opcode-builder/delegate.ts index 2c0d4d6dd3..7aaeac68d2 100644 --- a/packages/@glimmer/opcode-compiler/lib/opcode-builder/delegate.ts +++ b/packages/@glimmer/opcode-compiler/lib/opcode-builder/delegate.ts @@ -1,9 +1,4 @@ -import { - CompileTimeResolverDelegate, - ComponentCapabilities, - Option, - CompileTimeComponent, -} from '@glimmer/interfaces'; +import { ComponentCapabilities, Option, CompileTimeComponent } from '@glimmer/interfaces'; export const DEFAULT_CAPABILITIES: ComponentCapabilities = { dynamicLayout: true, @@ -44,96 +39,3 @@ export interface ResolverDelegate { // For debugging resolve?(handle: number): R; } - -export class DefaultCompileTimeResolverDelegate implements CompileTimeResolverDelegate { - constructor(private inner: ResolverDelegate) {} - - lookupHelper(name: string, referrer: unknown): Option { - if (this.inner.lookupHelper) { - let helper = this.inner.lookupHelper(name, referrer); - - if (helper === undefined) { - throw new Error( - `Unexpected helper (${name} from ${JSON.stringify( - referrer - )}) (lookupHelper returned undefined)` - ); - } - - return helper; - } else { - throw new Error( - `Can't compile global helper invocations without an implementation of lookupHelper` - ); - } - } - - lookupModifier(name: string, referrer: unknown): Option { - if (this.inner.lookupModifier) { - let modifier = this.inner.lookupModifier(name, referrer); - - if (modifier === undefined) { - throw new Error( - `Unexpected modifier (${name} from ${JSON.stringify( - referrer - )}) (lookupModifier returned undefined)` - ); - } - - return modifier; - } else { - throw new Error( - `Can't compile global modifier invocations without an implementation of lookupModifier` - ); - } - } - - lookupComponent(name: string, referrer: unknown): Option { - if (this.inner.lookupComponent) { - let component = this.inner.lookupComponent(name, referrer); - - if (component === undefined) { - throw new Error( - `Unexpected component (${name} from ${JSON.stringify( - referrer - )}) (lookupComponent returned undefined)` - ); - } - - return component; - } else { - throw new Error( - `Can't compile global component invocations without an implementation of lookupComponent` - ); - } - } - - lookupPartial(name: string, referrer: unknown): Option { - if (this.inner.lookupPartial) { - let partial = this.inner.lookupPartial(name, referrer); - - if (partial === undefined) { - throw new Error( - `Unexpected partial (${name} from ${JSON.stringify( - referrer - )}) (lookupPartial returned undefined)` - ); - } - - return partial; - } else { - throw new Error( - `Can't compile global partial invocations without an implementation of lookupPartial` - ); - } - } - - // For debugging - resolve(handle: number): unknown { - if (this.inner.resolve) { - return this.inner.resolve(handle); - } else { - throw new Error(`Compile-time debugging requires an implementation of resolve`); - } - } -} diff --git a/packages/@glimmer/opcode-compiler/lib/opcode-builder/encoder.ts b/packages/@glimmer/opcode-compiler/lib/opcode-builder/encoder.ts index fe85e44a8c..8f69f6ceea 100644 --- a/packages/@glimmer/opcode-compiler/lib/opcode-builder/encoder.ts +++ b/packages/@glimmer/opcode-compiler/lib/opcode-builder/encoder.ts @@ -231,25 +231,13 @@ function constant( } function isSimpleOpcode(op: AllOpcode): op is HighLevelBuilderOpcode { - return ( - op === 'Label' || - op === 'Option' || - op === 'GetComponentLayout' || - op === 'StartLabels' || - op === 'StopLabels' || - op === 'SimpleArgs' || - op === 'JitCompileBlock' || - op === 'SetBlock' - ); + return op === 'Label' || op === 'Option' || op === 'StartLabels' || op === 'StopLabels'; } function isCompileOpcode(op: AllOpcode): op is HighLevelCompileOpcode { return ( op === 'CompileInline' || op === 'CompileBlock' || - op === 'InvokeStatic' || - op === 'PushCompilable' || - op === 'Args' || op === 'IfResolvedComponent' || op === 'DynamicComponent' ); diff --git a/packages/@glimmer/opcode-compiler/lib/opcode-builder/helpers/blocks.ts b/packages/@glimmer/opcode-compiler/lib/opcode-builder/helpers/blocks.ts index 66a9ad9097..210675df01 100644 --- a/packages/@glimmer/opcode-compiler/lib/opcode-builder/helpers/blocks.ts +++ b/packages/@glimmer/opcode-compiler/lib/opcode-builder/helpers/blocks.ts @@ -7,11 +7,12 @@ import { StatementCompileActions, SymbolTable, WireFormat, + CompilableTemplate, } from '@glimmer/interfaces'; import { $fp } from '@glimmer/vm'; import { op } from '../encoder'; import { PushPrimitive } from './vm'; -import { serializable } from '../operands'; +import { serializable, other } from '../operands'; /** * Yield to a block located at a particular symbol location. @@ -26,8 +27,8 @@ export function YieldBlock( return [ op('SimpleArgs', { params, hash: null, atNames: true }), op(Op.GetBlock, to), - op(Op.JitSpreadBlock), - op('Option', op('JitCompileBlock')), + op(Op.SpreadBlock), + op('Option', op(Op.CompileBlock)), op(Op.InvokeYield), op(Op.PopScope), op(MachineOp.PopFrame), @@ -44,7 +45,7 @@ export function PushYieldableBlock(block: Option): StatementCom return [ PushSymbolTable(block && block.symbolTable), op(Op.PushBlockScope), - op('PushCompilable', block), + PushCompilable(block), ]; } @@ -56,8 +57,8 @@ export function PushYieldableBlock(block: Option): StatementCom export function InvokeStaticBlock(block: CompilableBlock): StatementCompileActions { return [ op(MachineOp.PushFrame), - op('PushCompilable', block), - op('JitCompileBlock'), + PushCompilable(block), + op(Op.CompileBlock), op(MachineOp.InvokeVirtual), op(MachineOp.PopFrame), ]; @@ -95,8 +96,8 @@ export function InvokeStaticBlockWithStack( } } - out.push(op('PushCompilable', block)); - out.push(op('JitCompileBlock')); + out.push(PushCompilable(block)); + out.push(op(Op.CompileBlock)); out.push(op(MachineOp.InvokeVirtual)); if (count) { @@ -115,3 +116,11 @@ export function PushSymbolTable(table: Option): BuilderOp { return PushPrimitive(null); } } + +export function PushCompilable(block: Option): BuilderOp { + if (block === null) { + return PushPrimitive(null); + } else { + return op(Op.Constant, other(block)); + } +} diff --git a/packages/@glimmer/opcode-compiler/lib/opcode-builder/helpers/components.ts b/packages/@glimmer/opcode-compiler/lib/opcode-builder/helpers/components.ts index 6ed6c23cd4..8e91735c0a 100644 --- a/packages/@glimmer/opcode-compiler/lib/opcode-builder/helpers/components.ts +++ b/packages/@glimmer/opcode-compiler/lib/opcode-builder/helpers/components.ts @@ -17,11 +17,17 @@ import { CompileTimeComponent, } from '@glimmer/interfaces'; -import { label, templateMeta } from '../operands'; +import { label, templateMeta, other } from '../operands'; import { resolveLayoutForTag } from '../../resolver'; import { $s0, $sp, $s1, $v0, SavedRegister } from '@glimmer/vm'; -import { meta } from './shared'; -import { YieldBlock, PushSymbolTable, InvokeStaticBlock, PushYieldableBlock } from './blocks'; +import { meta, CompileArgs } from './shared'; +import { + YieldBlock, + PushSymbolTable, + InvokeStaticBlock, + PushYieldableBlock, + PushCompilable, +} from './blocks'; import { Replayable } from './conditional'; import { EMPTY_ARRAY } from '@glimmer/util'; import { op } from '../encoder'; @@ -219,13 +225,13 @@ export function InvokeStaticComponent({ let { symbol, isBlock } = bindings[i]; if (isBlock) { - out.push(op('SetBlock', symbol)); + out.push(op(Op.SetBlock, symbol)); } else { out.push(op(Op.SetVariable, symbol)); } } - out.push(op('InvokeStatic', layout)); + out.push([op(Op.Constant, other(layout)), op(Op.CompileBlock), op(MachineOp.InvokeVirtual)]); if (capabilities.createInstance) { out.push(op(Op.DidRenderLayout, $s0)); @@ -360,19 +366,15 @@ export function InvokeComponent({ op(Op.Load, $s0), op(MachineOp.PushFrame), - op('Args', { params, hash, blocks, atNames }), + CompileArgs({ params, hash, blocks, atNames }), op(Op.PrepareArgs, $s0), invokePreparedComponent(blocks.has('default'), bindableBlocks, bindableAtNames, () => { let out: NestedStatementCompileActions; if (layout) { - out = [ - PushSymbolTable(layout.symbolTable), - op('PushCompilable', layout), - op('JitCompileBlock'), - ]; + out = [PushSymbolTable(layout.symbolTable), PushCompilable(layout), op(Op.CompileBlock)]; } else { - out = [op('GetComponentLayout', $s0)]; + out = [op(Op.GetComponentLayout, $s0)]; } out.push(op(Op.PopulateLayout, $s0)); @@ -437,7 +439,7 @@ export function InvokeBareComponent(): CompileActions { op(Op.PushEmptyArgs), op(Op.PrepareArgs, $s0), invokePreparedComponent(false, false, true, () => [ - op('GetComponentLayout', $s0), + op(Op.GetComponentLayout, $s0), op(Op.PopulateLayout, $s0), ]), op(Op.Load, $s0), diff --git a/packages/@glimmer/opcode-compiler/lib/opcode-builder/helpers/stdlib.ts b/packages/@glimmer/opcode-compiler/lib/opcode-builder/helpers/stdlib.ts index 30c830b6fe..9be441b77d 100644 --- a/packages/@glimmer/opcode-compiler/lib/opcode-builder/helpers/stdlib.ts +++ b/packages/@glimmer/opcode-compiler/lib/opcode-builder/helpers/stdlib.ts @@ -7,7 +7,7 @@ import { ContentType, Op, CompileActions, - WholeProgramCompilationContext, + CompileTimeCompilationContext, TemplateCompilationContext, } from '@glimmer/interfaces'; import { ContentTypeSwitchCases } from './conditional'; @@ -50,7 +50,7 @@ export function StdAppend(trusting: boolean): CompileActions { ]; } -export function compileStd(context: WholeProgramCompilationContext): StdLib { +export function compileStd(context: CompileTimeCompilationContext): StdLib { let mainHandle = build(context, main); let trustingGuardedAppend = build(context, () => StdAppend(true)); let cautiousGuardedAppend = build(context, () => StdAppend(false)); @@ -68,7 +68,7 @@ const STDLIB_META = { size: 0, }; -function build(program: WholeProgramCompilationContext, callback: () => CompileActions): number { +function build(program: CompileTimeCompilationContext, callback: () => CompileActions): number { let encoder = new EncoderImpl(); let macros = new MacrosImpl(); diff --git a/packages/@glimmer/opcode-compiler/lib/opcode-builder/operands.ts b/packages/@glimmer/opcode-compiler/lib/opcode-builder/operands.ts index c45d20f06f..fa5e191b7b 100644 --- a/packages/@glimmer/opcode-compiler/lib/opcode-builder/operands.ts +++ b/packages/@glimmer/opcode-compiler/lib/opcode-builder/operands.ts @@ -1,6 +1,4 @@ import { - ArgsOperand, - ArgsOptions, ArrayOperand, CompileActions, ExpressionOperand, @@ -47,10 +45,6 @@ export function label(value: string): LabelOperand { return { type: 'label', value }; } -export function args(options: ArgsOptions): ArgsOperand { - return { type: 'args', value: options }; -} - export function option(list: Option): OptionOperand { return { type: 'option', value: list }; } diff --git a/packages/@glimmer/opcode-compiler/lib/program-context.ts b/packages/@glimmer/opcode-compiler/lib/program-context.ts index 7cce24e45f..c37de7e0ec 100644 --- a/packages/@glimmer/opcode-compiler/lib/program-context.ts +++ b/packages/@glimmer/opcode-compiler/lib/program-context.ts @@ -1,37 +1,21 @@ import { - WholeProgramCompilationContext, - CompileTimeResolverDelegate, - CompileTimeHeap, - CompileMode, STDLib, - RuntimeHeap, + CompileTimeCompilationContext, + CompileTimeResolver, + CompileTimeHeap, CompileTimeConstants, - RuntimeConstants, + CompileTimeArtifacts, } from '@glimmer/interfaces'; -import { WriteOnlyConstants, HeapImpl, JitConstants } from '@glimmer/program'; import { compileStd } from './opcode-builder/helpers/stdlib'; -export class ProgramCompilationContext implements WholeProgramCompilationContext { - readonly constants = new WriteOnlyConstants(); - readonly resolverDelegate: CompileTimeResolverDelegate; - readonly heap: CompileTimeHeap = new HeapImpl(); - readonly stdlib: STDLib; - - constructor(delegate: CompileTimeResolverDelegate, readonly mode: CompileMode) { - this.resolverDelegate = delegate; - this.stdlib = compileStd(this); - } -} - -export class JitProgramCompilationContext implements JitProgramCompilationContext { - readonly constants: CompileTimeConstants & RuntimeConstants = new JitConstants(); - readonly resolverDelegate: CompileTimeResolverDelegate; - readonly heap: CompileTimeHeap & RuntimeHeap = new HeapImpl(); +export class CompileTimeCompilationContextImpl implements CompileTimeCompilationContext { + readonly constants: CompileTimeConstants; + readonly heap: CompileTimeHeap; readonly stdlib: STDLib; - readonly mode: CompileMode = CompileMode.jit; - constructor(delegate: CompileTimeResolverDelegate) { - this.resolverDelegate = delegate; + constructor({ constants, heap }: CompileTimeArtifacts, readonly resolver: CompileTimeResolver) { + this.constants = constants; + this.heap = heap; this.stdlib = compileStd(this); } } diff --git a/packages/@glimmer/opcode-compiler/lib/syntax/expressions.ts b/packages/@glimmer/opcode-compiler/lib/syntax/expressions.ts index e1dde5dbea..b760031624 100644 --- a/packages/@glimmer/opcode-compiler/lib/syntax/expressions.ts +++ b/packages/@glimmer/opcode-compiler/lib/syntax/expressions.ts @@ -149,7 +149,7 @@ EXPRESSIONS.add(SexpOpcodes.HasBlock, ([, block]) => { EXPRESSIONS.add(SexpOpcodes.HasBlockParams, ([, block]) => [ op('Expr', block), - op(Op.JitSpreadBlock), - op('JitCompileBlock'), + op(Op.SpreadBlock), + op(Op.CompileBlock), op(Op.HasBlockParams), ]); diff --git a/packages/@glimmer/opcode-compiler/lib/syntax/macros.ts b/packages/@glimmer/opcode-compiler/lib/syntax/macros.ts index 328ded58da..ed07ea4ffc 100644 --- a/packages/@glimmer/opcode-compiler/lib/syntax/macros.ts +++ b/packages/@glimmer/opcode-compiler/lib/syntax/macros.ts @@ -7,7 +7,7 @@ import { Option, Unhandled, SexpOpcodes, - CompileTimeResolverDelegate, + CompileTimeResolver, ContainingMetadata, MacroBlocks, MacroInlines, @@ -29,7 +29,7 @@ export class MacrosImpl implements Macros { } export interface MacroContext { - resolver: CompileTimeResolverDelegate; + resolver: CompileTimeResolver; meta: ContainingMetadata; } @@ -72,7 +72,7 @@ export class Blocks implements MacroBlocks { let index = this.names[name]; let macroContext = { - resolver: context.syntax.program.resolverDelegate, + resolver: context.syntax.program.resolver, meta: context.meta, }; @@ -158,7 +158,7 @@ export class Inlines implements MacroInlines { let index = this.names[name]; let macroContext = { - resolver: context.syntax.program.resolverDelegate, + resolver: context.syntax.program.resolver, meta: context.meta, }; diff --git a/packages/@glimmer/opcode-compiler/lib/syntax/push-builder.ts b/packages/@glimmer/opcode-compiler/lib/syntax/push-builder.ts index 1852b9fddc..fbb213f54a 100644 --- a/packages/@glimmer/opcode-compiler/lib/syntax/push-builder.ts +++ b/packages/@glimmer/opcode-compiler/lib/syntax/push-builder.ts @@ -1,27 +1,19 @@ import { HighLevelBuilderOp, HighLevelBuilderOpcode, - CompileMode, - Op, OptionOp, CompileActions, - CompileAction, TemplateCompilationContext, } from '@glimmer/interfaces'; import { exhausted } from '@glimmer/util'; -import { op } from '../opcode-builder/encoder'; +import { op as _op } from '../opcode-builder/encoder'; import { concat, NONE } from './concat'; export default function pushBuilderOp( context: TemplateCompilationContext, op: HighLevelBuilderOp ): void { - let { - encoder, - syntax: { - program: { mode, constants }, - }, - } = context; + let { encoder } = context; switch (op.op) { case HighLevelBuilderOpcode.Option: @@ -32,13 +24,6 @@ export default function pushBuilderOp( return encoder.startLabels(); case HighLevelBuilderOpcode.StopLabels: return encoder.stopLabels(); - case HighLevelBuilderOpcode.JitCompileBlock: - return concat(context, jitCompileBlock(mode)); - case HighLevelBuilderOpcode.GetComponentLayout: - return encoder.push(constants, compileLayoutOpcode(mode), op.op1); - case HighLevelBuilderOpcode.SetBlock: - return encoder.push(constants, setBlock(mode), op.op1); - default: return exhausted(op); } @@ -49,15 +34,3 @@ function option(op: OptionOp): CompileActions { return value === null ? NONE : value; } - -function compileLayoutOpcode(mode: CompileMode): Op { - return mode === CompileMode.aot ? Op.GetAotComponentLayout : Op.GetJitComponentLayout; -} - -function jitCompileBlock(mode: CompileMode): CompileAction { - return mode === CompileMode.jit ? op(Op.CompileBlock) : NONE; -} - -function setBlock(mode: CompileMode): Op { - return mode === CompileMode.aot ? Op.SetAotBlock : Op.SetJitBlock; -} diff --git a/packages/@glimmer/opcode-compiler/lib/syntax/push-compile.ts b/packages/@glimmer/opcode-compiler/lib/syntax/push-compile.ts index 3223a26c1e..48bf7ba81b 100644 --- a/packages/@glimmer/opcode-compiler/lib/syntax/push-compile.ts +++ b/packages/@glimmer/opcode-compiler/lib/syntax/push-compile.ts @@ -1,30 +1,17 @@ -import { other } from '../opcode-builder/operands'; import { HighLevelCompileOp, HighLevelCompileOpcode, - CompileMode, - Op, - MachineOp, StatementCompileActions, - InvokeStaticOp, DynamicComponentOp, IfResolvedComponentOp, - SyntaxCompilationContext, TemplateCompilationContext, - Option, - CompilableTemplate, - BuilderOp, - CompileErrorOp, } from '@glimmer/interfaces'; -import { op } from '../opcode-builder/encoder'; -import { CompileArgs } from '../opcode-builder/helpers/shared'; -import { compilableBlock, PLACEHOLDER_HANDLE } from '../compilable-template'; +import { compilableBlock } from '../compilable-template'; import { InvokeDynamicComponent } from '../opcode-builder/helpers/components'; import { resolveLayoutForTag } from '../resolver'; import { exhausted } from '@glimmer/util'; import { concatStatements, isHandled } from './concat'; import { compileInline, compileBlock } from '../compiler'; -import { PushPrimitive } from '../opcode-builder/helpers/vm'; import { namedBlocks } from '../utils'; export default function pushCompileOp( @@ -43,12 +30,6 @@ function compileOp( return CompileBlockOp(context, action); case HighLevelCompileOpcode.CompileInline: return CompileInlineOp(context, action); - case HighLevelCompileOpcode.InvokeStatic: - return InvokeStatic(context.syntax, action); - case HighLevelCompileOpcode.Args: - return CompileArgs(action.op1); - case HighLevelCompileOpcode.PushCompilable: - return PushCompilable(action.op1, context.syntax); case HighLevelCompileOpcode.DynamicComponent: return DynamicComponent(context, action); case HighLevelCompileOpcode.IfResolvedComponent: @@ -81,33 +62,6 @@ function CompileInlineOp( } } -function InvokeStatic( - context: SyntaxCompilationContext, - action: InvokeStaticOp -): StatementCompileActions { - let compilable = action.op1; - - if (context.program.mode === CompileMode.aot) { - let handle = compilable.compile(context); - - if (typeof handle !== 'number') { - return op('Error', { problem: 'Invalid block', start: 0, end: 0 }); - } - - // If the handle for the invoked component is not yet known (for example, - // because this is a recursive invocation and we're still compiling), push a - // function that will produce the correct handle when the heap is - // serialized. - if (handle === PLACEHOLDER_HANDLE) { - return op(MachineOp.InvokeStatic, () => compilable.compile(context)); - } else { - return op(MachineOp.InvokeStatic, handle); - } - } else { - return [op(Op.Constant, other(action.op1)), op(Op.CompileBlock), op(MachineOp.InvokeVirtual)]; - } -} - function DynamicComponent( context: TemplateCompilationContext, action: DynamicComponentOp @@ -135,7 +89,7 @@ function IfResolvedComponent( ): StatementCompileActions { let { name, attrs, blocks, staticTemplate, dynamicTemplate, orElse } = action.op1; let component = resolveLayoutForTag(name, { - resolver: context.syntax.program.resolverDelegate, + resolver: context.syntax.program.resolver, meta: context.meta, }); @@ -165,26 +119,3 @@ function IfResolvedComponent( throw new Error(`Compile Error: Cannot find component ${name}`); } } - -function PushCompilable( - block: Option, - context: SyntaxCompilationContext -): BuilderOp | CompileErrorOp { - if (block === null) { - return PushPrimitive(null); - } else if (context.program.mode === CompileMode.aot) { - let compiled = block.compile(context); - - if (typeof compiled !== 'number') { - return op('Error', { - problem: 'Compile Error (TODO: thread better)', - start: 0, - end: 0, - }); - } - - return PushPrimitive(compiled); - } else { - return op(Op.Constant, other(block)); - } -} diff --git a/packages/@glimmer/opcode-compiler/lib/syntax/push-resolution.ts b/packages/@glimmer/opcode-compiler/lib/syntax/push-resolution.ts index 61248bc33a..50617c9d21 100644 --- a/packages/@glimmer/opcode-compiler/lib/syntax/push-resolution.ts +++ b/packages/@glimmer/opcode-compiler/lib/syntax/push-resolution.ts @@ -2,7 +2,7 @@ import { Encoder, HighLevelResolutionOp, HighLevelResolutionOpcode, - CompileTimeResolverDelegate, + CompileTimeResolver, ResolveHandle, Option, ExpressionCompileActions, @@ -74,7 +74,7 @@ export default function pushResolutionOp( } case ExpressionContext.AppendSingleId: { - let resolver = context.syntax.program.resolverDelegate; + let resolver = context.syntax.program.resolver; let name = context.meta.upvars![freeVar]; let resolvedHelper = resolver.lookupHelper(name, context.meta.referrer); @@ -152,12 +152,7 @@ function ifResolved( ): ExpressionCompileActions { let { kind, name, andThen, orElse, span } = op1; - let resolved = resolve( - context.syntax.program.resolverDelegate, - kind, - name, - context.meta.referrer - ); + let resolved = resolve(context.syntax.program.resolver, kind, name, context.meta.referrer); if (resolved !== null) { return andThen(resolved); @@ -169,7 +164,7 @@ function ifResolved( } function resolve( - resolver: CompileTimeResolverDelegate, + resolver: CompileTimeResolver, kind: ResolveHandle, name: string, referrer: unknown diff --git a/packages/@glimmer/opcode-compiler/test/jit-context-test.ts b/packages/@glimmer/opcode-compiler/test/jit-context-test.ts deleted file mode 100644 index d8c3ab833c..0000000000 --- a/packages/@glimmer/opcode-compiler/test/jit-context-test.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { JitContext } from '..'; - -QUnit.module('Jit Context Test'); - -QUnit.test('Jit template metas are not not stringified and parsed', (assert) => { - let context = JitContext(); - - let { constants } = context.program; - - let meta = {}; - let handle = constants.value(meta); - assert.equal(constants.getValue(handle), meta, 'Meta is not serialized'); -}); diff --git a/packages/@glimmer/program/lib/constants.ts b/packages/@glimmer/program/lib/constants.ts index bc5f9a3abe..7b2a56cb82 100644 --- a/packages/@glimmer/program/lib/constants.ts +++ b/packages/@glimmer/program/lib/constants.ts @@ -5,7 +5,7 @@ const WELL_KNOWN_EMPTY_ARRAY: unknown = Object.freeze([]); const STARTER_CONSTANTS = constants(WELL_KNOWN_EMPTY_ARRAY); const WELL_KNOWN_EMPTY_ARRAY_POSITION: number = STARTER_CONSTANTS.indexOf(WELL_KNOWN_EMPTY_ARRAY); -export class WriteOnlyConstants implements CompileTimeConstants { +export class CompileTimeConstantImpl implements CompileTimeConstants { // `0` means NULL protected values: unknown[] = STARTER_CONSTANTS.slice(); @@ -78,7 +78,7 @@ export class RuntimeConstantsImpl implements RuntimeConstants { } } -export class JitConstants extends WriteOnlyConstants implements RuntimeConstants { +export class ConstantsImpl extends CompileTimeConstantImpl implements RuntimeConstants { protected reifiedArrs: { [key: number]: unknown[] } = { [WELL_KNOWN_EMPTY_ARRAY_POSITION]: WELL_KNOWN_EMPTY_ARRAY as unknown[], }; diff --git a/packages/@glimmer/program/lib/helpers.ts b/packages/@glimmer/program/lib/helpers.ts index 1c95d2d8b8..f3d1002e76 100644 --- a/packages/@glimmer/program/lib/helpers.ts +++ b/packages/@glimmer/program/lib/helpers.ts @@ -1,20 +1,18 @@ import { - WholeProgramCompilationContext, - CompilerArtifacts, - SyntaxCompilationContext, + CompileTimeCompilationContext, + CompileTimeArtifacts, + RuntimeArtifacts, } from '@glimmer/interfaces'; +import { ConstantsImpl } from './constants'; +import { HeapImpl } from './program'; -export function patchStdlibs(program: WholeProgramCompilationContext) { +export function patchStdlibs(program: CompileTimeCompilationContext) { program.heap.patchStdlibs(program.stdlib); } -export function programArtifacts(program: WholeProgramCompilationContext): CompilerArtifacts { - let heap = program.heap.capture(program.stdlib); - let constants = program.constants.toPool(); - - return { heap, constants }; -} - -export function artifacts(syntax: SyntaxCompilationContext): CompilerArtifacts { - return programArtifacts(syntax.program); +export function artifacts(): CompileTimeArtifacts & RuntimeArtifacts { + return { + constants: new ConstantsImpl(), + heap: new HeapImpl(), + }; } diff --git a/packages/@glimmer/program/lib/program.ts b/packages/@glimmer/program/lib/program.ts index 05f7e1b083..9c926f4815 100644 --- a/packages/@glimmer/program/lib/program.ts +++ b/packages/@glimmer/program/lib/program.ts @@ -6,10 +6,8 @@ import { StdlibOperand, RuntimeConstants, RuntimeProgram, - CompilerArtifacts, } from '@glimmer/interfaces'; import { LOCAL_DEBUG } from '@glimmer/local-debug-flags'; -import { RuntimeConstantsImpl } from './constants'; import { RuntimeOpImpl } from './opcode'; import { assert } from '@glimmer/util'; @@ -295,13 +293,6 @@ export class HeapImpl implements CompileTimeHeap, RuntimeHeap { export class RuntimeProgramImpl implements RuntimeProgram { [key: number]: never; - static hydrate(artifacts: CompilerArtifacts) { - let heap = new RuntimeHeapImpl(artifacts.heap); - let constants = new RuntimeConstantsImpl(artifacts.constants); - - return new RuntimeProgramImpl(constants, heap); - } - private _opcode: RuntimeOpImpl; constructor(public constants: RuntimeConstants, public heap: RuntimeHeap) { @@ -314,13 +305,6 @@ export class RuntimeProgramImpl implements RuntimeProgram { } } -export function hydrateProgram(artifacts: CompilerArtifacts): RuntimeProgram { - let heap = new RuntimeHeapImpl(artifacts.heap); - let constants = new RuntimeConstantsImpl(artifacts.constants); - - return new RuntimeProgramImpl(constants, heap); -} - function slice(arr: Int32Array, start: number, end: number): Int32Array { if (arr.slice !== undefined) { return arr.slice(start, end); diff --git a/packages/@glimmer/program/test/artifacts-test.ts b/packages/@glimmer/program/test/artifacts-test.ts new file mode 100644 index 0000000000..79f72fd335 --- /dev/null +++ b/packages/@glimmer/program/test/artifacts-test.ts @@ -0,0 +1,11 @@ +import { artifacts } from '..'; + +QUnit.module('Artifacts Test'); + +QUnit.test('template metas are not not stringified and parsed', (assert) => { + let { constants } = artifacts(); + + let meta = {}; + let handle = constants.value(meta); + assert.equal(constants.getValue(handle), meta, 'Meta is not serialized'); +}); diff --git a/packages/@glimmer/runtime/index.ts b/packages/@glimmer/runtime/index.ts index c6e97da1cc..9da54c3203 100644 --- a/packages/@glimmer/runtime/index.ts +++ b/packages/@glimmer/runtime/index.ts @@ -27,25 +27,14 @@ export { export { normalizeProperty } from './lib/dom/props'; export { DynamicScopeImpl, PartialScopeImpl } from './lib/scope'; export { - AotRuntime, - JitRuntime, + runtimeContext, EnvironmentImpl, EnvironmentDelegate, - JitProgramCompilationContext, - JitSyntaxCompilationContext, inTransaction, } from './lib/environment'; export { default as getDynamicVar } from './lib/helpers/get-dynamic-var'; export { PublicModifierDefinition as ModifierDefinition } from './lib/modifier/interfaces'; -export { - renderAot, - renderAotComponent, - renderAotMain, - RenderComponentArgs, - renderJitComponent, - renderJitMain, - renderSync, -} from './lib/render'; +export { RenderComponentArgs, renderComponent, renderMain, renderSync } from './lib/render'; export { SafeString } from './lib/upsert'; export { InternalVM, UpdatingVM, VM as LowLevelVM } from './lib/vm'; export { diff --git a/packages/@glimmer/runtime/lib/capabilities.ts b/packages/@glimmer/runtime/lib/capabilities.ts index 0c183a8926..9a724249a5 100644 --- a/packages/@glimmer/runtime/lib/capabilities.ts +++ b/packages/@glimmer/runtime/lib/capabilities.ts @@ -4,8 +4,7 @@ import { WithUpdateHook, WithPrepareArgs, WithCreateInstance, - WithJitDynamicLayout, - WithAotDynamicLayout, + WithDynamicLayout, } from '@glimmer/interfaces'; import { check, CheckNumber } from '@glimmer/debug'; @@ -46,7 +45,7 @@ export function capabilityFlagsFrom(capabilities: ComponentCapabilities): Capabi } export interface CapabilityMap { - [Capability.DynamicLayout]: WithJitDynamicLayout | WithAotDynamicLayout; + [Capability.DynamicLayout]: WithDynamicLayout; [Capability.DynamicTag]: ComponentManager; [Capability.PrepareArgs]: WithPrepareArgs; [Capability.CreateArgs]: ComponentManager; diff --git a/packages/@glimmer/runtime/lib/compiled/opcodes/-debug-strip.ts b/packages/@glimmer/runtime/lib/compiled/opcodes/-debug-strip.ts index 4bda357a00..3afb84d3a0 100644 --- a/packages/@glimmer/runtime/lib/compiled/opcodes/-debug-strip.ts +++ b/packages/@glimmer/runtime/lib/compiled/opcodes/-debug-strip.ts @@ -20,12 +20,11 @@ import { ComponentManager, ElementOperations, Invocation, - JitOrAotBlock, Scope, Helper, CapturedArguments, Option, - JitScopeBlock, + ScopeBlock, } from '@glimmer/interfaces'; import { Reference, REFERENCE, OpaqueIterator, UNDEFINED_REFERENCE } from '@glimmer/reference'; import { Tag, COMPUTE } from '@glimmer/validator'; @@ -89,9 +88,7 @@ export const CheckCapturedArguments: Checker = CheckInterface named: wrap(() => CheckDict(CheckReference)), }); -export const CheckScope: Checker> = wrap(() => - CheckInstanceof(PartialScopeImpl) -); +export const CheckScope: Checker = wrap(() => CheckInstanceof(PartialScopeImpl)); export const CheckComponentManager: Checker> = CheckInterface({ getCapabilities: CheckFunction, @@ -130,7 +127,7 @@ export const CheckCompilableBlock: Checker = CheckInterface({ symbolTable: CheckBlockSymbolTable, }); -export const CheckScopeBlock: Checker = CheckInterface({ +export const CheckScopeBlock: Checker = CheckInterface({ 0: CheckOr(CheckHandle, CheckCompilableBlock), 1: CheckScope, 2: CheckBlockSymbolTable, diff --git a/packages/@glimmer/runtime/lib/compiled/opcodes/component.ts b/packages/@glimmer/runtime/lib/compiled/opcodes/component.ts index bb2835c85a..4aabc0e9c3 100644 --- a/packages/@glimmer/runtime/lib/compiled/opcodes/component.ts +++ b/packages/@glimmer/runtime/lib/compiled/opcodes/component.ts @@ -17,24 +17,18 @@ import { DynamicScope, ElementOperations, InternalComponentManager, - JitOrAotBlock, Maybe, Op, ProgramSymbolTable, Recast, - RuntimeResolverDelegate, ScopeSlot, VMArguments, - WithAotDynamicLayout, - WithAotStaticLayout, + WithDynamicLayout, + WithStaticLayout, WithDynamicTagName, WithElementHook, - WithJitDynamicLayout, - WithJitStaticLayout, WithUpdateHook, WithCreateInstance, - JitRuntimeResolver, - RuntimeResolver, ModifierManager, } from '@glimmer/interfaces'; import { Reference, valueForRef, isConstRef } from '@glimmer/reference'; @@ -64,6 +58,7 @@ import { resolveCurriedComponentDefinition, } from '../../component/curried-component'; import { resolveComponent } from '../../component/resolve'; +import { hasStaticLayout } from '../../component/interfaces'; import { APPEND_OPCODES, UpdatingOpcode } from '../../opcodes'; import createClassListRef from '../../references/class-list'; import createCurryComponentRef from '../../references/curry-component'; @@ -103,7 +98,7 @@ export interface ComponentInstance { state: ComponentInstanceState; handle: number; table: ProgramSymbolTable; - lookup: Option>>; + lookup: Option>; } export interface InitialComponentInstance { @@ -114,7 +109,7 @@ export interface InitialComponentInstance { state: null; handle: Option; table: Option; - lookup: Option>>; + lookup: Option>; } export interface PopulatedComponentInstance { @@ -125,7 +120,7 @@ export interface PopulatedComponentInstance { state: null; handle: number; table: Option; - lookup: Option>>; + lookup: Option>; } export interface PartialComponentDefinition { @@ -446,7 +441,7 @@ export class ComponentElementOperations implements ElementOperations { this.modifiers.push([manager, state]); } - flush(vm: InternalVM): [ModifierManager, unknown][] { + flush(vm: InternalVM): [ModifierManager, unknown][] { let type: DeferredAttribute | undefined; let attributes = this.attributes; @@ -496,7 +491,7 @@ function allStringClasses(classes: (string | Reference)[]): classes is } function setDeferredAttr( - vm: InternalVM, + vm: InternalVM, name: string, value: string | Reference, namespace: Option, @@ -548,115 +543,40 @@ APPEND_OPCODES.add(Op.GetComponentTagName, (vm, { op1: _state }) => { }); // Dynamic Invocation Only -APPEND_OPCODES.add( - Op.GetJitComponentLayout, - (vm, { op1: _state }) => { - let instance = check(vm.fetchValue(_state), CheckComponentInstance); - - let manager = instance.manager as WithJitStaticLayout | WithJitDynamicLayout; - let { definition } = instance; - let { stack } = vm; - - let { capabilities } = instance; - - // let invoke: { handle: number; symbolTable: ProgramSymbolTable }; - - let layout: CompilableTemplate; +APPEND_OPCODES.add(Op.GetComponentLayout, (vm, { op1: _state }) => { + let instance = check(vm.fetchValue(_state), CheckComponentInstance); - if (hasStaticLayoutCapability(capabilities, manager)) { - layout = manager.getJitStaticLayout(definition.state, vm.runtime.resolver); - } else if (hasDynamicLayoutCapability(capabilities, manager)) { - let template = unwrapTemplate( - manager.getJitDynamicLayout(instance.state, vm.runtime.resolver) - ); + let manager = instance.manager as WithStaticLayout | WithDynamicLayout; + let { definition } = instance; + let { stack } = vm; - if (hasCapability(capabilities, Capability.Wrapped)) { - layout = template.asWrappedLayout(); - } else { - layout = template.asLayout(); - } - } else { - throw unreachable(); - } + let { capabilities } = instance; - let handle = layout.compile(vm.context); + let layout: CompilableTemplate; - stack.pushJs(layout.symbolTable); + if (hasStaticLayout(capabilities, manager)) { + layout = manager.getStaticLayout(definition.state, vm.runtime.resolver); + } else { + let template = unwrapTemplate(manager.getDynamicLayout(instance.state, vm.runtime.resolver)); - if (DEBUG && isErrHandle(handle)) { - stack.pushJs(handle); + if (hasCapability(capabilities, Capability.Wrapped)) { + layout = template.asWrappedLayout(); } else { - stack.pushSmallInt(handle as number); + layout = template.asLayout(); } - }, - 'jit' -); - -// Dynamic Invocation Only -APPEND_OPCODES.add(Op.GetAotComponentLayout, (vm, { op1: _state }) => { - let instance = check(vm.fetchValue(_state), CheckComponentInstance); - let { manager, definition } = instance; - let { stack } = vm; - - let { state: instanceState, capabilities } = instance; - let { state: definitionState } = definition; - - let invoke: { handle: number; symbolTable: ProgramSymbolTable }; - - if (hasStaticLayoutCapability(capabilities, manager)) { - invoke = (manager as WithAotStaticLayout< - ComponentInstanceState, - ComponentDefinitionState, - RuntimeResolverDelegate - >).getAotStaticLayout(definitionState, vm.runtime.resolver); - } else if (hasDynamicLayoutCapability(capabilities, manager)) { - invoke = (manager as WithAotDynamicLayout< - ComponentInstanceState, - RuntimeResolver - >).getAotDynamicLayout(instanceState, vm.runtime.resolver); - } else { - throw unreachable(); } - stack.pushJs(invoke.symbolTable); + let handle = layout.compile(vm.context); + + stack.pushJs(layout.symbolTable); - if (DEBUG && isErrHandle(invoke.handle)) { - stack.pushJs(invoke.handle); + if (DEBUG && isErrHandle(handle)) { + stack.pushJs(handle); } else { - stack.pushSmallInt(invoke.handle); + stack.pushSmallInt(handle as number); } }); -// These types are absurd here -export function hasStaticLayoutCapability( - capabilities: Capability, - _manager: InternalComponentManager -): _manager is - | WithJitStaticLayout - | WithAotStaticLayout { - return managerHasCapability(_manager, capabilities, Capability.DynamicLayout) === false; -} - -export function hasJitStaticLayoutCapability( - capabilities: Capability, - _manager: InternalComponentManager -): _manager is WithJitStaticLayout< - ComponentInstanceState, - ComponentDefinitionState, - JitRuntimeResolver -> { - return managerHasCapability(_manager, capabilities, Capability.DynamicLayout) === false; -} - -export function hasDynamicLayoutCapability( - capabilities: Capability, - _manager: InternalComponentManager -): _manager is - | WithJitDynamicLayout - | WithAotDynamicLayout { - return managerHasCapability(_manager, capabilities, Capability.DynamicLayout) === true; -} - APPEND_OPCODES.add(Op.Main, (vm, { op1: register }) => { let definition = check(vm.stack.popJs(), CheckComponentDefinition); let invocation = check(vm.stack.popJs(), CheckInvocation); @@ -701,7 +621,7 @@ APPEND_OPCODES.add(Op.SetupForEval, (vm, { op1: _state }) => { let state = check(vm.fetchValue(_state), CheckFinishedComponentInstance); if (state.table.hasEval) { - let lookup = (state.lookup = dict>()); + let lookup = (state.lookup = dict()); vm.scope().bindEvalScope(lookup); } }); @@ -723,12 +643,12 @@ APPEND_OPCODES.add(Op.SetNamedVariables, (vm, { op1: _state }) => { } }); -function bindBlock( +function bindBlock( symbolName: string, blockName: string, state: ComponentInstance, - blocks: BlockArgumentsImpl, - vm: InternalVM + blocks: BlockArgumentsImpl, + vm: InternalVM ) { let symbol = state.table.symbols.indexOf(symbolName); let block = blocks.get(blockName); diff --git a/packages/@glimmer/runtime/lib/compiled/opcodes/debugger.ts b/packages/@glimmer/runtime/lib/compiled/opcodes/debugger.ts index 02a778e4e8..82914ec27c 100644 --- a/packages/@glimmer/runtime/lib/compiled/opcodes/debugger.ts +++ b/packages/@glimmer/runtime/lib/compiled/opcodes/debugger.ts @@ -1,4 +1,4 @@ -import { Op, JitOrAotBlock, Scope } from '@glimmer/interfaces'; +import { Op, Scope } from '@glimmer/interfaces'; import { Reference, childRefFor, valueForRef } from '@glimmer/reference'; import { dict, decodeHandle } from '@glimmer/util'; import { APPEND_OPCODES } from '../../opcodes'; @@ -30,10 +30,10 @@ export function resetDebuggerCallback() { callback = debugCallback; } -class ScopeInspector { +class ScopeInspector { private locals = dict(); - constructor(private scope: Scope, symbols: string[], evalInfo: number[]) { + constructor(private scope: Scope, symbols: string[], evalInfo: number[]) { for (let i = 0; i < evalInfo.length; i++) { let slot = evalInfo[i]; let name = symbols[slot - 1]; diff --git a/packages/@glimmer/runtime/lib/compiled/opcodes/expressions.ts b/packages/@glimmer/runtime/lib/compiled/opcodes/expressions.ts index 919860f851..baa670bf37 100644 --- a/packages/@glimmer/runtime/lib/compiled/opcodes/expressions.ts +++ b/packages/@glimmer/runtime/lib/compiled/opcodes/expressions.ts @@ -1,4 +1,4 @@ -import { Option, Op, JitScopeBlock, AotScopeBlock, VM as PublicVM } from '@glimmer/interfaces'; +import { Option, Op, ScopeBlock, VM as PublicVM } from '@glimmer/interfaces'; import { Reference, childRefFor, @@ -28,7 +28,6 @@ import { CheckScopeBlock, } from './-debug-strip'; import { CONSTANTS } from '../../symbols'; -import { DEBUG } from '@glimmer/env'; export type FunctionExpression = (vm: PublicVM) => Reference; @@ -52,27 +51,12 @@ APPEND_OPCODES.add(Op.SetVariable, (vm, { op1: symbol }) => { vm.scope().bindSymbol(symbol, expr); }); -APPEND_OPCODES.add( - Op.SetJitBlock, - (vm, { op1: symbol }) => { - let handle = check(vm.stack.popJs(), CheckOption(CheckCompilableBlock)); - let scope = check(vm.stack.popJs(), CheckScope); - let table = check(vm.stack.popJs(), CheckOption(CheckBlockSymbolTable)); - - let block: Option = table ? [handle!, scope, table] : null; - - vm.scope().bindBlock(symbol, block); - }, - 'jit' -); - -APPEND_OPCODES.add(Op.SetAotBlock, (vm, { op1: symbol }) => { - // In DEBUG handles could be ErrHandle objects - let handle = check(DEBUG ? vm.stack.pop() : vm.stack.popSmallInt(), CheckOption(CheckHandle)); +APPEND_OPCODES.add(Op.SetBlock, (vm, { op1: symbol }) => { + let handle = check(vm.stack.popJs(), CheckOption(CheckCompilableBlock)); let scope = check(vm.stack.popJs(), CheckScope); let table = check(vm.stack.popJs(), CheckOption(CheckBlockSymbolTable)); - let block: Option = table ? [handle!, scope, table] : null; + let block: Option = table ? [handle!, scope, table] : null; vm.scope().bindBlock(symbol, block); }); @@ -110,7 +94,7 @@ APPEND_OPCODES.add(Op.GetBlock, (vm, { op1: _block }) => { } }); -APPEND_OPCODES.add(Op.JitSpreadBlock, (vm) => { +APPEND_OPCODES.add(Op.SpreadBlock, (vm) => { let { stack } = vm; let block = check(stack.popJs(), CheckOption(CheckOr(CheckScopeBlock, CheckUndefinedReference))); @@ -132,7 +116,7 @@ APPEND_OPCODES.add(Op.JitSpreadBlock, (vm) => { } }); -function isUndefinedReference(input: JitScopeBlock | Reference): input is Reference { +function isUndefinedReference(input: ScopeBlock | Reference): input is Reference { assert( Array.isArray(input) || input === UNDEFINED_REFERENCE, 'a reference other than UNDEFINED_REFERENCE is illegal here' diff --git a/packages/@glimmer/runtime/lib/compiled/opcodes/partial.ts b/packages/@glimmer/runtime/lib/compiled/opcodes/partial.ts index 71b0e51689..5482ef1a5d 100644 --- a/packages/@glimmer/runtime/lib/compiled/opcodes/partial.ts +++ b/packages/@glimmer/runtime/lib/compiled/opcodes/partial.ts @@ -6,58 +6,54 @@ import { Op, Dict, PartialDefinition } from '@glimmer/interfaces'; import { CheckReference } from './-debug-strip'; import { CONSTANTS } from '../../symbols'; -APPEND_OPCODES.add( - Op.InvokePartial, - (vm, { op1: _meta, op2: _symbols, op3: _evalInfo }) => { - let { [CONSTANTS]: constants, stack } = vm; +APPEND_OPCODES.add(Op.InvokePartial, (vm, { op1: _meta, op2: _symbols, op3: _evalInfo }) => { + let { [CONSTANTS]: constants, stack } = vm; - let name = valueForRef(check(stack.pop(), CheckReference)); - assert(typeof name === 'string', `Could not find a partial named "${String(name)}"`); + let name = valueForRef(check(stack.pop(), CheckReference)); + assert(typeof name === 'string', `Could not find a partial named "${String(name)}"`); - let meta = constants.getValue(decodeHandle(_meta)); - let outerSymbols = constants.getArray(_symbols); - let evalInfo = constants.getValue(decodeHandle(_evalInfo)); + let meta = constants.getValue(decodeHandle(_meta)); + let outerSymbols = constants.getArray(_symbols); + let evalInfo = constants.getValue(decodeHandle(_evalInfo)); - let handle = vm.runtime.resolver.lookupPartial(name as string, meta); + let handle = vm.runtime.resolver.lookupPartial(name as string, meta); - assert(handle !== null, `Could not find a partial named "${name}"`); + assert(handle !== null, `Could not find a partial named "${name}"`); - let definition = vm.runtime.resolver.resolve(handle!); + let definition = vm.runtime.resolver.resolve(handle!); - let { symbolTable, handle: vmHandle } = definition.getPartial(vm.context); + let { symbolTable, handle: vmHandle } = definition.getPartial(vm.context); - { - let partialSymbols = symbolTable.symbols; - let outerScope = vm.scope(); - let partialScope = vm.pushRootScope(partialSymbols.length); - let evalScope = outerScope.getEvalScope(); - partialScope.bindEvalScope(evalScope); - partialScope.bindSelf(outerScope.getSelf()); + { + let partialSymbols = symbolTable.symbols; + let outerScope = vm.scope(); + let partialScope = vm.pushRootScope(partialSymbols.length); + let evalScope = outerScope.getEvalScope(); + partialScope.bindEvalScope(evalScope); + partialScope.bindSelf(outerScope.getSelf()); - let locals = Object.create(outerScope.getPartialMap()) as Dict; + let locals = Object.create(outerScope.getPartialMap()) as Dict; - for (let i = 0; i < evalInfo.length; i++) { - let slot = evalInfo[i]; - let name = outerSymbols[slot - 1]; - let ref = outerScope.getSymbol(slot); - locals[name] = ref; - } + for (let i = 0; i < evalInfo.length; i++) { + let slot = evalInfo[i]; + let name = outerSymbols[slot - 1]; + let ref = outerScope.getSymbol(slot); + locals[name] = ref; + } - if (evalScope) { - for (let i = 0; i < partialSymbols.length; i++) { - let name = partialSymbols[i]; - let symbol = i + 1; - let value = evalScope[name]; + if (evalScope) { + for (let i = 0; i < partialSymbols.length; i++) { + let name = partialSymbols[i]; + let symbol = i + 1; + let value = evalScope[name]; - if (value !== undefined) partialScope.bind(symbol, value); - } + if (value !== undefined) partialScope.bind(symbol, value); } + } - partialScope.bindPartialMap(locals); + partialScope.bindPartialMap(locals); - vm.pushFrame(); // sp += 2 - vm.call(unwrapHandle(vmHandle!)); - } - }, - 'jit' -); + vm.pushFrame(); // sp += 2 + vm.call(unwrapHandle(vmHandle!)); + } +}); diff --git a/packages/@glimmer/runtime/lib/compiled/opcodes/vm.ts b/packages/@glimmer/runtime/lib/compiled/opcodes/vm.ts index 11ae72f893..994ae545c1 100644 --- a/packages/@glimmer/runtime/lib/compiled/opcodes/vm.ts +++ b/packages/@glimmer/runtime/lib/compiled/opcodes/vm.ts @@ -38,7 +38,7 @@ import { UpdatingVM } from '../../vm'; import { VMArgumentsImpl } from '../../vm/arguments'; import { CheckReference, CheckScope } from './-debug-strip'; import { CONSTANTS } from '../../symbols'; -import { InternalJitVM } from '../../vm/append'; +import { InternalVM } from '../../vm/append'; APPEND_OPCODES.add(Op.ChildScope, (vm) => vm.pushChildScope()); @@ -125,20 +125,16 @@ APPEND_OPCODES.add(Op.PushBlockScope, (vm) => { stack.pushJs(vm.scope()); }); -APPEND_OPCODES.add( - Op.CompileBlock, - (vm: InternalJitVM) => { - let stack = vm.stack; - let block = stack.pop | 0>(); +APPEND_OPCODES.add(Op.CompileBlock, (vm: InternalVM) => { + let stack = vm.stack; + let block = stack.pop | 0>(); - if (block) { - stack.pushSmallInt(vm.compile(block)); - } else { - stack.pushNull(); - } - }, - 'jit' -); + if (block) { + stack.pushSmallInt(vm.compile(block)); + } else { + stack.pushNull(); + } +}); APPEND_OPCODES.add(Op.InvokeYield, (vm) => { let { stack } = vm; diff --git a/packages/@glimmer/runtime/lib/component/interfaces.ts b/packages/@glimmer/runtime/lib/component/interfaces.ts index 02c95ad72d..db41e223af 100644 --- a/packages/@glimmer/runtime/lib/component/interfaces.ts +++ b/packages/@glimmer/runtime/lib/component/interfaces.ts @@ -3,36 +3,20 @@ import { ComponentDefinitionState, ComponentInstanceState, ComponentManager, - WithAotDynamicLayout, - WithAotStaticLayout, - WithJitDynamicLayout, - WithJitStaticLayout, - JitRuntimeResolver, + WithStaticLayout, RuntimeResolver, } from '@glimmer/interfaces'; +import { hasCapability, Capability } from '../capabilities'; /** @internal */ export function hasStaticLayout< D extends ComponentDefinitionState, I extends ComponentInstanceState >( - state: D, - manager: ComponentManager -): manager is - | WithAotStaticLayout - | WithJitStaticLayout { - return manager.getCapabilities(state).dynamicLayout === false; -} - -/** @internal */ -export function hasDynamicLayout< - D extends ComponentDefinitionState, - I extends ComponentInstanceState ->( - state: D, - manager: ComponentManager -): manager is WithAotDynamicLayout | WithJitDynamicLayout { - return manager.getCapabilities(state).dynamicLayout === true; + capabilities: Capability, + _manager: ComponentManager +): _manager is WithStaticLayout { + return !hasCapability(capabilities, Capability.DynamicLayout); } export const DEFAULT_CAPABILITIES: ComponentCapabilities = { diff --git a/packages/@glimmer/runtime/lib/environment.ts b/packages/@glimmer/runtime/lib/environment.ts index d4d5285959..89318055df 100644 --- a/packages/@glimmer/runtime/lib/environment.ts +++ b/packages/@glimmer/runtime/lib/environment.ts @@ -6,25 +6,12 @@ import { GlimmerTreeConstruction, Transaction, TransactionSymbol, - CompilerArtifacts, WithCreateInstance, - ResolvedValue, - RuntimeResolverDelegate, ModifierManager, - Template, - AotRuntimeResolver, - Invocation, - JitRuntimeContext, - AotRuntimeContext, - JitRuntimeResolver, - SyntaxCompilationContext, - RuntimeConstants, - RuntimeHeap, - Macros, + RuntimeContext, + RuntimeResolver, Option, - CompileTimeConstants, - CompileTimeHeap, - WholeProgramCompilationContext, + RuntimeArtifacts, } from '@glimmer/interfaces'; import { assert, expect, symbol, debugToString } from '@glimmer/util'; import { track, updateTag } from '@glimmer/validator'; @@ -226,123 +213,16 @@ export interface EnvironmentDelegate { onTransactionCommit: () => void; } -export class DefaultRuntimeResolver implements JitRuntimeResolver, AotRuntimeResolver { - constructor(private inner: RuntimeResolverDelegate) {} - - lookupComponent(name: string, referrer?: R): Option { - if (this.inner.lookupComponent) { - let component = this.inner.lookupComponent(name, referrer); - - if (component === undefined) { - throw new Error( - `Unexpected component ${name} (from ${referrer}) (lookupComponent returned undefined)` - ); - } - - return component; - } else { - throw new Error('lookupComponent not implemented on RuntimeResolver.'); - } - } - - lookupPartial(name: string, referrer?: R): Option { - if (this.inner.lookupPartial) { - let partial = this.inner.lookupPartial(name, referrer); - - if (partial === undefined) { - throw new Error( - `Unexpected partial ${name} (from ${referrer}) (lookupPartial returned undefined)` - ); - } - - return partial; - } else { - throw new Error('lookupPartial not implemented on RuntimeResolver.'); - } - } - - resolve(handle: number): U { - if (this.inner.resolve) { - let resolved = this.inner.resolve(handle); - - if (resolved === undefined) { - throw new Error(`Unexpected handle ${handle} (resolve returned undefined)`); - } - - return resolved as U; - } else { - throw new Error('resolve not implemented on RuntimeResolver.'); - } - } - - compilable(locator: R): Template { - if (this.inner.compilable) { - let resolved = this.inner.compilable(locator); - - if (resolved === undefined) { - throw new Error(`Unable to compile ${name} (compilable returned undefined)`); - } - - return resolved; - } else { - throw new Error('compilable not implemented on RuntimeResolver.'); - } - } - - getInvocation(locator: R): Invocation { - if (this.inner.getInvocation) { - let invocation = this.inner.getInvocation(locator); - - if (invocation === undefined) { - throw new Error( - `Unable to get invocation for ${JSON.stringify( - locator - )} (getInvocation returned undefined)` - ); - } - - return invocation; - } else { - throw new Error('getInvocation not implemented on RuntimeResolver.'); - } - } -} - -export function AotRuntime( - options: EnvironmentOptions, - program: CompilerArtifacts, - resolver: RuntimeResolverDelegate = {}, - delegate: EnvironmentDelegate -): AotRuntimeContext { - let env = new EnvironmentImpl(options, delegate); - - return { - env, - resolver: new DefaultRuntimeResolver(resolver), - program: RuntimeProgramImpl.hydrate(program), - }; -} - -export interface JitProgramCompilationContext extends WholeProgramCompilationContext { - readonly constants: CompileTimeConstants & RuntimeConstants; - readonly heap: CompileTimeHeap & RuntimeHeap; -} - -export interface JitSyntaxCompilationContext extends SyntaxCompilationContext { - readonly program: JitProgramCompilationContext; - readonly macros: Macros; -} - -export function JitRuntime( +export function runtimeContext( options: EnvironmentOptions, delegate: EnvironmentDelegate, - context: JitSyntaxCompilationContext, - resolver: RuntimeResolverDelegate = {} -): JitRuntimeContext { + artifacts: RuntimeArtifacts, + resolver: RuntimeResolver +): RuntimeContext { return { env: new EnvironmentImpl(options, delegate), - program: new RuntimeProgramImpl(context.program.constants, context.program.heap), - resolver: new DefaultRuntimeResolver(resolver), + program: new RuntimeProgramImpl(artifacts.constants, artifacts.heap), + resolver: resolver, }; } diff --git a/packages/@glimmer/runtime/lib/opcode-builder.ts b/packages/@glimmer/runtime/lib/opcode-builder.ts deleted file mode 100644 index 0a4ae8a8bb..0000000000 --- a/packages/@glimmer/runtime/lib/opcode-builder.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Reference } from '@glimmer/reference'; - -import { Option } from '@glimmer/util'; - -import { RuntimeResolverDelegate, VMArguments, VM as PublicVM } from '@glimmer/interfaces'; -import { CurriedComponentDefinition } from './component/curried-component'; - -export interface DynamicComponentDefinition { - (vm: PublicVM, args: VMArguments, meta: unknown, resolver: RuntimeResolverDelegate): Reference< - Option - >; -} diff --git a/packages/@glimmer/runtime/lib/opcodes.ts b/packages/@glimmer/runtime/lib/opcodes.ts index d585dedc7d..50b530e0a3 100644 --- a/packages/@glimmer/runtime/lib/opcodes.ts +++ b/packages/@glimmer/runtime/lib/opcodes.ts @@ -3,12 +3,12 @@ import { LowLevelVM, VM, UpdatingVM } from './vm'; import { Option, initializeGuid, fillNulls, assert } from '@glimmer/util'; import { recordStackSize, opcodeMetadata } from '@glimmer/debug'; import { $pc, $sp, $ra, $fp } from '@glimmer/vm'; -import { RuntimeOp, Op, JitOrAotBlock, Maybe, Dict } from '@glimmer/interfaces'; +import { RuntimeOp, Op, Maybe, Dict } from '@glimmer/interfaces'; import { LOCAL_DEBUG, LOCAL_SHOULD_LOG } from '@glimmer/local-debug-flags'; // these import bindings will be stripped from build import { debug, logOpcode } from '@glimmer/debug'; import { DESTROYABLE_STACK, INNER_VM, CONSTANTS, STACKS } from './symbols'; -import { InternalVM, InternalJitVM } from './vm/append'; +import { InternalVM } from './vm/append'; import { CURSOR_STACK } from './vm/element-builder'; import { isScopeReference } from './scope'; import { valueForRef } from '@glimmer/reference'; @@ -26,8 +26,7 @@ export type Operand1 = number; export type Operand2 = number; export type Operand3 = number; -export type Syscall = (vm: InternalVM, opcode: RuntimeOp) => void; -export type JitSyscall = (vm: InternalJitVM, opcode: RuntimeOp) => void; +export type Syscall = (vm: InternalVM, opcode: RuntimeOp) => void; export type MachineOpcode = (vm: LowLevelVM, opcode: RuntimeOp) => void; export type Evaluate = @@ -50,19 +49,14 @@ export class AppendOpcodes { add(name: Name, evaluate: Syscall): void; add(name: Name, evaluate: MachineOpcode, kind: 'machine'): void; - add(name: Name, evaluate: JitSyscall, kind: 'jit'): void; - add( - name: Name, - evaluate: Syscall | JitSyscall | MachineOpcode, - kind = 'syscall' - ): void { + add(name: Name, evaluate: Syscall | MachineOpcode, kind = 'syscall'): void { this.evaluateOpcode[name as number] = { syscall: kind !== 'machine', evaluate, } as Evaluate; } - debugBefore(vm: VM, opcode: RuntimeOp): DebugState { + debugBefore(vm: VM, opcode: RuntimeOp): DebugState { let params: Maybe = undefined; let opName: string | undefined = undefined; @@ -101,7 +95,7 @@ export class AppendOpcodes { }; } - debugAfter(vm: VM, pre: DebugState) { + debugAfter(vm: VM, pre: DebugState) { let { sp, type, isMachine, pc } = pre; if (LOCAL_DEBUG) { @@ -155,7 +149,7 @@ export class AppendOpcodes { } } - evaluate(vm: VM, opcode: RuntimeOp, type: number) { + evaluate(vm: VM, opcode: RuntimeOp, type: number) { let operation = this.evaluateOpcode[type]; if (operation.syscall) { diff --git a/packages/@glimmer/runtime/lib/render.ts b/packages/@glimmer/runtime/lib/render.ts index 5f23b13f7a..479f953694 100644 --- a/packages/@glimmer/runtime/lib/render.ts +++ b/packages/@glimmer/runtime/lib/render.ts @@ -3,32 +3,24 @@ import { DynamicScope, Environment, Invocation, - JitOrAotBlock, RenderResult, RichIteratorResult, SyntaxCompilationContext, - WithAotStaticLayout, TemplateIterator, - Cursor, ComponentDefinition, - JitRuntimeContext, - AotRuntimeContext, + RuntimeContext, ElementBuilder, CompilableProgram, } from '@glimmer/interfaces'; -import { Reference, UNDEFINED_REFERENCE } from '@glimmer/reference'; -import { expect, unwrapHandle } from '@glimmer/util'; -import { capabilityFlagsFrom } from './capabilities'; -import { hasStaticLayoutCapability } from './compiled/opcodes/component'; -import { resolveComponent } from './component/resolve'; +import { Reference } from '@glimmer/reference'; +import { unwrapHandle } from '@glimmer/util'; import { ARGS } from './symbols'; -import { AotVM, InternalVM, JitVM } from './vm/append'; -import { NewElementBuilder } from './vm/element-builder'; +import VM, { InternalVM } from './vm/append'; import { DynamicScopeImpl } from './scope'; import { inTransaction } from './environment'; -class TemplateIteratorImpl implements TemplateIterator { - constructor(private vm: InternalVM) {} +class TemplateIteratorImpl implements TemplateIterator { + constructor(private vm: InternalVM) {} next(): RichIteratorResult { return this.vm.next(); } @@ -46,45 +38,22 @@ export function renderSync(env: Environment, iterator: TemplateIterator): Render return result!; } -export function renderAotMain( - runtime: AotRuntimeContext, - self: Reference, - treeBuilder: ElementBuilder, - handle: number, - dynamicScope: DynamicScope = new DynamicScopeImpl() -): TemplateIterator { - let vm = AotVM.initial(runtime, { self, dynamicScope, treeBuilder, handle }); - return new TemplateIteratorImpl(vm); -} - -export function renderAot( - runtime: AotRuntimeContext, - handle: number, - cursor: Cursor, - self: Reference = UNDEFINED_REFERENCE -): TemplateIterator { - let treeBuilder = NewElementBuilder.forInitialRender(runtime.env, cursor); - let dynamicScope = new DynamicScopeImpl(); - let vm = AotVM.initial(runtime, { self, dynamicScope, treeBuilder, handle }); - return new TemplateIteratorImpl(vm); -} - -export function renderJitMain( - runtime: JitRuntimeContext, +export function renderMain( + runtime: RuntimeContext, context: SyntaxCompilationContext, self: Reference, treeBuilder: ElementBuilder, handle: number, dynamicScope: DynamicScope = new DynamicScopeImpl() ): TemplateIterator { - let vm = JitVM.initial(runtime, context, { self, dynamicScope, treeBuilder, handle }); + let vm = VM.initial(runtime, context, { self, dynamicScope, treeBuilder, handle }); return new TemplateIteratorImpl(vm); } export type RenderComponentArgs = Dict; -function renderInvocation( - vm: InternalVM, +function renderInvocation( + vm: InternalVM, invocation: Invocation, definition: ComponentDefinition, args: RenderComponentArgs @@ -123,38 +92,8 @@ function renderInvocation( return new TemplateIteratorImpl(vm); } -export function renderAotComponent( - runtime: AotRuntimeContext, - treeBuilder: ElementBuilder, - main: number, - name: string, - args: RenderComponentArgs = {}, - dynamicScope: DynamicScope = new DynamicScopeImpl() -): TemplateIterator { - let vm = AotVM.empty(runtime, { treeBuilder, handle: main, dynamicScope }); - - const definition = expect( - resolveComponent(vm.runtime.resolver, name), - `could not find component "${name}"` - ); - - const { manager, state } = definition; - - const capabilities = capabilityFlagsFrom(manager.getCapabilities(state)); - - let invocation; - - if (hasStaticLayoutCapability(capabilities, manager)) { - invocation = (manager as WithAotStaticLayout).getAotStaticLayout(state, vm.runtime.resolver); - } else { - throw new Error('Cannot invoke components with dynamic layouts as a root component.'); - } - - return renderInvocation(vm, invocation, definition, args); -} - -export function renderJitComponent( - runtime: JitRuntimeContext, +export function renderComponent( + runtime: RuntimeContext, treeBuilder: ElementBuilder, context: SyntaxCompilationContext, definition: ComponentDefinition, @@ -164,7 +103,7 @@ export function renderJitComponent( ): TemplateIterator { const handle = unwrapHandle(layout.compile(context)); const invocation = { handle, symbolTable: layout.symbolTable }; - let vm = JitVM.empty( + let vm = VM.empty( runtime, { treeBuilder, handle: context.program.stdlib.main, dynamicScope }, context diff --git a/packages/@glimmer/runtime/lib/scope.ts b/packages/@glimmer/runtime/lib/scope.ts index 9807655b96..6030140672 100644 --- a/packages/@glimmer/runtime/lib/scope.ts +++ b/packages/@glimmer/runtime/lib/scope.ts @@ -2,7 +2,6 @@ import { DynamicScope, Dict, PartialScope, - JitOrAotBlock, ScopeSlot, ScopeBlock, Option, @@ -40,18 +39,18 @@ export function isScopeReference(s: ScopeSlot): s is Reference { return true; } -export class PartialScopeImpl implements PartialScope { - static root(self: Reference, size = 0): PartialScope { +export class PartialScopeImpl implements PartialScope { + static root(self: Reference, size = 0): PartialScope { let refs: Reference[] = new Array(size + 1); for (let i = 0; i <= size; i++) { refs[i] = UNDEFINED_REFERENCE; } - return new PartialScopeImpl(refs, null, null, null).init({ self }); + return new PartialScopeImpl(refs, null, null, null).init({ self }); } - static sized(size = 0): Scope { + static sized(size = 0): Scope { let refs: Reference[] = new Array(size + 1); for (let i = 0; i <= size; i++) { @@ -63,10 +62,10 @@ export class PartialScopeImpl implements PartialScope>, - private callerScope: Option>, + readonly slots: Array, + private callerScope: Option, // named arguments and blocks passed to a layout that uses eval - private evalScope: Option>>, + private evalScope: Option>, // locals in scope when the partial was invoked private partialMap: Option>> ) {} @@ -84,12 +83,12 @@ export class PartialScopeImpl implements PartialScope>(symbol); } - getBlock(symbol: number): Option> { + getBlock(symbol: number): Option { let block = this.get(symbol); - return block === UNDEFINED_REFERENCE ? null : (block as ScopeBlock); + return block === UNDEFINED_REFERENCE ? null : (block as ScopeBlock); } - getEvalScope(): Option>> { + getEvalScope(): Option> { return this.evalScope; } @@ -97,7 +96,7 @@ export class PartialScopeImpl implements PartialScope) { + bind(symbol: number, value: ScopeSlot) { this.set(symbol, value); } @@ -109,11 +108,11 @@ export class PartialScopeImpl implements PartialScope>) { - this.set>>(symbol, value); + bindBlock(symbol: number, value: Option) { + this.set>(symbol, value); } - bindEvalScope(map: Option>>) { + bindEvalScope(map: Option>) { this.evalScope = map; } @@ -121,15 +120,15 @@ export class PartialScopeImpl implements PartialScope>): void { + bindCallerScope(scope: Option): void { this.callerScope = scope; } - getCallerScope(): Option> { + getCallerScope(): Option { return this.callerScope; } - child(): Scope { + child(): Scope { return new PartialScopeImpl( this.slots.slice(), this.callerScope, @@ -138,7 +137,7 @@ export class PartialScopeImpl implements PartialScope>(index: number): T { + private get(index: number): T { if (index >= this.slots.length) { throw new RangeError(`BUG: cannot get $${index} from scope; length=${this.slots.length}`); } @@ -146,7 +145,7 @@ export class PartialScopeImpl implements PartialScope>(index: number, value: T): void { + private set(index: number, value: T): void { if (index >= this.slots.length) { throw new RangeError(`BUG: cannot get $${index} from scope; length=${this.slots.length}`); } diff --git a/packages/@glimmer/runtime/lib/vm/append.ts b/packages/@glimmer/runtime/lib/vm/append.ts index cb6dd33f7a..2bde2248cc 100644 --- a/packages/@glimmer/runtime/lib/vm/append.ts +++ b/packages/@glimmer/runtime/lib/vm/append.ts @@ -1,10 +1,8 @@ import { - CompilableBlock, CompilableTemplate, Destroyable, DynamicScope, Environment, - JitOrAotBlock, PartialScope, RenderResult, RichIteratorResult, @@ -15,8 +13,6 @@ import { Scope, SyntaxCompilationContext, VM as PublicVM, - JitRuntimeContext, - AotRuntimeContext, ElementBuilder, } from '@glimmer/interfaces'; import { LOCAL_SHOULD_LOG } from '@glimmer/local-debug-flags'; @@ -43,7 +39,6 @@ import { Register, SyscallRegister, } from '@glimmer/vm'; -import { CheckNumber, check } from '@glimmer/debug'; import { unwrapHandle } from '@glimmer/util'; import { JumpIfNotModifiedOpcode, @@ -76,13 +71,14 @@ import { assertGlobalContextWasSet } from '@glimmer/global-context'; * This interface is used by internal opcodes, and is more stable than * the implementation of the Append VM itself. */ -export interface InternalVM { +export interface InternalVM { readonly [CONSTANTS]: RuntimeConstants; readonly [ARGS]: VMArgumentsImpl; readonly env: Environment; readonly stack: EvaluationStack; readonly runtime: RuntimeContext; + readonly context: SyntaxCompilationContext; loadValue(register: MachineRegister, value: number): void; loadValue(register: Register, value: unknown): void; @@ -96,7 +92,9 @@ export interface InternalVM { load(register: Register): void; fetch(register: Register): void; - scope(): Scope; + compile(block: CompilableTemplate): number; + + scope(): Scope; elements(): ElementBuilder; getSelf(): Reference; @@ -115,10 +113,10 @@ export interface InternalVM { enterItem(item: OpaqueIterationItem): ListItemOpcode; registerItem(item: ListItemOpcode): void; - pushRootScope(size: number): PartialScope; + pushRootScope(size: number): PartialScope; pushChildScope(): void; popScope(): void; - pushScope(scope: Scope): void; + pushScope(scope: Scope): void; dynamicScope(): DynamicScope; bindDynamicScope(names: string[]): void; @@ -139,22 +137,16 @@ export interface InternalVM { next(): RichIteratorResult; } -export interface InternalJitVM extends InternalVM { - compile(block: CompilableTemplate): number; - readonly runtime: JitRuntimeContext; - readonly context: SyntaxCompilationContext; -} - -class Stacks { - readonly scope = new Stack>(); +class Stacks { + readonly scope = new Stack(); readonly dynamicScope = new Stack(); readonly updating = new Stack(); readonly cache = new Stack(); readonly list = new Stack(); } -export default abstract class VM implements PublicVM, InternalVM { - private readonly [STACKS] = new Stacks(); +export default class VM implements PublicVM, InternalVM { + private readonly [STACKS] = new Stacks(); private readonly [HEAP]: RuntimeHeap; private readonly destructor: object; private readonly [DESTROYABLE_STACK] = new Stack(); @@ -281,7 +273,8 @@ export default abstract class VM implements PublicVM, I constructor( readonly runtime: RuntimeContext, { pc, scope, dynamicScope, stack }: VMState, - private readonly elementStack: ElementBuilder + private readonly elementStack: ElementBuilder, + readonly context: SyntaxCompilationContext ) { if (DEBUG) { assertGlobalContextWasSet!(); @@ -321,6 +314,45 @@ export default abstract class VM implements PublicVM, I this[DESTROYABLE_STACK].push(this.destructor); } + static initial( + runtime: RuntimeContext, + context: SyntaxCompilationContext, + { handle, self, dynamicScope, treeBuilder }: InitOptions + ) { + let scopeSize = runtime.program.heap.scopesizeof(handle); + let scope = PartialScopeImpl.root(self, scopeSize); + let state = vmState(runtime.program.heap.getaddr(handle), scope, dynamicScope); + let vm = initVM(context)(runtime, state, treeBuilder); + vm.pushUpdating(); + return vm; + } + + static empty( + runtime: RuntimeContext, + { handle, treeBuilder, dynamicScope }: MinimalInitOptions, + context: SyntaxCompilationContext + ) { + let vm = initVM(context)( + runtime, + vmState( + runtime.program.heap.getaddr(handle), + PartialScopeImpl.root(UNDEFINED_REFERENCE, 0), + dynamicScope + ), + treeBuilder + ); + vm.pushUpdating(); + return vm; + } + + private resume: VmInitCallback = initVM(this.context); + + compile(block: CompilableTemplate): number { + let handle = unwrapHandle(block.compile(this.context)); + + return handle; + } + get program(): RuntimeProgram { return this.runtime.program; } @@ -338,7 +370,9 @@ export default abstract class VM implements PublicVM, I }; } - abstract capture(args: number, pc?: number): ResumableVMState; + capture(args: number, pc = this[INNER_VM].fetchRegister($pc)): ResumableVMState { + return new ResumableVMStateImpl(this.captureState(args, pc), this.resume); + } beginCacheGroup(name?: string) { let opcodes = this.updating(); @@ -462,7 +496,7 @@ export default abstract class VM implements PublicVM, I return this.elementStack; } - scope(): Scope { + scope(): Scope { return expect(this[STACKS].scope.current, 'expected scope on the scope stack'); } @@ -483,13 +517,13 @@ export default abstract class VM implements PublicVM, I return child; } - pushRootScope(size: number): PartialScope { - let scope = PartialScopeImpl.sized(size); + pushRootScope(size: number): PartialScope { + let scope = PartialScopeImpl.sized(size); this[STACKS].scope.push(scope); return scope; } - pushScope(scope: Scope) { + pushScope(scope: Scope) { this[STACKS].scope.push(scope); } @@ -578,9 +612,9 @@ export default abstract class VM implements PublicVM, I } } -function vmState( +function vmState( pc: number, - scope: Scope = PartialScopeImpl.root(UNDEFINED_REFERENCE, 0), + scope: Scope = PartialScopeImpl.root(UNDEFINED_REFERENCE, 0), dynamicScope: DynamicScope ) { return { @@ -601,116 +635,13 @@ export interface InitOptions extends MinimalInitOptions { self: Reference; } -export class AotVM extends VM implements InternalVM { - static empty( - runtime: AotRuntimeContext, - { handle, treeBuilder, dynamicScope }: MinimalInitOptions - ): InternalVM { - let vm = initAOT( - runtime, - vmState( - runtime.program.heap.getaddr(handle), - PartialScopeImpl.root(UNDEFINED_REFERENCE, 0), - dynamicScope - ), - treeBuilder - ); - vm.pushUpdating(); - return vm; - } - - static initial( - runtime: AotRuntimeContext, - { handle, self, treeBuilder, dynamicScope }: InitOptions - ) { - let scopeSize = runtime.program.heap.scopesizeof(handle); - let scope = PartialScopeImpl.root(self, scopeSize); - let pc = check(runtime.program.heap.getaddr(handle), CheckNumber); - let state = vmState(pc, scope, dynamicScope); - let vm = initAOT(runtime, state, treeBuilder); - vm.pushUpdating(); - return vm; - } - - capture(args: number, pc = this[INNER_VM].fetchRegister($pc)): ResumableVMState { - return new ResumableVMStateImpl(this.captureState(args, pc), initAOT); - } -} - -export type VmInitCallback = ( +export type VmInitCallback = ( this: void, - runtime: V extends JitVM ? JitRuntimeContext : AotRuntimeContext, + runtime: RuntimeContext, state: VMState, builder: ElementBuilder -) => V; +) => InternalVM; -export type JitVmInitCallback = ( - this: void, - runtime: JitRuntimeContext, - state: VMState, - builder: ElementBuilder -) => V; - -function initAOT(runtime: AotRuntimeContext, state: VMState, builder: ElementBuilder): AotVM { - return new AotVM(runtime, state, builder); -} - -function initJIT(context: SyntaxCompilationContext): JitVmInitCallback { - return (runtime, state, builder) => new JitVM(runtime, state, builder, context); -} - -export class JitVM extends VM implements InternalJitVM { - static initial( - runtime: JitRuntimeContext, - context: SyntaxCompilationContext, - { handle, self, dynamicScope, treeBuilder }: InitOptions - ) { - let scopeSize = runtime.program.heap.scopesizeof(handle); - let scope = PartialScopeImpl.root(self, scopeSize); - let state = vmState(runtime.program.heap.getaddr(handle), scope, dynamicScope); - let vm = initJIT(context)(runtime, state, treeBuilder); - vm.pushUpdating(); - return vm; - } - - static empty( - runtime: JitRuntimeContext, - { handle, treeBuilder, dynamicScope }: MinimalInitOptions, - context: SyntaxCompilationContext - ) { - let vm = initJIT(context)( - runtime, - vmState( - runtime.program.heap.getaddr(handle), - PartialScopeImpl.root(UNDEFINED_REFERENCE, 0), - dynamicScope - ), - treeBuilder - ); - vm.pushUpdating(); - return vm; - } - - readonly runtime!: JitRuntimeContext; - - constructor( - runtime: JitRuntimeContext, - state: VMState, - elementStack: ElementBuilder, - readonly context: SyntaxCompilationContext - ) { - super(runtime, state, elementStack); - } - - capture(args: number, pc = this[INNER_VM].fetchRegister($pc)): ResumableVMState { - return new ResumableVMStateImpl(this.captureState(args, pc), this.resume); - } - - private resume: VmInitCallback = initJIT(this.context); - - compile(block: CompilableTemplate): number { - let handle = unwrapHandle(block.compile(this.context)); - - return handle; - } +function initVM(context: SyntaxCompilationContext): VmInitCallback { + return (runtime, state, builder) => new VM(runtime, state, builder, context); } diff --git a/packages/@glimmer/runtime/lib/vm/arguments.ts b/packages/@glimmer/runtime/lib/vm/arguments.ts index cb0086dcf8..f460049e93 100644 --- a/packages/@glimmer/runtime/lib/vm/arguments.ts +++ b/packages/@glimmer/runtime/lib/vm/arguments.ts @@ -10,12 +10,12 @@ import { CapturedPositionalArguments, NamedArguments, CapturedNamedArguments, - JitOrAotBlock, BlockValue, ScopeBlock, CapturedBlockArguments, Scope, BlockArguments, + CompilableBlock, } from '@glimmer/interfaces'; import { Reference, @@ -354,9 +354,9 @@ function toSymbolName(name: string): string { return `&${name}`; } -export class BlockArgumentsImpl implements BlockArguments { +export class BlockArgumentsImpl implements BlockArguments { private stack!: EvaluationStack; - private internalValues: Option = null; + private internalValues: Option = null; private _symbolNames: Option = null; public internalTag: Option = null; @@ -397,7 +397,7 @@ export class BlockArgumentsImpl implements BlockArgumen if (!values) { let { base, length, stack } = this; - values = this.internalValues = stack.slice(base, base + length * 3); + values = this.internalValues = stack.slice(base, base + length * 3); } return values; @@ -407,7 +407,7 @@ export class BlockArgumentsImpl implements BlockArgumen return this.names!.indexOf(name) !== -1; } - get(name: string): Option> { + get(name: string): Option { let idx = this.names!.indexOf(name); if (idx === -1) { @@ -423,7 +423,7 @@ export class BlockArgumentsImpl implements BlockArgumen CheckOption(CheckOr(CheckHandle, CheckCompilableBlock)) ); - return handle === null ? null : ([handle, scope!, table!] as ScopeBlock); + return handle === null ? null : ([handle, scope!, table!] as ScopeBlock); } capture(): CapturedBlockArguments { @@ -458,8 +458,8 @@ class CapturedBlockArgumentsImpl implements CapturedBlockArguments { if (idx === -1) return null; return [ - this.values[idx * 3 + 2] as number, - this.values[idx * 3 + 1] as Scope, + this.values[idx * 3 + 2] as CompilableBlock, + this.values[idx * 3 + 1] as Scope, this.values[idx * 3] as BlockSymbolTable, ]; } diff --git a/packages/@glimmer/runtime/lib/vm/low-level.ts b/packages/@glimmer/runtime/lib/vm/low-level.ts index a37c53b5a3..2dcb3afd94 100644 --- a/packages/@glimmer/runtime/lib/vm/low-level.ts +++ b/packages/@glimmer/runtime/lib/vm/low-level.ts @@ -1,11 +1,4 @@ -import { - Option, - RuntimeHeap, - MachineOp, - RuntimeProgram, - RuntimeOp, - JitOrAotBlock, -} from '@glimmer/interfaces'; +import { Option, RuntimeHeap, MachineOp, RuntimeProgram, RuntimeOp } from '@glimmer/interfaces'; import { APPEND_OPCODES } from '../opcodes'; import VM from './append'; import { LOCAL_DEBUG } from '@glimmer/local-debug-flags'; @@ -143,7 +136,7 @@ export default class LowLevelVM { return opcode; } - evaluateOuter(opcode: RuntimeOp, vm: VM) { + evaluateOuter(opcode: RuntimeOp, vm: VM) { if (LOCAL_DEBUG) { let { externs: { debugBefore, debugAfter }, @@ -156,7 +149,7 @@ export default class LowLevelVM { } } - evaluateInner(opcode: RuntimeOp, vm: VM) { + evaluateInner(opcode: RuntimeOp, vm: VM) { if (opcode.isMachine) { this.evaluateMachine(opcode); } else { @@ -183,7 +176,7 @@ export default class LowLevelVM { } } - evaluateSyscall(opcode: RuntimeOp, vm: VM) { + evaluateSyscall(opcode: RuntimeOp, vm: VM) { APPEND_OPCODES.evaluate(vm, opcode, opcode.type); } } diff --git a/packages/@glimmer/runtime/lib/vm/update.ts b/packages/@glimmer/runtime/lib/vm/update.ts index 49f4bb38d1..8fa616e321 100644 --- a/packages/@glimmer/runtime/lib/vm/update.ts +++ b/packages/@glimmer/runtime/lib/vm/update.ts @@ -4,11 +4,8 @@ import { Environment, ExceptionHandler, GlimmerTreeChanges, - JitOrAotBlock, RuntimeContext, Scope, - AotRuntimeContext, - JitRuntimeContext, ElementBuilder, LiveBlock, UpdatableBlock, @@ -25,7 +22,7 @@ import { resetTracking } from '@glimmer/validator'; import { SimpleComment } from '@simple-dom/interface'; import { move as moveBounds, clear } from '../bounds'; import { UpdatingOpcode } from '../opcodes'; -import { InternalVM, VmInitCallback, JitVM } from './append'; +import { InternalVM, VmInitCallback } from './append'; import { NewElementBuilder, LiveBlockList } from './element-builder'; import { destroy, associateDestroyableChild, destroyChildren } from '../destroyables'; import { LOCAL_DEBUG } from '@glimmer/local-debug-flags'; @@ -88,22 +85,19 @@ export default class UpdatingVM { export interface VMState { readonly pc: number; - readonly scope: Scope; + readonly scope: Scope; readonly dynamicScope: DynamicScope; readonly stack: unknown[]; } -export interface ResumableVMState { - resume(runtime: RuntimeContext, builder: ElementBuilder): V; +export interface ResumableVMState { + resume(runtime: RuntimeContext, builder: ElementBuilder): InternalVM; } -export class ResumableVMStateImpl implements ResumableVMState { - constructor(readonly state: VMState, private resumeCallback: VmInitCallback) {} +export class ResumableVMStateImpl implements ResumableVMState { + constructor(readonly state: VMState, private resumeCallback: VmInitCallback) {} - resume( - runtime: V extends JitVM ? JitRuntimeContext : AotRuntimeContext, - builder: ElementBuilder - ): V { + resume(runtime: RuntimeContext, builder: ElementBuilder): InternalVM { return this.resumeCallback(runtime, this.state, builder); } } @@ -115,7 +109,7 @@ export abstract class BlockOpcode extends UpdatingOpcode implements Bounds { protected readonly bounds: LiveBlock; constructor( - protected state: ResumableVMState, + protected state: ResumableVMState, protected runtime: RuntimeContext, bounds: LiveBlock, children: UpdatingOpcode[] @@ -178,7 +172,7 @@ export class ListItemOpcode extends TryOpcode { public index = -1; constructor( - state: ResumableVMState, + state: ResumableVMState, runtime: RuntimeContext, bounds: UpdatableBlock, public key: unknown, @@ -214,7 +208,7 @@ export class ListBlockOpcode extends BlockOpcode { protected readonly bounds!: LiveBlockList; constructor( - state: ResumableVMState, + state: ResumableVMState, runtime: RuntimeContext, bounds: LiveBlockList, children: ListItemOpcode[], diff --git a/packages/@glimmer/vm/lib/opcodes.toml b/packages/@glimmer/vm/lib/opcodes.toml index 6a6cb5941f..45ac6a9366 100644 --- a/packages/@glimmer/vm/lib/opcodes.toml +++ b/packages/@glimmer/vm/lib/opcodes.toml @@ -84,19 +84,9 @@ operand-stack = [ [] ] -[syscall.sbblock] +[syscall.sblock] -format = ["SetAotBlock", "symbol:u32"] -operation = "Bind the block at the top of the stack." -operand-stack = [ - ["symbol-table", "scope", "handle"], - [] -] - - -[syscall.sjblock] - -format = ["SetJitBlock", "symbol:u32"] +format = ["SetBlock", "symbol:u32"] operation = "Bind the block at the top of the stack." operand-stack = [ ["symbol-table", "scope", "block"], @@ -140,8 +130,8 @@ notes = "TODO: The three elements on the stack can be null" [syscall.blockspread] -format = ["JitSpreadBlock"] -operation = "Spread a JIT scope block into three stack elements" +format = ["SpreadBlock"] +operation = "Spread a scope block into three stack elements" operand-stack = [ ["scope-block"], ["symbol-table", "scope", "handle"] @@ -792,18 +782,9 @@ operand-stack = [ ["option-str"] ] -[syscall.comp_alayoutload] - -format = ["GetAotComponentLayout", "state:register"] -operation = "Get the component layout from the manager." -operand-stack = [ - [], - ["ProgramSymbolTable", "handle"] -] - -[syscall.comp_jlayoutload] +[syscall.comp_layoutload] -format = ["GetJitComponentLayout", "state:register"] +format = ["GetComponentLayout", "state:register"] operation = "Get the component layout from the manager." operand-stack = [ [], diff --git a/yarn.lock b/yarn.lock index 5ef580511f..13ac119b2a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -846,6 +846,19 @@ exec-sh "^0.3.2" minimist "^1.2.0" +"@glimmer/bundle-compiler@^0.60.0": + version "0.60.0" + resolved "https://registry.yarnpkg.com/@glimmer/bundle-compiler/-/bundle-compiler-0.60.0.tgz#f96c72745d671ecc7fb1886adf8d8d7a6f70cefb" + integrity sha512-vR4t4ElNZC0aKBiTIrGgzzrzbhy7VIlfcoCXZdBOBFIx+ut4cVbUCFk+vwXk+siTiQBlNlbaN/hkWtUW8oHB9w== + dependencies: + "@glimmer/compiler" "^0.60.0" + "@glimmer/interfaces" "^0.60.0" + "@glimmer/opcode-compiler" "^0.60.0" + "@glimmer/program" "^0.60.0" + "@glimmer/syntax" "^0.60.0" + "@glimmer/util" "^0.60.0" + "@glimmer/wire-format" "^0.60.0" + "@glimmer/env@0.1.7", "@glimmer/env@^0.1.7": version "0.1.7" resolved "https://registry.yarnpkg.com/@glimmer/env/-/env-0.1.7.tgz#fd2d2b55a9029c6b37a6c935e8c8871ae70dfa07"