forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtsc.ts
493 lines (405 loc) · 19.8 KB
/
tsc.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
/// <reference path="core.ts"/>
/// <reference path="sys.ts"/>
/// <reference path="types.ts"/>
/// <reference path="scanner.ts"/>
/// <reference path="parser.ts"/>
/// <reference path="binder.ts"/>
/// <reference path="checker.ts"/>
/// <reference path="emitter.ts"/>
/// <reference path="commandLineParser.ts"/>
module ts {
var version = "1.3.0.0";
/**
* Checks to see if the locale is in the appropriate format,
* and if it is, attempts to set the appropriate language.
*/
function validateLocaleAndSetLanguage(locale: string, errors: Diagnostic[]): boolean {
var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
if (!matchResult) {
errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, 'en', 'ja-jp'));
return false;
}
var language = matchResult[1];
var territory = matchResult[3];
// First try the entire locale, then fall back to just language if that's all we have.
if (!trySetLanguageAndTerritory(language, territory, errors) &&
!trySetLanguageAndTerritory(language, undefined, errors)) {
errors.push(createCompilerDiagnostic(Diagnostics.Unsupported_locale_0, locale));
return false;
}
return true;
}
function trySetLanguageAndTerritory(language: string, territory: string, errors: Diagnostic[]): boolean {
var compilerFilePath = normalizePath(sys.getExecutingFilePath());
var containingDirectoryPath = getDirectoryPath(compilerFilePath);
var filePath = combinePaths(containingDirectoryPath, language);
if (territory) {
filePath = filePath + "-" + territory;
}
filePath = sys.resolvePath(combinePaths(filePath, "diagnosticMessages.generated.json"));
if (!sys.fileExists(filePath)) {
return false;
}
// TODO: Add codePage support for readFile?
try {
var fileContents = sys.readFile(filePath);
}
catch (e) {
errors.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath));
return false;
}
try {
ts.localizedDiagnosticMessages = JSON.parse(fileContents);
}
catch (e) {
errors.push(createCompilerDiagnostic(Diagnostics.Corrupted_locale_file_0, filePath));
return false;
}
return true;
}
function countLines(program: Program): number {
var count = 0;
forEach(program.getSourceFiles(), file => {
count += file.getLineAndCharacterFromPosition(file.end).line;
});
return count;
}
function getDiagnosticText(message: DiagnosticMessage, ...args: any[]): string {
var diagnostic: Diagnostic = createCompilerDiagnostic.apply(undefined, arguments);
return diagnostic.messageText;
}
function reportDiagnostic(diagnostic: Diagnostic) {
var output = "";
if (diagnostic.file) {
var loc = diagnostic.file.getLineAndCharacterFromPosition(diagnostic.start);
output += diagnostic.file.filename + "(" + loc.line + "," + loc.character + "): ";
}
var category = DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + diagnostic.messageText + sys.newLine;
sys.write(output);
}
function reportDiagnostics(diagnostics: Diagnostic[]) {
for (var i = 0; i < diagnostics.length; i++) {
reportDiagnostic(diagnostics[i]);
}
}
function padLeft(s: string, length: number) {
while (s.length < length) {
s = " " + s;
}
return s;
}
function padRight(s: string, length: number) {
while (s.length < length) {
s = s + " ";
}
return s;
}
function reportStatisticalValue(name: string, value: string) {
sys.write(padRight(name + ":", 12) + padLeft(value.toString(), 10) + sys.newLine);
}
function reportCountStatistic(name: string, count: number) {
reportStatisticalValue(name, "" + count);
}
function reportTimeStatistic(name: string, time: number) {
reportStatisticalValue(name, (time / 1000).toFixed(2) + "s");
}
function createCompilerHost(options: CompilerOptions): CompilerHost {
var currentDirectory: string;
var existingDirectories: Map<boolean> = {};
function getCanonicalFileName(fileName: string): string {
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
// otherwise use toLowerCase as a canonical form.
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
// returned by CScript sys environment
var unsupportedFileEncodingErrorCode = -2147024809;
function getSourceFile(filename: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile {
try {
var text = sys.readFile(filename, options.charset);
}
catch (e) {
if (onError) {
onError(e.number === unsupportedFileEncodingErrorCode ?
getDiagnosticText(Diagnostics.Unsupported_file_encoding) :
e.message);
}
text = "";
}
return text !== undefined ? createSourceFile(filename, text, languageVersion, /*version:*/ "0") : undefined;
}
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) {
function directoryExists(directoryPath: string): boolean {
if (hasProperty(existingDirectories, directoryPath)) {
return true;
}
if (sys.directoryExists(directoryPath)) {
existingDirectories[directoryPath] = true;
return true;
}
return false;
}
function ensureDirectoriesExist(directoryPath: string) {
if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) {
var parentDirectory = getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
sys.createDirectory(directoryPath);
}
}
try {
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
sys.writeFile(fileName, data, writeByteOrderMark);
}
catch (e) {
if (onError) onError(e.message);
}
}
return {
getSourceFile: getSourceFile,
getDefaultLibFilename: () => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), "lib.d.ts"),
writeFile: writeFile,
getCurrentDirectory: () => currentDirectory || (currentDirectory = sys.getCurrentDirectory()),
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
getCanonicalFileName: getCanonicalFileName,
getNewLine: () => sys.newLine
};
}
export function executeCommandLine(args: string[]): void {
var commandLine = parseCommandLine(args);
var compilerOptions = commandLine.options;
if (compilerOptions.locale) {
if (typeof JSON === "undefined") {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--locale"));
return sys.exit(1);
}
validateLocaleAndSetLanguage(commandLine.options.locale, commandLine.errors);
}
// If there are any errors due to command line parsing and/or
// setting up localization, report them and quit.
if (commandLine.errors.length > 0) {
reportDiagnostics(commandLine.errors);
return sys.exit(EmitReturnStatus.CompilerOptionsErrors);
}
if (compilerOptions.version) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Version_0, version));
return sys.exit(EmitReturnStatus.Succeeded);
}
if (compilerOptions.help) {
printVersion();
printHelp();
return sys.exit(EmitReturnStatus.Succeeded);
}
if (commandLine.filenames.length === 0) {
printVersion();
printHelp();
return sys.exit(EmitReturnStatus.CompilerOptionsErrors);
}
var defaultCompilerHost = createCompilerHost(compilerOptions);
if (compilerOptions.watch) {
if (!sys.watchFile) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"));
return sys.exit(EmitReturnStatus.CompilerOptionsErrors);
}
watchProgram(commandLine, defaultCompilerHost);
}
else {
var result = compile(commandLine, defaultCompilerHost).exitStatus
return sys.exit(result);
}
}
/**
* Compiles the program once, and then watches all given and referenced files for changes.
* Upon detecting a file change, watchProgram will queue up file modification events for the next
* 250ms and then perform a recompilation. The reasoning is that in some cases, an editor can
* save all files at once, and we'd like to just perform a single recompilation.
*/
function watchProgram(commandLine: ParsedCommandLine, compilerHost: CompilerHost): void {
var watchers: Map<FileWatcher> = {};
var updatedFiles: Map<boolean> = {};
// Compile the program the first time and watch all given/referenced files.
var program = compile(commandLine, compilerHost).program;
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compilation_complete_Watching_for_file_changes));
addWatchers(program);
return;
function addWatchers(program: Program) {
forEach(program.getSourceFiles(), f => {
var filename = getCanonicalName(f.filename);
watchers[filename] = sys.watchFile(filename, fileUpdated);
});
}
function removeWatchers(program: Program) {
forEach(program.getSourceFiles(), f => {
var filename = getCanonicalName(f.filename);
if (hasProperty(watchers, filename)) {
watchers[filename].close();
}
});
watchers = {};
}
// Fired off whenever a file is changed.
function fileUpdated(filename: string) {
var firstNotification = isEmpty(updatedFiles);
updatedFiles[getCanonicalName(filename)] = true;
// Only start this off when the first file change comes in,
// so that we can batch up all further changes.
if (firstNotification) {
setTimeout(() => {
var changedFiles = updatedFiles;
updatedFiles = {};
recompile(changedFiles);
}, 250);
}
}
function recompile(changedFiles: Map<boolean>) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.File_change_detected_Compiling));
// Remove all the watchers, as we may not be watching every file
// specified since the last compilation cycle.
removeWatchers(program);
// Reuse source files from the last compilation so long as they weren't changed.
var oldSourceFiles = arrayToMap(
filter(program.getSourceFiles(), file => !hasProperty(changedFiles, getCanonicalName(file.filename))),
file => getCanonicalName(file.filename));
// We create a new compiler host for this compilation cycle.
// This new host is effectively the same except that 'getSourceFile'
// will try to reuse the SourceFiles from the last compilation cycle
// so long as they were not modified.
var newCompilerHost = clone(compilerHost);
newCompilerHost.getSourceFile = (fileName, languageVersion, onError) => {
fileName = getCanonicalName(fileName);
var sourceFile = lookUp(oldSourceFiles, fileName);
if (sourceFile) {
return sourceFile;
}
return compilerHost.getSourceFile(fileName, languageVersion, onError);
};
program = compile(commandLine, newCompilerHost).program;
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compilation_complete_Watching_for_file_changes));
addWatchers(program);
}
function getCanonicalName(fileName: string) {
return compilerHost.getCanonicalFileName(fileName);
}
}
function compile(commandLine: ParsedCommandLine, compilerHost: CompilerHost) {
var parseStart = new Date().getTime();
var compilerOptions = commandLine.options;
var program = createProgram(commandLine.filenames, compilerOptions, compilerHost);
var bindStart = new Date().getTime();
var errors: Diagnostic[] = program.getDiagnostics();
var exitStatus: EmitReturnStatus;
if (errors.length) {
var checkStart = bindStart;
var emitStart = bindStart;
var reportStart = bindStart;
exitStatus = EmitReturnStatus.AllOutputGenerationSkipped;
}
else {
var checker = program.getTypeChecker(/*fullTypeCheckMode*/ true);
var checkStart = new Date().getTime();
errors = checker.getDiagnostics();
if (checker.isEmitBlocked()) {
exitStatus = EmitReturnStatus.AllOutputGenerationSkipped;
}
else {
var emitStart = new Date().getTime();
var emitOutput = checker.emitFiles();
var emitErrors = emitOutput.errors;
exitStatus = emitOutput.emitResultStatus;
var reportStart = new Date().getTime();
errors = concatenate(errors, emitErrors);
}
}
reportDiagnostics(errors);
if (commandLine.options.diagnostics) {
var memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1;
reportCountStatistic("Files", program.getSourceFiles().length);
reportCountStatistic("Lines", countLines(program));
reportCountStatistic("Nodes", checker ? checker.getNodeCount() : 0);
reportCountStatistic("Identifiers", checker ? checker.getIdentifierCount() : 0);
reportCountStatistic("Symbols", checker ? checker.getSymbolCount() : 0);
reportCountStatistic("Types", checker ? checker.getTypeCount() : 0);
if (memoryUsed >= 0) {
reportStatisticalValue("Memory used", Math.round(memoryUsed / 1000) + "K");
}
reportTimeStatistic("Parse time", bindStart - parseStart);
reportTimeStatistic("Bind time", checkStart - bindStart);
reportTimeStatistic("Check time", emitStart - checkStart);
reportTimeStatistic("Emit time", reportStart - emitStart);
reportTimeStatistic("Total time", reportStart - parseStart);
}
return { program: program, exitStatus: exitStatus }
}
function printVersion() {
sys.write(getDiagnosticText(Diagnostics.Version_0, version) + sys.newLine);
}
function printHelp() {
var output = "";
// We want to align our "syntax" and "examples" commands to a certain margin.
var syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length;
var examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length;
var marginLength = Math.max(syntaxLength, examplesLength);
// Build up the syntactic skeleton.
var syntax = makePadding(marginLength - syntaxLength);
syntax += "tsc [" + getDiagnosticText(Diagnostics.options) + "] [" + getDiagnosticText(Diagnostics.file) + " ...]";
output += getDiagnosticText(Diagnostics.Syntax_Colon_0, syntax);
output += sys.newLine + sys.newLine;
// Build up the list of examples.
var padding = makePadding(marginLength);
output += getDiagnosticText(Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine;
output += padding + "tsc --out file.js file.ts" + sys.newLine;
output += padding + "tsc @args.txt" + sys.newLine;
output += sys.newLine;
output += getDiagnosticText(Diagnostics.Options_Colon) + sys.newLine;
// Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch")
var optsList = optionDeclarations.slice();
optsList.sort((a, b) => compareValues<string>(a.name.toLowerCase(), b.name.toLowerCase()));
// We want our descriptions to align at the same column in our output,
// so we keep track of the longest option usage string.
var marginLength = 0;
var usageColumn: string[] = []; // Things like "-d, --declaration" go in here.
var descriptionColumn: string[] = [];
for (var i = 0; i < optsList.length; i++) {
var option = optsList[i];
// If an option lacks a description,
// it is not officially supported.
if (!option.description) {
continue;
}
var usageText = " ";
if (option.shortName) {
usageText += "-" + option.shortName;
usageText += getParamName(option);
usageText += ", ";
}
usageText += "--" + option.name;
usageText += getParamName(option);
usageColumn.push(usageText);
descriptionColumn.push(getDiagnosticText(option.description));
// Set the new margin for the description column if necessary.
marginLength = Math.max(usageText.length, marginLength);
}
// Special case that can't fit in the loop.
var usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">";
usageColumn.push(usageText);
descriptionColumn.push(getDiagnosticText(Diagnostics.Insert_command_line_options_and_files_from_a_file));
marginLength = Math.max(usageText.length, marginLength);
// Print out each row, aligning all the descriptions on the same column.
for (var i = 0; i < usageColumn.length; i++) {
var usage = usageColumn[i];
var description = descriptionColumn[i];
output += usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine;
}
sys.write(output);
return;
function getParamName(option: CommandLineOption) {
if (option.paramName !== undefined) {
return " " + getDiagnosticText(option.paramName);
}
return "";
}
function makePadding(paddingLength: number): string {
return Array(paddingLength + 1).join(" ");
}
}
}
ts.executeCommandLine(sys.args);