diff --git a/CHANGELOG.md b/CHANGELOG.md index c657a5fc..fecc2283 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ ### Changed +- Faster crawl of sources, which runs on one thread. Finding an export of another module while gathering source info + (`import {x} from "..."` used in `b.asset`, `b.sprite`, translation parameters) walked the whole module for each + lookup, now one pass per module builds an index of its exports. Parsing of the transpiled JavaScript is done on the + worker threads of native transpiler (tsrs) instead of on the crawl thread. In a project with ~2650 sources the crawl + thread went from ~9.4 s to ~6.5 s, output is byte identical. - Faster builds: released binaries now use the server garbage collector and have dynamic PGO (`TieredPGO`) turned off. A build without build cache of a ~2650 source project went from ~27 s to ~22 s and one with build cache from ~20 s to ~17 s, at the cost of ~170 MB more memory and ~30-100 ms slower start. `DOTNET_gcServer=0` and `DOTNET_TieredPGO=1` diff --git a/Lib/TSCompiler/BuildModuleCtx.cs b/Lib/TSCompiler/BuildModuleCtx.cs index 698944e8..8a977828 100644 --- a/Lib/TSCompiler/BuildModuleCtx.cs +++ b/Lib/TSCompiler/BuildModuleCtx.cs @@ -1286,19 +1286,41 @@ void PrefetchTranspiles(string nativeExecutable) _prefetchedTranspiles[fileName] = (source, Task.Run(() => { var compiler = pool.GetNativeTranspiler(nativeExecutable, options); + TranspileResult result; try { - return compiler.Transpile(transpileFileName, source); + result = compiler.Transpile(transpileFileName, source); } finally { pool.ReleaseNativeTranspiler(compiler); } + + ParseAhead(result); + return result; })); running++; } } + // Parsing and scope analysis of the transpiled JavaScript is pure function of its text, so it is done here on the worker + // thread instead of on the sequential crawl. When it fails the crawl parses again and reports the error as before. + static void ParseAhead(TranspileResult result) + { + if (result.Diagnostics != null && result.Diagnostics.Exists(d => d.IsError)) + return; + try + { + var toplevel = new Parser(new(), SourceMap.RemoveLinkToSourceMap(result.JavaScript)).Parse(); + toplevel.FigureOutScope(); + result.Ast = toplevel; + } + catch (Exception) + { + result.Ast = null; + } + } + // Only TypeScript files which will be really transpiled: changed since last crawl and not in build cache bool TryGetSourceToPrefetch(string fileName, out string source) { diff --git a/Njsast.Test/ConstEval/ExportIndexTest.cs b/Njsast.Test/ConstEval/ExportIndexTest.cs new file mode 100644 index 00000000..4e43eea0 --- /dev/null +++ b/Njsast.Test/ConstEval/ExportIndexTest.cs @@ -0,0 +1,67 @@ +using Njsast.Ast; +using Njsast.ConstEval; +using Njsast.Output; +using Njsast.Reader; +using Xunit; + +namespace Test.ConstEval; + +public class ExportIndexTest +{ + const string Main = "/src/main.js"; + + static InMemoryImportResolver Resolver() => new InMemoryImportResolver() + .Add("/src/other", "exports.a = 7;\nexports.d = 8;\n") + .Add("/src/chain", "__exportStar(require(\"./other\"), exports);\nexports.e = 9;\n") + .Add("/src/whole", "module.exports = { a: 1, b: 2 };\n"); + + [Theory] + [InlineData("exports.a = 1;\nexports.b = \"x\";\nexports.a = 2;")] + [InlineData("exports.a = exports.b = void 0;\nexports.a = 5;")] + [InlineData("module.exports = { a: 1, b: 2 };")] + [InlineData("exports.a = 1;\nmodule.exports = { a: 3 };\nexports.b = 4;")] + [InlineData("__exportStar(require(\"./other\"), exports);\nexports.c = 3;")] + [InlineData("exports.a = 1;\n__exportStar(require(\"./other\"), exports);")] + [InlineData("__export(require(\"./chain\"));\nexports.b = 3;")] + [InlineData("__exportStar(require(\"./missing\"), exports);\nexports.a = 1;")] + [InlineData("(function () { exports.a = 1; exports.z = 2; })();\nexports.b = 3;")] + [InlineData("exports.a.b = 1;\nvar x = exports.a;\nexports[\"b\"] = 2;\nmodule.exports.c = 3;")] + [InlineData("exports.a = exports.b = exports.c = void 0;\nexports.a = 1;\nexports.d = 2;")] + [InlineData("var exports = {};\nexports.a = 1;")] + public void FindsSameExportAsWalkingWholeModule(string source) + { + foreach (var export in new[] { "a", "b", "c", "d", "e", "z", "missing" }) + { + var expected = WithWalker(source, export); + var actual = WithIndex(source, export); + Assert.Equal(expected, actual); + } + } + + static string WithWalker(string source, string export) + { + var toplevel = Parse(source); + var finder = new ExportFinder(export, new ResolvingConstEvalCtx(Main, Resolver())); + finder.Walk(toplevel); + return Print(finder.Result, finder.CompleteResult); + } + + static string WithIndex(string source, string export) + { + var toplevel = Parse(source); + // Asked twice, the second answer must not depend on the first one + ExportIndex.For(toplevel).Find(export, new ResolvingConstEvalCtx(Main, Resolver())); + var (result, complete) = ExportIndex.For(toplevel).Find(export, new ResolvingConstEvalCtx(Main, Resolver())); + return Print(result, complete); + } + + static AstToplevel Parse(string source) + { + var toplevel = new Parser(new Options(), source).Parse(); + toplevel.FigureOutScope(); + return toplevel; + } + + static string Print(AstNode? result, bool complete) => + (result?.PrintToString(new OutputOptions { Beautify = true }) ?? "") + " complete=" + complete; +} diff --git a/Njsast/ConstEval/ExportFinder.cs b/Njsast/ConstEval/ExportFinder.cs index 7034c8b9..cc46ce65 100644 --- a/Njsast/ConstEval/ExportFinder.cs +++ b/Njsast/ConstEval/ExportFinder.cs @@ -1,3 +1,6 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; using Njsast.Ast; using Njsast.Reader; using Njsast.Runtime; @@ -8,7 +11,7 @@ public class ExportFinder : TreeWalker { readonly string _export; readonly IConstEvalCtx _ctx; - internal AstNode? Result; + public AstNode? Result; public bool CompleteResult; public ExportFinder(string export, IConstEvalCtx ctx) @@ -17,7 +20,7 @@ public ExportFinder(string export, IConstEvalCtx ctx) _ctx = ctx; } - static bool IsExportsAssignVoid0(AstNode? node) + internal static bool IsExportsAssignVoid0(AstNode? node) { while (true) { @@ -49,7 +52,7 @@ protected override void Visit(AstNode node) } } - if (node is AstCall call && call.Expression is AstSymbol symbol && (symbol.Name == "__exportStar" && call.Args.Count == 2 || symbol.Name == "__export" && call.Args.Count == 1) && call.Args[0] is AstCall) + if (node is AstCall call && IsExportStarCall(call)) { var module = call.Args[0].ConstValue(_ctx); if (module is JsModule) @@ -71,7 +74,12 @@ protected override void Visit(AstNode node) } } - static bool IsExports(AstNode node) + internal static bool IsExportStarCall(AstCall call) => + call.Expression is AstSymbol symbol && + (symbol.Name == "__exportStar" && call.Args.Count == 2 || symbol.Name == "__export" && call.Args.Count == 1) && + call.Args[0] is AstCall; + + internal static bool IsExports(AstNode node) { if (node is AstDot dot && dot.Property as string == "exports") { @@ -91,4 +99,126 @@ static bool IsExports(AstNode node) if (def == null) return false; return def.Undeclared && def.Global && def.Name == "exports"; } -} \ No newline at end of file +} +/// Everything reacts to in one module, in source order. Finding an export then needs only the +/// entries of that export and the ones which can set any export, instead of walking the whole module for each export. +public sealed class ExportIndex +{ + static readonly ConditionalWeakTable Cache = new(); + + enum EntryKind + { + Named, + ExportStar, + ModuleExports + } + + readonly List<(EntryKind Kind, AstNode Node)> _entries = []; + readonly Dictionary> _named = new(); + readonly List _anyExport = []; + // Walk of ExportFinder would fail on such module for every export + bool _unsupported; + + public static ExportIndex For(AstToplevel module) => Cache.GetValue(module, static m => new ExportIndex(m)); + + ExportIndex(AstToplevel module) + { + new Builder(this).Walk(module); + } + + /// Same result as ExportFinder.Walk(module) for the export name, including evaluating exports of other modules + /// through in the same order. + public (AstNode? Result, bool CompleteResult) Find(string export, IConstEvalCtx ctx) + { + if (_unsupported) throw new InvalidCastException(); + AstNode? result = null; + var complete = false; + _named.TryGetValue(export, out var named); + var n = 0; + var a = 0; + while (true) + { + var hasNamed = named != null && n < named.Count; + var hasAny = a < _anyExport.Count; + if (!hasNamed && !hasAny) break; + int index; + if (hasNamed && (!hasAny || named![n] < _anyExport[a])) + index = named![n++]; + else + index = _anyExport[a++]; + var (kind, node) = _entries[index]; + switch (kind) + { + case EntryKind.Named: + result = ((AstAssign)node).Right; + complete = false; + break; + case EntryKind.ExportStar: + var module = ((AstCall)node).Args[0].ConstValue(ctx); + if (module is JsModule jsModule) + { + var res = ctx.ConstValue(ctx, jsModule, export); + if (res != null) + { + result = TypeConverter.ToAst(res); + complete = false; + } + } + + break; + default: + result = ((AstAssign)node).Right; + complete = true; + break; + } + } + + return (result, complete); + } + + sealed class Builder(ExportIndex owner) : TreeWalker + { + protected override void Visit(AstNode node) + { + if (ExportFinder.IsExportsAssignVoid0(node)) + { + StopDescending(); + return; + } + + if (node is AstDot dot) + { + StopDescending(); + if (ExportFinder.IsExports(dot.Expression)) + { + if (dot.Property is not string name) + { + owner._unsupported = true; + } + else if (Parent() is AstAssign assign && assign.Operator == Operator.Assignment && + assign.Left == node) + { + if (!owner._named.TryGetValue(name, out var list)) + owner._named[name] = list = []; + list.Add(owner._entries.Count); + owner._entries.Add((EntryKind.Named, assign)); + } + } + } + + if (node is AstCall call && ExportFinder.IsExportStarCall(call)) + { + owner._anyExport.Add(owner._entries.Count); + owner._entries.Add((EntryKind.ExportStar, call)); + } + + if (node is AstAssign assign2 && assign2.Operator == Operator.Assignment && + ExportFinder.IsExports(assign2.Left)) + { + StopDescending(); + owner._anyExport.Add(owner._entries.Count); + owner._entries.Add((EntryKind.ModuleExports, assign2)); + } + } + } +} diff --git a/Njsast/ConstEval/ResolvingConstEvalCtx.cs b/Njsast/ConstEval/ResolvingConstEvalCtx.cs index e197c19b..4281efc5 100644 --- a/Njsast/ConstEval/ResolvingConstEvalCtx.cs +++ b/Njsast/ConstEval/ResolvingConstEvalCtx.cs @@ -29,13 +29,12 @@ public JsModule ResolveRequire(string name) try { var ctx2 = ctx.CreateForSourceName(fileName); - var treeWalker = new ExportFinder((string)export, ctx2); - treeWalker.Walk(content); - if (treeWalker.Result == null) + var (finderResult, completeResult) = ExportIndex.For(content).Find((string)export, ctx2); + if (finderResult == null) return null; - var result = treeWalker.Result.ConstValue(ctx2); + var result = finderResult.ConstValue(ctx2); if (result == null) return null; - if (treeWalker.CompleteResult) + if (completeResult) { if (result is IReadOnlyDictionary dict) {