forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.ts
206 lines (182 loc) · 5.6 KB
/
compiler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import * as ts from "typescript";
import { log, assert, globalEval } from "./util";
import { exit, readFileSync } from "./os";
import * as path from "path";
export function compile(cwd: string, inputFn: string): void {
const options: ts.CompilerOptions = {
allowJs: true,
outDir: "_denoCache_/",
};
const host = new CompilerHost(cwd);
const inputExt = path.extname(inputFn);
if (!EXTENSIONS.includes(inputExt)) {
console.error(`Bad file name extension for input "${inputFn}"`);
exit(1);
}
const program = ts.createProgram([inputFn], options, host);
//let sourceFiles = program.getSourceFiles();
//log("rootFileNames", program.getRootFileNames());
// Print compilation errors, if any.
const diagnostics = getDiagnostics(program);
if (diagnostics.length > 0) {
const errorMessages = diagnostics.map(d => formatDiagnostic(d, cwd));
for (const msg of errorMessages) {
console.error(msg);
}
exit(2);
}
const emitResult = program.emit();
assert(!emitResult.emitSkipped);
log("emitResult", emitResult);
}
/**
* Format a diagnostic object into a string.
* Adapted from TS-Node https://github.com/TypeStrong/ts-node
* which uses the same MIT license as this file but is
* Copyright (c) 2014 Blake Embrey ([email protected])
*/
export function formatDiagnostic(
diagnostic: ts.Diagnostic,
cwd: string,
lineOffset = 0
): string {
const messageText = ts.flattenDiagnosticMessageText(
diagnostic.messageText,
"\n"
);
const { code } = diagnostic;
if (diagnostic.file) {
const fn = path.relative(cwd, diagnostic.file.fileName);
if (diagnostic.start) {
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(
diagnostic.start
);
const r = Number(line) + 1 + lineOffset;
const c = Number(character) + 1;
return `${fn} (${r},${c}): ${messageText} (${code})`;
}
return `${fn}: ${messageText} (${code})`;
}
return `${messageText} (${code})`;
}
function getDiagnostics(program: ts.Program): ReadonlyArray<ts.Diagnostic> {
return program
.getOptionsDiagnostics()
.concat(
program.getGlobalDiagnostics(),
program.getSyntacticDiagnostics(),
program.getSemanticDiagnostics(),
program.getDeclarationDiagnostics()
);
}
const EXTENSIONS = [".ts", ".js"];
export class CompilerHost {
constructor(public cwd: string) {}
getSourceFile(
fileName: string,
languageVersion: ts.ScriptTarget,
onError?: (message: string) => void,
shouldCreateNewSourceFile?: boolean
): ts.SourceFile | undefined {
let sourceText: string;
if (fileName === "lib.d.ts") {
// TODO this should be compiled into the bindata.
sourceText = readFileSync("node_modules/typescript/lib/lib.d.ts");
} else {
sourceText = readFileSync(fileName);
}
if (sourceText) {
log("getSourceFile", {
fileName
//sourceText,
});
return ts.createSourceFile(fileName, sourceText, languageVersion);
} else {
log("getSourceFile NOT FOUND", { fileName });
return undefined;
}
}
getSourceFileByPath?(
fileName: string,
path: ts.Path,
languageVersion: ts.ScriptTarget,
onError?: (message: string) => void,
shouldCreateNewSourceFile?: boolean
): ts.SourceFile | undefined {
console.log("getSourceFileByPath", fileName);
return undefined;
}
// getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: ts.CompilerOptions): string {
return ts.getDefaultLibFileName(options);
}
getDefaultLibLocation(): string {
return "/blah/";
}
writeFile(
fileName: string,
data: string,
writeByteOrderMark: boolean,
onError: ((message: string) => void) | undefined,
sourceFiles: ReadonlyArray<ts.SourceFile>
): void {
log("writeFile", { fileName, data });
globalEval(data);
}
getCurrentDirectory(): string {
log("getCurrentDirectory", this.cwd);
return this.cwd;
}
getDirectories(path: string): string[] {
log("getDirectories", path);
return [];
}
getCanonicalFileName(fileName: string): string {
return fileName;
}
useCaseSensitiveFileNames(): boolean {
return true;
}
getNewLine(): string {
return "\n";
}
resolveModuleNames(
moduleNames: string[],
containingFile: string,
reusedNames?: string[]
): Array<ts.ResolvedModule | undefined> {
log("resolveModuleNames", { moduleNames, reusedNames });
return moduleNames.map((name: string) => {
if (
name.startsWith("/") ||
name.startsWith("http:https://") ||
name.startsWith("https://")
) {
throw Error("Non-relative imports not yet supported.");
} else {
// Relative import.
const containingDir = path.dirname(containingFile);
const resolvedFileName = path.join(containingDir, name);
log("relative import", { containingFile, name, resolvedFileName });
const isExternalLibraryImport = false;
return { resolvedFileName, isExternalLibraryImport };
}
});
}
fileExists(fileName: string): boolean {
log("fileExists", fileName);
return false;
}
readFile(fileName: string): string | undefined {
log("readFile", fileName);
return undefined;
}
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve
* 'types' references to actual type declaration files
*/
// resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[],
// containingFile: string): (ResolvedTypeReferenceDirective | undefined)[];
// getEnvironmentVariable?(name: string): string
// createHash?(data: string): string;
}