Skip to content

Commit

Permalink
Improve AST garbage collection (#4762)
Browse files Browse the repository at this point in the history
* Add AST LRU cache

* Fix dynamic import AST keep

* Refactor implementation

* Remove lru config

* Fix cache check

* Add test for line coverage

* Refactor cache check
  • Loading branch information
bluwy committed Dec 23, 2022
1 parent 1243370 commit b179695
Show file tree
Hide file tree
Showing 12 changed files with 174 additions and 19 deletions.
17 changes: 17 additions & 0 deletions LICENSE.md
Expand Up @@ -247,6 +247,23 @@ Repository: jonschlinkert/fill-range
---------------------------------------

## flru
License: MIT
By: Luke Edwards
Repository: lukeed/flru

> MIT License
>
> Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---------------------------------------

## glob-parent
License: ISC
By: Gulp Team, Elan Shanker, Blaine Bublitz
Expand Down
17 changes: 17 additions & 0 deletions browser/LICENSE.md
Expand Up @@ -88,6 +88,23 @@ Repository: https://github.com/acornjs/acorn.git
---------------------------------------

## flru
License: MIT
By: Luke Edwards
Repository: lukeed/flru

> MIT License
>
> Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---------------------------------------

## hash.js
License: MIT
By: Fedor Indutny
Expand Down
16 changes: 16 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Expand Up @@ -90,6 +90,7 @@
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-unicorn": "^44.0.2",
"fixturify": "^2.1.1",
"flru": "^1.0.2",
"fs-extra": "^10.1.0",
"github-api": "^3.4.0",
"hash.js": "^1.1.7",
Expand Down
2 changes: 2 additions & 0 deletions src/Graph.ts
@@ -1,4 +1,5 @@
import * as acorn from 'acorn';
import flru from 'flru';
import type ExternalModule from './ExternalModule';
import Module from './Module';
import { ModuleLoader, type UnresolvedModule } from './ModuleLoader';
Expand Down Expand Up @@ -52,6 +53,7 @@ function normalizeEntryModules(

export default class Graph {
readonly acornParser: typeof acorn.Parser;
readonly astLru = flru<acorn.Node>(5);
readonly cachedModules = new Map<string, ModuleJSON>();
readonly deoptimizationTracker = new PathTracker();
entryModules: Module[] = [];
Expand Down
29 changes: 22 additions & 7 deletions src/Module.ts
Expand Up @@ -770,10 +770,7 @@ export default class Module {
this.transformDependencies = transformDependencies;
this.customTransformCache = customTransformCache;
this.updateOptions(moduleOptions);

if (!ast) {
ast = this.tryParse();
}
const moduleAst = ast || this.tryParse();

timeEnd('generate ast', 3);
timeStart('analyze ast', 3);
Expand Down Expand Up @@ -821,16 +818,34 @@ export default class Module {

this.scope = new ModuleScope(this.graph.scope, this.astContext);
this.namespace = new NamespaceVariable(this.astContext);
this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope);
this.info.ast = ast;
this.ast = new Program(moduleAst, { context: this.astContext, type: 'Module' }, this.scope);

// Assign AST directly if has existing one as there's no way to drop it from memory.
// If cache is enabled, also assign directly as otherwise it takes more CPU and memory to re-compute.
if (ast || this.options.cache !== false) {
this.info.ast = moduleAst;
} else {
// Make lazy and apply LRU cache to not hog the memory
Object.defineProperty(this.info, 'ast', {
get: () => {
if (this.graph.astLru.has(fileName)) {
return this.graph.astLru.get(fileName)!;
} else {
const parsedAst = this.tryParse();
this.graph.astLru.set(fileName, parsedAst);
return parsedAst;
}
}
});
}

timeEnd('analyze ast', 3);
}

toJSON(): ModuleJSON {
return {
assertions: this.info.assertions,
ast: this.ast!.esTreeNode,
ast: this.info.ast!,
code: this.info.code!,
customTransformCache: this.customTransformCache,
// eslint-disable-next-line unicorn/prefer-spread
Expand Down
2 changes: 1 addition & 1 deletion src/ModuleLoader.ts
Expand Up @@ -541,7 +541,7 @@ export class ModuleLoader {
module,
typeof dynamicImport.argument === 'string'
? dynamicImport.argument
: dynamicImport.argument.esTreeNode,
: dynamicImport.argument.esTreeNode!,
module.id,
getAssertionsFromImportExpression(dynamicImport.node)
);
Expand Down
12 changes: 11 additions & 1 deletion src/ast/nodes/ImportExpression.ts
Expand Up @@ -14,7 +14,12 @@ import type ChildScope from '../scopes/ChildScope';
import type NamespaceVariable from '../variables/NamespaceVariable';
import type * as NodeType from './NodeType';
import type ObjectExpression from './ObjectExpression';
import { type ExpressionNode, type IncludeChildren, NodeBase } from './shared/Node';
import {
type ExpressionNode,
type GenericEsTreeNode,
type IncludeChildren,
NodeBase
} from './shared/Node';

interface DynamicImportMechanism {
left: string;
Expand Down Expand Up @@ -57,6 +62,11 @@ export default class ImportExpression extends NodeBase {
this.context.addDynamicImport(this);
}

parseNode(esTreeNode: GenericEsTreeNode): void {
// Keep the source AST to be used by renderDynamicImport
super.parseNode(esTreeNode, ['source']);
}

render(code: MagicString, options: RenderOptions): void {
const {
snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess }
Expand Down
23 changes: 16 additions & 7 deletions src/ast/nodes/shared/Node.ts
Expand Up @@ -31,7 +31,7 @@ export interface Node extends Entity {
annotations?: acorn.Comment[];
context: AstContext;
end: number;
esTreeNode: GenericEsTreeNode;
esTreeNode: GenericEsTreeNode | null;
included: boolean;
keys: string[];
needsBoundaries?: boolean;
Expand Down Expand Up @@ -119,7 +119,7 @@ export class NodeBase extends ExpressionEntity implements ExpressionNode {
declare annotations?: acorn.Comment[];
context: AstContext;
declare end: number;
esTreeNode: acorn.Node;
esTreeNode: acorn.Node | null;
keys: string[];
parent: Node | { context: AstContext; type: string };
declare scope: ChildScope;
Expand All @@ -140,10 +140,13 @@ export class NodeBase extends ExpressionEntity implements ExpressionNode {
constructor(
esTreeNode: GenericEsTreeNode,
parent: Node | { context: AstContext; type: string },
parentScope: ChildScope
parentScope: ChildScope,
keepEsTreeNode = false
) {
super();
this.esTreeNode = esTreeNode;
// Nodes can opt-in to keep the AST if needed during the build pipeline.
// Avoid true when possible as large AST takes up memory.
this.esTreeNode = keepEsTreeNode ? esTreeNode : null;
this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
this.parent = parent;
this.context = parent.context;
Expand Down Expand Up @@ -243,7 +246,7 @@ export class NodeBase extends ExpressionEntity implements ExpressionNode {
}
}

parseNode(esTreeNode: GenericEsTreeNode): void {
parseNode(esTreeNode: GenericEsTreeNode, keepEsTreeNodeKeys?: string[]): void {
for (const [key, value] of Object.entries(esTreeNode)) {
// That way, we can override this function to add custom initialisation and then call super.parseNode
if (this.hasOwnProperty(key)) continue;
Expand All @@ -262,14 +265,20 @@ export class NodeBase extends ExpressionEntity implements ExpressionNode {
(this as GenericEsTreeNode)[key].push(
child === null
? null
: new (this.context.getNodeConstructor(child.type))(child, this, this.scope)
: new (this.context.getNodeConstructor(child.type))(
child,
this,
this.scope,
keepEsTreeNodeKeys?.includes(key)
)
);
}
} else {
(this as GenericEsTreeNode)[key] = new (this.context.getNodeConstructor(value.type))(
value,
this,
this.scope
this.scope,
keepEsTreeNodeKeys?.includes(key)
);
}
}
Expand Down
8 changes: 5 additions & 3 deletions src/rollup/rollup.ts
Expand Up @@ -50,10 +50,12 @@ export async function rollupInternal(

const graph = new Graph(inputOptions, watcher);

// remove the cache option from the memory after graph creation (cache is not used anymore)
// remove the cache object from the memory after graph creation (cache is not used anymore)
const useCache = rawInputOptions.cache !== false;
delete inputOptions.cache;
delete rawInputOptions.cache;
if (rawInputOptions.cache) {
inputOptions.cache = undefined;
rawInputOptions.cache = undefined;
}

timeStart('BUILD', 1);

Expand Down
@@ -0,0 +1,65 @@
const assert = require('node:assert');
const path = require('node:path');

const ID_MAIN = path.join(__dirname, 'main.js');

module.exports = {
description: 'handles accessing module information via plugins with cache disabled',
options: {
cache: false,
plugins: [
{
renderStart() {
const info = this.getModuleInfo(ID_MAIN);
const ast = {
type: 'Program',
start: 0,
end: 19,
body: [
{
type: 'ExportDefaultDeclaration',
start: 0,
end: 18,
declaration: {
type: 'Literal',
start: 15,
end: 17,
value: 42,
raw: '42'
}
}
],
sourceType: 'module'
};
assert.deepStrictEqual(JSON.parse(JSON.stringify(info)), {
assertions: {},
ast,
code: 'export default 42;\n',
dynamicallyImportedIdResolutions: [],
dynamicallyImportedIds: [],
dynamicImporters: [],
exportedBindings: {
'.': ['default']
},
exports: ['default'],
hasDefaultExport: true,
id: ID_MAIN,
implicitlyLoadedAfterOneOf: [],
implicitlyLoadedBefore: [],
importedIdResolutions: [],
importedIds: [],
importers: [],
isEntry: true,
isExternal: false,
isIncluded: true,
meta: {},
moduleSideEffects: true,
syntheticNamedExports: false
});
// Call AST again to ensure line coverage for cached getter
assert.deepStrictEqual(JSON.parse(JSON.stringify(info.ast)), ast);
}
}
]
}
};
@@ -0,0 +1 @@
export default 42;

0 comments on commit b179695

Please sign in to comment.