Skip to content

Commit 2fa14b8

Browse files
committed
Refactor
1 parent ceff8f2 commit 2fa14b8

14 files changed

Lines changed: 148 additions & 151 deletions

File tree

src/transformation/index.ts

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import * as ts from "typescript";
22
import * as lua from "../LuaAST";
3-
import { LuaLibFeature } from "../LuaLib";
43
import { getOrUpdate } from "../utils";
54
import { ObjectVisitor, TransformationContext, VisitorMap, Visitors } from "./context";
65
import { getUsedLuaLibFeatures } from "./utils/lualib";
@@ -29,17 +28,7 @@ export function createVisitorMap(customVisitors: Visitors[]): VisitorMap {
2928
return visitorMap;
3029
}
3130

32-
export interface TransformSourceFileResult {
33-
luaAst: lua.Block;
34-
luaLibFeatures: Set<LuaLibFeature>;
35-
diagnostics: ts.Diagnostic[];
36-
}
37-
38-
export function transformSourceFile(
39-
program: ts.Program,
40-
sourceFile: ts.SourceFile,
41-
visitorMap: VisitorMap
42-
): TransformSourceFileResult {
31+
export function transformSourceFile(program: ts.Program, sourceFile: ts.SourceFile, visitorMap: VisitorMap) {
4332
const context = new TransformationContext(program, sourceFile, visitorMap);
4433
const [luaAst] = context.transformNode(sourceFile) as [lua.Block];
4534

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,12 @@
11
import * as path from "path";
22
import { SourceNode } from "source-map";
3-
import * as ts from "typescript";
4-
import { CompilerOptions, isBundleEnabled } from "../CompilerOptions";
5-
import { escapeString } from "../LuaPrinter";
6-
import { assert, normalizeSlashes } from "../utils";
7-
import { couldNotFindBundleEntryPoint } from "./diagnostics";
8-
import { Module } from "./module";
9-
import { Transpilation } from "./transpilation";
10-
import { getConfigDirectory } from "./utils";
11-
12-
export interface Chunk {
13-
outputPath: string;
14-
source: SourceNode;
15-
sourceFiles?: ts.SourceFile[];
16-
}
17-
18-
export function modulesToChunks(transpilation: Transpilation, modules: Module[]): Chunk[] {
19-
return modules.map(module => {
20-
const moduleId = transpilation.getModuleId(module);
21-
const outputPath = normalizeSlashes(path.resolve(transpilation.outDir, `${moduleId.replace(/\./g, "/")}.lua`));
22-
return { outputPath, source: module.source, sourceFiles: module.sourceFiles };
23-
});
24-
}
3+
import { Chunk } from ".";
4+
import { CompilerOptions, isBundleEnabled } from "../../CompilerOptions";
5+
import { escapeString } from "../../LuaPrinter";
6+
import { assert, normalizeSlashes } from "../../utils";
7+
import { couldNotFindBundleEntryPoint } from "../diagnostics";
8+
import { Module } from "../module";
9+
import { Transpilation } from "../transpilation";
2510

2611
// Override `require` to read from ____modules table.
2712
const requireOverride = `
@@ -48,11 +33,10 @@ end
4833
export function modulesToBundleChunks(transpilation: Transpilation, modules: Module[]): Chunk[] {
4934
const options = transpilation.program.getCompilerOptions() as CompilerOptions;
5035
assert(isBundleEnabled(options));
51-
const projectDirectory = getConfigDirectory(options, transpilation.host);
52-
const outputPath = normalizeSlashes(path.resolve(projectDirectory, options.luaBundle));
5336

54-
// Resolve project settings relative to project file.
55-
const entryFileName = normalizeSlashes(path.resolve(projectDirectory, options.luaBundleEntry));
37+
const outputPath = normalizeSlashes(path.resolve(transpilation.projectDir, options.luaBundle));
38+
const entryFileName = normalizeSlashes(path.resolve(transpilation.projectDir, options.luaBundleEntry));
39+
5640
const entryModule = modules.find(m => m.request === entryFileName);
5741
if (entryModule === undefined) {
5842
transpilation.diagnostics.push(couldNotFindBundleEntryPoint(options.luaBundleEntry));

src/transpilation/chunk/index.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import * as path from "path";
2+
import { SourceNode } from "source-map";
3+
import * as ts from "typescript";
4+
import { normalizeSlashes } from "../../utils";
5+
import { Module } from "../module";
6+
import { Transpilation } from "../transpilation";
7+
8+
export * from "./bundle";
9+
export * from "./print";
10+
11+
export interface Chunk {
12+
outputPath: string;
13+
source: SourceNode;
14+
sourceFiles?: ts.SourceFile[];
15+
}
16+
17+
export function modulesToChunks(transpilation: Transpilation, modules: Module[]): Chunk[] {
18+
return modules.map(module => {
19+
const moduleId = transpilation.getModuleId(module);
20+
const outputPath = normalizeSlashes(path.resolve(transpilation.outDir, `${moduleId.replace(/\./g, "/")}.lua`));
21+
return { outputPath, source: module.source, sourceFiles: module.sourceFiles };
22+
});
23+
}
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import * as path from "path";
22
import { Mapping, SourceMapGenerator, SourceNode, StartOfSourceMap } from "source-map";
3-
import { CompilerOptions } from "../CompilerOptions";
4-
import { Chunk } from "./chunk";
3+
import { Chunk } from ".";
4+
import { CompilerOptions } from "../../CompilerOptions";
55

66
export function printChunk(chunk: Chunk, options: CompilerOptions) {
77
const sourceRoot = options.sourceRoot

src/transpilation/index.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
export * from "./managed";
1+
export { Chunk } from "./chunk";
2+
export * from "./managed-api";
3+
export { Module } from "./module";
24
export { Plugin } from "./plugins";
35
export * from "./transpile";
46
export * from "./transpiler";
Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import * as ts from "typescript";
2-
import { parseConfigFileWithSystem } from "../cli/tsconfig";
3-
import { CompilerOptions } from "../CompilerOptions";
4-
import { createEmitOutputCollector, TranspiledFile } from "./output-collector";
5-
import { EmitResult, Transpiler } from "./transpiler";
6-
import { createVirtualProgram } from "./utils";
2+
import { parseConfigFileWithSystem } from "../../cli/tsconfig";
3+
import { CompilerOptions } from "../../CompilerOptions";
4+
import { EmitResult, Transpiler } from "../transpiler";
5+
import { createEmitOutputCollector, createVirtualProgram, TranspiledFile } from "./utils";
76

87
export { TranspiledFile };
98

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import * as fs from "fs";
2+
import * as path from "path";
3+
import * as ts from "typescript";
4+
import { CompilerOptions } from "../../CompilerOptions";
5+
import { intersection, union } from "../../utils";
6+
7+
const libCache = new Map<string, ts.SourceFile>();
8+
export function createVirtualProgram(input: Record<string, string>, options: CompilerOptions = {}): ts.Program {
9+
function notImplemented(): never {
10+
throw new Error("Not implemented");
11+
}
12+
13+
const getFileFromInput = (fileName: string) =>
14+
input[fileName] ?? (fileName.startsWith("/") ? input[fileName.slice(1)] : undefined);
15+
16+
const compilerHost: ts.CompilerHost = {
17+
useCaseSensitiveFileNames: () => false,
18+
getCanonicalFileName: fileName => fileName,
19+
getCurrentDirectory: () => "/",
20+
fileExists: fileName => fileName.startsWith("lib.") || getFileFromInput(fileName) !== undefined,
21+
readFile: notImplemented,
22+
writeFile: notImplemented,
23+
getDefaultLibFileName: ts.getDefaultLibFileName,
24+
getNewLine: () => "\n",
25+
26+
getSourceFile(fileName) {
27+
const fileFromInput = getFileFromInput(fileName);
28+
if (fileFromInput !== undefined) {
29+
return ts.createSourceFile(fileName, fileFromInput, ts.ScriptTarget.Latest, false);
30+
}
31+
32+
if (libCache.has(fileName)) return libCache.get(fileName)!;
33+
34+
if (fileName.startsWith("lib.")) {
35+
const typeScriptDir = path.dirname(require.resolve("typescript"));
36+
const filePath = path.join(typeScriptDir, fileName);
37+
const content = fs.readFileSync(filePath, "utf8");
38+
39+
const sourceFile = ts.createSourceFile(fileName, content, ts.ScriptTarget.Latest, false);
40+
libCache.set(fileName, sourceFile);
41+
return sourceFile;
42+
}
43+
},
44+
};
45+
46+
return ts.createProgram(Object.keys(input), options, compilerHost);
47+
}
48+
49+
export interface TranspiledFile {
50+
sourceFiles: ts.SourceFile[];
51+
lua?: string;
52+
luaSourceMap?: string;
53+
declaration?: string;
54+
declarationMap?: string;
55+
/** @internal */
56+
js?: string;
57+
/** @internal */
58+
jsSourceMap?: string;
59+
}
60+
61+
export function createEmitOutputCollector() {
62+
const files: TranspiledFile[] = [];
63+
const writeFile: ts.WriteFileCallback = (fileName, data, _bom, _onError, sourceFiles = []) => {
64+
let file = files.find(f => intersection(f.sourceFiles, sourceFiles).length > 0);
65+
if (!file) {
66+
file = { sourceFiles: [...sourceFiles] };
67+
files.push(file);
68+
} else {
69+
file.sourceFiles = union(file.sourceFiles, sourceFiles);
70+
}
71+
72+
if (fileName.endsWith(".lua")) {
73+
file.lua = data;
74+
} else if (fileName.endsWith(".lua.map")) {
75+
file.luaSourceMap = data;
76+
} else if (fileName.endsWith(".js")) {
77+
file.js = data;
78+
} else if (fileName.endsWith(".js.map")) {
79+
file.jsSourceMap = data;
80+
} else if (fileName.endsWith(".d.ts")) {
81+
file.declaration = data;
82+
} else if (fileName.endsWith(".d.ts.map")) {
83+
file.declarationMap = data;
84+
}
85+
};
86+
87+
return { writeFile, files };
88+
}

src/transpilation/output-collector.ts

Lines changed: 0 additions & 43 deletions
This file was deleted.

src/transpilation/plugins.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { Visitors } from "../transformation/context";
44
import { Chunk } from "./chunk";
55
import { Module } from "./module";
66
import { Transpilation } from "./transpilation";
7-
import { getConfigDirectory, resolvePlugin } from "./utils";
7+
import { resolveConfigImport } from "./utils";
88

99
export interface Plugin {
1010
/**
@@ -45,10 +45,10 @@ export function getPlugins(transpilation: Transpilation, customPlugins: Plugin[]
4545
for (const [index, pluginOption] of (transpilation.options.luaPlugins ?? []).entries()) {
4646
const optionName = `tstl.luaPlugins[${index}]`;
4747

48-
const { error: resolveError, result: factory } = resolvePlugin(
48+
const { error: resolveError, result: factory } = resolveConfigImport(
4949
"plugin",
5050
`${optionName}.name`,
51-
getConfigDirectory(transpilation.options),
51+
transpilation.projectDir,
5252
pluginOption.name,
5353
pluginOption.import
5454
);

src/transpilation/transpilation.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,14 @@ export class Transpilation {
1616
public readonly diagnostics: ts.Diagnostic[] = [];
1717
public modules: Module[] = [];
1818

19+
public host: TranspilerHost;
1920
public options = this.program.getCompilerOptions() as CompilerOptions;
2021
public rootDir: string;
2122
public outDir: string;
22-
public host: TranspilerHost;
23+
public projectDir: string;
2324

24-
protected resolver: Resolver;
2525
public plugins: Plugin[];
26+
protected resolver: Resolver;
2627

2728
constructor(public transpiler: Transpiler, public program: ts.Program, extraPlugins: Plugin[]) {
2829
this.host = transpiler.host;
@@ -35,6 +36,11 @@ export class Transpilation {
3536

3637
this.outDir = this.options.outDir ?? this.rootDir;
3738

39+
this.projectDir =
40+
this.options.configFilePath !== undefined
41+
? path.dirname(this.options.configFilePath)
42+
: this.host.getCurrentDirectory();
43+
3844
this.plugins = getPlugins(this, extraPlugins);
3945

4046
this.resolver = ResolverFactory.createResolver({

0 commit comments

Comments
 (0)