From 62fafbaec1c01d5b88a50392fdb4ec2abb9277ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Radek=20Sedl=C3=A1k?= Date: Thu, 29 Oct 2026 09:01:54 +0100 Subject: [PATCH 1/2] Parse transpiled output on the prefetch worker threads Parsing and scope analysis of the transpiled JavaScript is a pure function of its text, so it runs after the native transpile on the worker instead of on the sequential crawl. Co-Authored-By: Claude Sonnet 5.5 --- Lib/TSCompiler/BuildModuleCtx.cs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) 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) { From 2c0ffe70089b1b71900c0d39685f17ac4a58869c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Radek=20Sedl=C3=A1k?= Date: Thu, 29 Oct 2026 09:01:54 +0100 Subject: [PATCH 2/2] Find exports of other modules through a per module index ExportFinder walked the whole module for each looked up export (5386 lookups of 1673 distinct exports in a 2650 source project, ~3 s on the crawl thread). ExportIndex records everything the walk reacts to in one pass and answers each lookup from the entries of that export and the ones which can set any export, in source order, so the result and the evaluation of re-exported modules are the same. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 8 ++ Njsast.Test/ConstEval/ExportIndexTest.cs | 67 +++++++++++ Njsast/ConstEval/ExportFinder.cs | 140 +++++++++++++++++++++- Njsast/ConstEval/ResolvingConstEvalCtx.cs | 9 +- 4 files changed, 214 insertions(+), 10 deletions(-) create mode 100644 Njsast.Test/ConstEval/ExportIndexTest.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index a4b06c89..48807a9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [unreleased] +### 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. + ## 7.1.0 ### Changed 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) {