-
Notifications
You must be signed in to change notification settings - Fork 12.6k
/
harness.ts
1382 lines (1160 loc) · 60 KB
/
harness.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/// <reference path='..\services\services.ts' />
/// <reference path='..\services\shims.ts' />
/// <reference path='..\compiler\sys.ts' />
/// <reference path='external\mocha.d.ts'/>
/// <reference path='external\chai.d.ts'/>
/// <reference path='sourceMapRecorder.ts'/>
// this will work in the browser via browserify
var _chai: typeof chai = require('chai');
var assert: typeof _chai.assert = _chai.assert;
declare var __dirname: any; // Node-specific
var global = <any>Function("return this").call(null);
module Utils {
var global = <any>Function("return this").call(null);
// Setup some globals based on the current environment
export enum ExecutionEnvironment {
Node,
Browser,
CScript
}
export function getExecutionEnvironment() {
if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
return ExecutionEnvironment.CScript;
} else if (process && (<any>process).execPath && (<any>process).execPath.indexOf("node") !== -1) {
return ExecutionEnvironment.Node;
} else {
return ExecutionEnvironment.Browser;
}
}
export var currentExecutionEnvironment = getExecutionEnvironment();
export function evalFile(fileContents: string, filename: string, nodeContext?: any) {
var environment = getExecutionEnvironment();
switch (environment) {
case ExecutionEnvironment.CScript:
case ExecutionEnvironment.Browser:
eval(fileContents);
break;
case ExecutionEnvironment.Node:
var vm = require('vm');
if (nodeContext) {
vm.runInNewContext(fileContents, nodeContext, filename);
} else {
vm.runInThisContext(fileContents, filename);
}
break;
default:
throw new Error('Unknown context');
}
}
/** Splits the given string on \r\n or on only \n if that fails */
export function splitContentByNewlines(content: string) {
// Split up the input file by line
// Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so
// we have to string-based splitting instead and try to figure out the delimiting chars
var lines = content.split('\r\n');
if (lines.length === 1) {
lines = content.split('\n');
}
return lines;
}
/** Reads a file under /tests */
export function readTestFile(path: string) {
if (path.indexOf('tests') < 0) {
path = "tests/" + path;
}
try {
var content = sys.readFile(Harness.userSpecifiedroot + path);
}
catch (err) {
return undefined;
}
return content;
}
export function memoize<T extends Function>(f: T): T {
var cache: { [idx: string]: any } = {};
return <any>(() => {
var key = Array.prototype.join.call(arguments);
var cachedResult = cache[key];
if (cachedResult) {
return cachedResult;
} else {
return cache[key] = f.apply(this, arguments);
}
});
}
}
module Harness.Path {
export function getFileName(fullPath: string) {
return fullPath.replace(/^.*[\\\/]/, '');
}
export function filePath(fullPath: string) {
fullPath = switchToForwardSlashes(fullPath);
var components = fullPath.split("/");
var path: string[] = components.slice(0, components.length - 1);
return path.join("/") + "/";
}
export function switchToForwardSlashes(path: string) {
return path.replace(/\\/g, "/").replace(/\/\//g, '/');
}
}
module Harness {
export interface IO {
readFile(path: string): string;
writeFile(path: string, contents: string): void;
directoryName(path: string): string;
createDirectory(path: string): void;
fileExists(filename: string): boolean;
directoryExists(path: string): boolean;
deleteFile(filename: string): void;
listFiles(path: string, filter: RegExp, options?: { recursive?: boolean }): string[];
log(text: string): void;
getMemoryUsage? (): number;
}
module IOImpl {
declare class Enumerator {
public atEnd(): boolean;
public moveNext(): boolean;
public item(): any;
constructor(o: any);
}
export module CScript {
var fso: any;
if (global.ActiveXObject) {
fso = new global.ActiveXObject("Scripting.FileSystemObject");
} else {
fso = {};
}
export var readFile: typeof IO.readFile = sys.readFile;
export var writeFile: typeof IO.writeFile = sys.writeFile;
export var directoryName: typeof IO.directoryName = fso.GetParentFolderName;
export var directoryExists: typeof IO.directoryExists = fso.FolderExists;
export var fileExists: typeof IO.fileExists = fso.FileExists;
export var log: typeof IO.log = global.WScript && global.WScript.StdOut.WriteLine;
export function createDirectory(path: string) {
if (directoryExists(path)) {
fso.CreateFolder(path);
}
}
export function deleteFile(path: string) {
if (fileExists(path)) {
fso.DeleteFile(path, true); // true: delete read-only files
}
}
export var listFiles: typeof IO.listFiles = (path, spec?, options?) => {
options = options || <{ recursive?: boolean; }>{};
function filesInFolder(folder: any, root: string): string[] {
var paths: string[] = [];
var fc: any;
if (options.recursive) {
fc = new Enumerator(folder.subfolders);
for (; !fc.atEnd(); fc.moveNext()) {
paths = paths.concat(filesInFolder(fc.item(), root + "\\" + fc.item().Name));
}
}
fc = new Enumerator(folder.files);
for (; !fc.atEnd(); fc.moveNext()) {
if (!spec || fc.item().Name.match(spec)) {
paths.push(root + "\\" + fc.item().Name);
}
}
return paths;
}
var folder: any = fso.GetFolder(path);
var paths: string[] = [];
return filesInFolder(folder, path);
}
}
export module Node {
declare var require: any;
var fs: any, pathModule: any;
if (require) {
fs = require('fs');
pathModule = require('path');
} else {
fs = pathModule = {};
}
export var readFile: typeof IO.readFile = sys.readFile;
export var writeFile: typeof IO.writeFile = sys.writeFile;
export var fileExists: typeof IO.fileExists = fs.existsSync;
export var log: typeof IO.log = console.log;
export function createDirectory(path: string) {
if (!directoryExists(path)) {
fs.mkdirSync(path);
}
}
export function deleteFile(path: string) {
try {
fs.unlinkSync(path);
} catch (e) {
}
}
export function directoryExists(path: string): boolean {
return fs.existsSync(path) && fs.statSync(path).isDirectory();
}
export function directoryName(path: string) {
var dirPath = pathModule.dirname(path);
// Node will just continue to repeat the root path, rather than return null
if (dirPath === path) {
dirPath = null;
} else {
return dirPath;
}
}
export var listFiles: typeof IO.listFiles = (path, spec?, options?) => {
options = options || <{ recursive?: boolean; }>{};
function filesInFolder(folder: string): string[] {
var paths: string[] = [];
var files = fs.readdirSync(folder);
for (var i = 0; i < files.length; i++) {
var pathToFile = pathModule.join(folder, files[i]);
var stat = fs.statSync(pathToFile);
if (options.recursive && stat.isDirectory()) {
paths = paths.concat(filesInFolder(pathToFile));
}
else if (stat.isFile() && (!spec || files[i].match(spec))) {
paths.push(pathToFile);
}
}
return paths;
}
return filesInFolder(path);
}
export var getMemoryUsage: typeof IO.getMemoryUsage = () => {
if (global.gc) {
global.gc();
}
return process.memoryUsage().heapUsed;
}
}
export module Network {
var serverRoot = "http://localhost:8888/";
// Unused?
var newLine = '\r\n';
var currentDirectory = () => '';
var supportsCodePage = () => false;
module Http {
function waitForXHR(xhr: XMLHttpRequest) {
while (xhr.readyState !== 4) { }
return { status: xhr.status, responseText: xhr.responseText };
}
/// Ask the server to use node's path.resolve to resolve the given path
function getResolvedPathFromServer(path: string) {
var xhr = new XMLHttpRequest();
try {
xhr.open("GET", path + "?resolve", false);
xhr.send();
}
catch (e) {
return { status: 404, responseText: null };
}
return waitForXHR(xhr);
}
export interface XHRResponse {
status: number;
responseText: string;
}
/// Ask the server for the contents of the file at the given URL via a simple GET request
export function getFileFromServerSync(url: string): XHRResponse {
var xhr = new XMLHttpRequest();
try {
xhr.open("GET", url, false);
xhr.send();
}
catch (e) {
return { status: 404, responseText: null };
}
return waitForXHR(xhr);
}
/// Submit a POST request to the server to do the given action (ex WRITE, DELETE) on the provided URL
export function writeToServerSync(url: string, action: string, contents?: string): XHRResponse {
var xhr = new XMLHttpRequest();
try {
var action = '?action=' + action;
xhr.open('POST', url + action, false);
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.send(contents);
}
catch (e) {
return { status: 500, responseText: null };
}
return waitForXHR(xhr);
}
}
export function createDirectory(path: string) {
// Do nothing (?)
}
export function deleteFile(path: string) {
Http.writeToServerSync(serverRoot + path, 'DELETE', null);
}
export function directoryExists(path: string): boolean {
return false;
}
function directoryNameImpl(path: string) {
var dirPath = path;
// root of the server
if (dirPath.match(/localhost:\d+$/) || dirPath.match(/localhost:\d+\/$/)) {
dirPath = null;
// path + filename
} else if (dirPath.indexOf('.') === -1) {
dirPath = dirPath.substring(0, dirPath.lastIndexOf('/'));
// path
} else {
// strip any trailing slash
if (dirPath.match(/.*\/$/)) {
dirPath = dirPath.substring(0, dirPath.length - 2);
}
var dirPath = dirPath.substring(0, dirPath.lastIndexOf('/'));
}
return dirPath;
}
export var directoryName: typeof IO.directoryName = Utils.memoize(directoryNameImpl);
export function fileExists(path: string): boolean {
var response = Http.getFileFromServerSync(serverRoot + path);
return response.status === 200;
}
export function _listFilesImpl(path: string, spec?: RegExp, options?: any) {
var response = Http.getFileFromServerSync(serverRoot + path);
if (response.status === 200) {
var results = response.responseText.split(',');
if (spec) {
return results.filter(file => spec.test(file));
} else {
return results;
}
}
else {
return [''];
}
};
export var listFiles = Utils.memoize(_listFilesImpl);
export var log = console.log;
export function readFile(file: string) {
var response = Http.getFileFromServerSync(serverRoot + file);
if (response.status === 200) {
return response.responseText;
} else {
return null;
}
}
export function writeFile(path: string, contents: string) {
Http.writeToServerSync(serverRoot + path, 'WRITE', contents);
}
}
}
export var IO: IO;
switch (Utils.getExecutionEnvironment()) {
case Utils.ExecutionEnvironment.CScript:
IO = IOImpl.CScript;
break;
case Utils.ExecutionEnvironment.Node:
IO = IOImpl.Node;
break;
case Utils.ExecutionEnvironment.Browser:
IO = IOImpl.Network;
break;
}
}
module Harness {
var tcServicesFilename = "typescriptServices.js";
export var libFolder: string;
switch (Utils.getExecutionEnvironment()) {
case Utils.ExecutionEnvironment.CScript:
libFolder = "built/local/";
tcServicesFilename = "built/local/typescriptServices.js";
break;
case Utils.ExecutionEnvironment.Node:
libFolder = "built/local/";
tcServicesFilename = "built/local/typescriptServices.js";
break;
case Utils.ExecutionEnvironment.Browser:
libFolder = "built/local/";
tcServicesFilename = "built/local/typescriptServices.js";
break;
default:
throw new Error('Unknown context');
}
export var tcServicesFile = IO.readFile(tcServicesFilename);
export interface SourceMapEmitterCallback {
(emittedFile: string, emittedLine: number, emittedColumn: number, sourceFile: string, sourceLine: number, sourceColumn: number, sourceName: string): void;
}
// Settings
export var userSpecifiedroot = "";
/** Functionality for compiling TypeScript code */
export module Compiler {
/** Aggregate various writes into a single array of lines. Useful for passing to the
* TypeScript compiler to fill with source code or errors.
*/
export class WriterAggregator implements ITextWriter {
public lines: string[] = [];
public currentLine = <string>undefined;
public Write(str: string) {
// out of memory usage concerns avoid using + or += if we're going to do any manipulation of this string later
this.currentLine = [(this.currentLine || ''), str].join('');
}
public WriteLine(str: string) {
// out of memory usage concerns avoid using + or += if we're going to do any manipulation of this string later
this.lines.push([(this.currentLine || ''), str].join(''));
this.currentLine = undefined;
}
public Close() {
if (this.currentLine !== undefined) { this.lines.push(this.currentLine); }
this.currentLine = undefined;
}
public reset() {
this.lines = [];
this.currentLine = undefined;
}
}
export interface IEmitterIOHost {
writeFile(path: string, contents: string, writeByteOrderMark: boolean): void;
resolvePath(path: string): string;
}
/** Mimics having multiple files, later concatenated to a single file. */
export class EmitterIOHost implements IEmitterIOHost {
private fileCollection: any = {};
/** create file gets the whole path to create, so this works as expected with the --out parameter */
public writeFile(s: string, contents: string, writeByteOrderMark: boolean): void {
var writer: ITextWriter;
if (this.fileCollection[s]) {
writer = <ITextWriter>this.fileCollection[s];
}
else {
writer = new Harness.Compiler.WriterAggregator();
this.fileCollection[s] = writer;
}
writer.Write(contents);
writer.Close();
}
public resolvePath(s: string) { return s; }
public reset() { this.fileCollection = {}; }
public toArray(): { fileName: string; file: WriterAggregator; }[] {
var result: { fileName: string; file: WriterAggregator; }[] = [];
for (var p in this.fileCollection) {
if (this.fileCollection.hasOwnProperty(p)) {
var current = <Harness.Compiler.WriterAggregator>this.fileCollection[p];
if (current.lines.length > 0) {
if (p.indexOf('.d.ts') !== -1) { current.lines.unshift(['////[', Path.getFileName(p), ']'].join('')); }
result.push({ fileName: p, file: this.fileCollection[p] });
}
}
}
return result;
}
}
export var defaultLibFileName = 'lib.d.ts';
export var defaultLibSourceFile = ts.createSourceFile(defaultLibFileName, IO.readFile(libFolder + 'lib.core.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest, /*version:*/ "0");
// Cache these between executions so we don't have to re-parse them for every test
export var fourslashFilename = 'fourslash.ts';
export var fourslashSourceFile: ts.SourceFile;
export function getCanonicalFileName(fileName: string): string {
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
export function createCompilerHost(inputFiles: { unitName: string; content: string; }[],
writeFile: (fn: string, contents: string, writeByteOrderMark: boolean) => void,
scriptTarget: ts.ScriptTarget,
useCaseSensitiveFileNames: boolean): ts.CompilerHost {
// Local get canonical file name function, that depends on passed in parameter for useCaseSensitiveFileNames
function getCanonicalFileName(fileName: string): string {
return useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
var filemap: { [filename: string]: ts.SourceFile; } = {};
// Register input files
function register(file: { unitName: string; content: string; }) {
if (file.content !== undefined) {
var filename = Path.switchToForwardSlashes(file.unitName);
filemap[getCanonicalFileName(filename)] = ts.createSourceFile(filename, file.content, scriptTarget, /*version:*/ "0");
}
};
inputFiles.forEach(register);
return {
getCurrentDirectory: sys.getCurrentDirectory,
getCancellationToken: (): any => undefined,
getSourceFile: (fn, languageVersion) => {
if (Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(fn))) {
return filemap[getCanonicalFileName(fn)];
}
else if (fn === fourslashFilename) {
var tsFn = 'tests/cases/fourslash/' + fourslashFilename;
fourslashSourceFile = fourslashSourceFile || ts.createSourceFile(tsFn, Harness.IO.readFile(tsFn), scriptTarget, /*version*/ "0", /*isOpen*/ false);
return fourslashSourceFile;
}
else {
var lib = defaultLibFileName;
if (fn === defaultLibFileName) {
return defaultLibSourceFile;
}
// Don't throw here -- the compiler might be looking for a test that actually doesn't exist as part of the TC
return null;
}
},
getDefaultLibFilename: () => defaultLibFileName,
writeFile: writeFile,
getCanonicalFileName: getCanonicalFileName,
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
getNewLine: ()=> sys.newLine
};
}
export class HarnessCompiler {
private inputFiles: { unitName: string; content: string }[] = [];
private compileOptions: ts.CompilerOptions;
private settings: Harness.TestCaseParser.CompilerSetting[] = [];
private lastErrors: HarnessDiagnostic[];
public reset() {
this.inputFiles = [];
this.settings = [];
this.lastErrors = [];
}
public reportCompilationErrors() {
return this.lastErrors;
}
public setCompilerSettingsFromOptions(tcSettings: ts.CompilerOptions) {
this.settings = Object.keys(tcSettings).map(k => ({ flag: k, value: (<any>tcSettings)[k] }));
}
public setCompilerSettings(tcSettings: Harness.TestCaseParser.CompilerSetting[]) {
this.settings = tcSettings;
}
public addInputFiles(files: { unitName: string; content: string }[]) {
files.forEach(file => this.addInputFile(file));
}
public addInputFile(file: { unitName: string; content: string }) {
this.inputFiles.push(file);
}
public setCompilerOptions(options?: ts.CompilerOptions) {
this.compileOptions = options || { noResolve: false };
}
public emitAll(ioHost?: IEmitterIOHost) {
this.compileFiles(this.inputFiles, [], (result) => {
result.files.forEach(file => {
ioHost.writeFile(file.fileName, file.code, false);
});
result.declFilesCode.forEach(file => {
ioHost.writeFile(file.fileName, file.code, false);
});
result.sourceMaps.forEach(file => {
ioHost.writeFile(file.fileName, file.code, false);
});
}, () => { }, this.compileOptions);
}
public compileFiles(inputFiles: { unitName: string; content: string }[],
otherFiles: { unitName: string; content: string }[],
onComplete: (result: CompilerResult, checker: ts.TypeChecker) => void,
settingsCallback?: (settings: ts.CompilerOptions) => void,
options?: ts.CompilerOptions) {
options = options || { noResolve: false };
options.target = options.target || ts.ScriptTarget.ES3;
options.module = options.module || ts.ModuleKind.None;
options.noErrorTruncation = true;
if (settingsCallback) {
settingsCallback(null);
}
var useCaseSensitiveFileNames = sys.useCaseSensitiveFileNames;
this.settings.forEach(setting => {
switch (setting.flag.toLowerCase()) {
// "filename", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out", "outdir", "noimplicitany", "noresolve"
case "module":
case "modulegentarget":
if (typeof setting.value === 'string') {
if (setting.value.toLowerCase() === 'amd') {
options.module = ts.ModuleKind.AMD;
} else if (setting.value.toLowerCase() === 'commonjs') {
options.module = ts.ModuleKind.CommonJS;
} else if (setting.value.toLowerCase() === 'unspecified') {
options.module = ts.ModuleKind.None;
} else {
throw new Error('Unknown module type ' + setting.value);
}
} else {
options.module = <any>setting.value;
}
break;
case "target":
case 'codegentarget':
if (typeof setting.value === 'string') {
if (setting.value.toLowerCase() === 'es3') {
options.target = ts.ScriptTarget.ES3;
} else if (setting.value.toLowerCase() === 'es5') {
options.target = ts.ScriptTarget.ES5;
} else if (setting.value.toLowerCase() === 'es6') {
options.target = ts.ScriptTarget.ES6;
} else {
throw new Error('Unknown compile target ' + setting.value);
}
} else {
options.target = <any>setting.value;
}
break;
case 'noresolve':
options.noResolve = !!setting.value;
break;
case 'noimplicitany':
options.noImplicitAny = !!setting.value;
break;
case 'nolib':
options.noLib = !!setting.value;
break;
case 'out':
case 'outfileoption':
options.out = setting.value;
break;
case 'outdiroption':
case 'outdir':
options.outDir = setting.value;
break;
case 'sourceroot':
options.sourceRoot = setting.value;
break;
case 'sourcemap':
options.sourceMap = !!setting.value;
break;
case 'declaration':
options.declaration = !!setting.value;
break;
case 'newline':
case 'newlines':
sys.newLine = setting.value;
break;
case 'comments':
options.removeComments = setting.value === 'false';
break;
case 'usecasesensitivefilenames':
useCaseSensitiveFileNames = setting.value === 'true';
break;
case 'mapsourcefiles':
case 'maproot':
case 'generatedeclarationfiles':
case 'gatherDiagnostics':
case 'codepage':
case 'createFileLog':
case 'filename':
case 'propagateenumconstants':
case 'removecomments':
case 'watch':
case 'allowautomaticsemicoloninsertion':
case 'locale':
// Not supported yet
break;
case 'emitbom':
options.emitBOM = !!setting.value;
break;
case 'errortruncation':
options.noErrorTruncation = setting.value === 'false';
break;
default:
throw new Error('Unsupported compiler setting ' + setting.flag);
}
});
var filemap: { [name: string]: ts.SourceFile; } = {};
var register = (file: { unitName: string; content: string; }) => {
if (file.content !== undefined) {
var filename = Path.switchToForwardSlashes(file.unitName);
filemap[getCanonicalFileName(filename)] = ts.createSourceFile(filename, file.content, options.target, /*version:*/ "0");
}
};
inputFiles.forEach(register);
otherFiles.forEach(register);
var fileOutputs: GeneratedFile[] = [];
var programFiles = inputFiles.map(file => file.unitName);
var program = ts.createProgram(programFiles, options, createCompilerHost(inputFiles.concat(otherFiles),
(fn, contents, writeByteOrderMark) => fileOutputs.push({ fileName: fn, code: contents, writeByteOrderMark: writeByteOrderMark }),
options.target,
useCaseSensitiveFileNames));
var hadParseErrors = program.getDiagnostics().length > 0;
var checker = program.getTypeChecker(/*fullTypeCheckMode*/ true);
checker.checkProgram();
var hasEarlyErrors = checker.hasEarlyErrors();
// only emit if there weren't parse errors
var emitResult: ts.EmitResult;
if (!hadParseErrors && !hasEarlyErrors) {
emitResult = checker.emitFiles();
}
var errors: HarnessDiagnostic[] = [];
program.getDiagnostics().concat(checker.getDiagnostics()).concat(emitResult ? emitResult.errors : []).forEach(err => {
// TODO: new compiler formats errors after this point to add . and newlines so we'll just do it manually for now
errors.push(getMinimalDiagnostic(err));
});
this.lastErrors = errors;
var result = new CompilerResult(fileOutputs, errors, program, sys.getCurrentDirectory(), emitResult ? emitResult.sourceMaps : undefined);
onComplete(result, checker);
// reset what newline means in case the last test changed it
sys.newLine = '\r\n';
return options;
}
public compileDeclarationFiles(inputFiles: { unitName: string; content: string; }[],
otherFiles: { unitName: string; content: string; }[],
result: CompilerResult,
settingsCallback?: (settings: ts.CompilerOptions) => void,
options?: ts.CompilerOptions) {
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length !== result.files.length) {
throw new Error('There were no errors and declFiles generated did not match number of js files generated');
}
// if the .d.ts is non-empty, confirm it compiles correctly as well
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length > 0) {
var declInputFiles: { unitName: string; content: string }[] = [];
var declOtherFiles: { unitName: string; content: string }[] = [];
var declResult: Harness.Compiler.CompilerResult;
ts.forEach(inputFiles, file => addDtsFile(file, declInputFiles));
ts.forEach(otherFiles, file => addDtsFile(file, declOtherFiles));
this.compileFiles(declInputFiles, declOtherFiles, function (compileResult) {
declResult = compileResult;
}, settingsCallback, options);
return { declInputFiles: declInputFiles, declOtherFiles: declOtherFiles, declResult: declResult };
}
function addDtsFile(file: { unitName: string; content: string }, dtsFiles: { unitName: string; content: string }[]) {
if (isDTS(file.unitName)) {
dtsFiles.push(file);
}
else if (isTS(file.unitName)) {
var declFile = findResultCodeFile(file.unitName);
if (!findUnit(declFile.fileName, declInputFiles) && !findUnit(declFile.fileName, declOtherFiles)) {
dtsFiles.push({ unitName: declFile.fileName, content: declFile.code });
}
}
function findResultCodeFile(fileName: string) {
var dTsFileName = ts.forEach(result.program.getSourceFiles(), sourceFile => {
if (sourceFile.filename === fileName) {
// Is this file going to be emitted separately
var sourceFileName: string;
if (ts.isExternalModule(sourceFile) || !options.out) {
if (options.outDir) {
var sourceFilePath = ts.getNormalizedPathFromPathComponents(ts.getNormalizedPathComponents(sourceFile.filename, result.currentDirectoryForProgram));
sourceFilePath = sourceFilePath.replace(result.program.getCommonSourceDirectory(), "");
sourceFileName = ts.combinePaths(options.outDir, sourceFilePath);
}
else {
sourceFileName = sourceFile.filename;
}
}
else {
// Goes to single --out file
sourceFileName = options.out;
}
return ts.removeFileExtension(sourceFileName) + ".d.ts";
}
});
return ts.forEach(result.declFilesCode, declFile => declFile.fileName === dTsFileName ? declFile : undefined);
}
function findUnit(fileName: string, units: { unitName: string; content: string; }[]) {
return ts.forEach(units, unit => unit.unitName === fileName ? unit : undefined);
}
}
}
}
export function getMinimalDiagnostic(err: ts.Diagnostic): HarnessDiagnostic {
var errorLineInfo = err.file ? err.file.getLineAndCharacterFromPosition(err.start) : { line: 0, character: 0 };
return {
filename: err.file && err.file.filename,
start: err.start,
end: err.start + err.length,
line: errorLineInfo.line,
character: errorLineInfo.character,
message: err.messageText,
category: ts.DiagnosticCategory[err.category].toLowerCase(),
code: err.code
};
}
export function minimalDiagnosticsToString(diagnostics: HarnessDiagnostic[]) {
// This is basically copied from tsc.ts's reportError to replicate what tsc does
var errorOutput = "";
ts.forEach(diagnostics, diagnotic => {
if (diagnotic.filename) {
errorOutput += diagnotic.filename + "(" + diagnotic.line + "," + diagnotic.character + "): ";
}
errorOutput += diagnotic.category + " TS" + diagnotic.code + ": " + diagnotic.message + sys.newLine;
});
return errorOutput;
}
export function getErrorBaseline(inputFiles: { unitName: string; content: string }[], diagnostics: HarnessDiagnostic[]) {
var outputLines: string[] = [];
// Count up all the errors we find so we don't miss any
var totalErrorsReported = 0;
function outputErrorText(error: Harness.Compiler.HarnessDiagnostic) {
var errLines = RunnerBase.removeFullPaths(error.message)
.split('\n')
.map(s => s.length > 0 && s.charAt(s.length - 1) === '\r' ? s.substr(0, s.length - 1) : s)
.filter(s => s.length > 0)
.map(s => '!!! ' + error.category + " TS" + error.code + ": " + s);
errLines.forEach(e => outputLines.push(e));
totalErrorsReported++;
}
// Report global errors
var globalErrors = diagnostics.filter(err => !err.filename);
globalErrors.forEach(err => outputErrorText(err));
// 'merge' the lines of each input file with any errors associated with it
inputFiles.filter(f => f.content !== undefined).forEach(inputFile => {
// Filter down to the errors in the file
var fileErrors = diagnostics.filter(e => {
var errFn = e.filename;
return errFn && errFn === inputFile.unitName;
});
// Header
outputLines.push('==== ' + inputFile.unitName + ' (' + fileErrors.length + ' errors) ====');
// Make sure we emit something for every error
var markedErrorCount = 0;
// For each line, emit the line followed by any error squiggles matching this line
// Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so
// we have to string-based splitting instead and try to figure out the delimiting chars
var lineStarts = ts.getLineStarts(inputFile.content);
var lines = inputFile.content.split('\n');
lines.forEach((line, lineIndex) => {
if (line.length > 0 && line.charAt(line.length - 1) === '\r') {
line = line.substr(0, line.length - 1);
}
var thisLineStart = lineStarts[lineIndex];
var nextLineStart: number;
// On the last line of the file, fake the next line start number so that we handle errors on the last character of the file correctly
if (lineIndex === lines.length - 1) {
nextLineStart = inputFile.content.length;
} else {
nextLineStart = lineStarts[lineIndex + 1];
}
// Emit this line from the original file
outputLines.push(' ' + line);
fileErrors.forEach(err => {
// Does any error start or continue on to this line? Emit squiggles
if ((err.end >= thisLineStart) && ((err.start < nextLineStart) || (lineIndex === lines.length - 1))) {
// How many characters from the start of this line the error starts at (could be positive or negative)
var relativeOffset = err.start - thisLineStart;
// How many characters of the error are on this line (might be longer than this line in reality)
var length = (err.end - err.start) - Math.max(0, thisLineStart - err.start);
// Calculate the start of the squiggle
var squiggleStart = Math.max(0, relativeOffset);
// TODO/REVIEW: this doesn't work quite right in the browser if a multi file test has files whose names are just the right length relative to one another
outputLines.push(' ' + line.substr(0, squiggleStart).replace(/[^\s]/g, ' ') + new Array(Math.min(length, line.length - squiggleStart) + 1).join('~'));
// If the error ended here, or we're at the end of the file, emit its message
if ((lineIndex === lines.length - 1) || nextLineStart > err.end) {
// Just like above, we need to do a split on a string instead of on a regex
// because the JS engine does regexes wrong
outputErrorText(err);
markedErrorCount++;
}
}