forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypescript.ts
More file actions
1524 lines (1257 loc) · 65.5 KB
/
Copy pathtypescript.ts
File metadata and controls
1524 lines (1257 loc) · 65.5 KB
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='references.ts' />
if (Error) (<any>Error).stackTraceLimit = 1000;
module TypeScript {
export var fileResolutionTime = 0;
export var fileResolutionIOTime = 0;
export var fileResolutionScanImportsTime = 0;
export var fileResolutionImportFileSearchTime = 0;
export var fileResolutionGetDefaultLibraryTime = 0;
export var sourceCharactersCompiled = 0;
export var syntaxTreeParseTime = 0;
export var typeCheckTime = 0;
export var createDeclarationsTime = 0;
export var compilerResolvePathTime = 0;
export var compilerDirectoryNameTime = 0;
export var compilerDirectoryExistsTime = 0;
export var compilerFileExistsTime = 0;
export var emitTime = 0;
export var emitWriteFileTime = 0;
export var declarationEmitTime = 0;
export var declarationEmitIsExternallyVisibleTime = 0;
export var declarationEmitTypeSignatureTime = 0;
export var declarationEmitGetBoundDeclTypeTime = 0;
export var declarationEmitIsOverloadedCallSignatureTime = 0;
export var declarationEmitFunctionDeclarationGetSymbolTime = 0;
export var declarationEmitGetBaseTypeTime = 0;
export var declarationEmitGetAccessorFunctionTime = 0;
export var declarationEmitGetTypeParameterSymbolTime = 0;
export var declarationEmitGetImportDeclarationSymbolTime = 0;
export var ioHostResolvePathTime = 0;
export var ioHostDirectoryNameTime = 0;
export var ioHostCreateDirectoryStructureTime = 0;
export var ioHostWriteFileTime = 0;
export interface PullSymbolInfo {
symbol: PullSymbol;
aliasSymbol: PullTypeAliasSymbol;
ast: ISyntaxElement;
enclosingScopeSymbol: PullSymbol;
}
export interface PullCallSymbolInfo {
targetSymbol: PullSymbol;
resolvedSignatures: TypeScript.PullSignatureSymbol[];
candidateSignature: TypeScript.PullSignatureSymbol;
isConstructorCall: boolean;
ast: ISyntaxElement;
enclosingScopeSymbol: PullSymbol;
}
export interface PullVisibleSymbolsInfo {
symbols: PullSymbol[];
enclosingScopeSymbol: PullSymbol;
}
export enum EmitOutputResult {
Succeeded,
FailedBecauseOfSyntaxErrors,
FailedBecauseOfCompilerOptionsErrors,
FailedToGenerateDeclarationsBecauseOfSemanticErrors
}
export class EmitOutput {
public outputFiles: OutputFile[] = [];
public emitOutputResult: EmitOutputResult;
constructor(emitOutputResult = EmitOutputResult.Succeeded) {
this.emitOutputResult = emitOutputResult;
}
}
export enum OutputFileType {
JavaScript,
SourceMap,
Declaration
}
export class OutputFile {
constructor(public name: string,
public writeByteOrderMark: boolean,
public text: string,
public fileType: OutputFileType,
public sourceMapEntries: SourceMapEntry[] = []) {
}
}
// Represents the results of the last "pull" on the compiler when using the streaming
// 'compile' method. The compile result for a single pull can have diagnostics (if
// something went wrong), and/or OutputFiles that need to get written.
export class CompileResult {
public diagnostics: Diagnostic[] = [];
public outputFiles: OutputFile[] = [];
public static fromDiagnostics(diagnostics: Diagnostic[]): CompileResult {
var result = new CompileResult();
result.diagnostics = diagnostics;
return result;
}
public static fromOutputFiles(outputFiles: OutputFile[]): CompileResult {
var result = new CompileResult();
result.outputFiles = outputFiles;
return result;
}
}
export interface ICancellationToken {
isCancellationRequested(): boolean;
}
export class OperationCanceledException { }
export class CancellationToken {
public static None: CancellationToken = new CancellationToken(null);
constructor(private cancellationToken: ICancellationToken) {
}
public isCancellationRequested() {
return this.cancellationToken && this.cancellationToken.isCancellationRequested();
}
public throwIfCancellationRequested(): void {
if (this.isCancellationRequested()) {
throw new OperationCanceledException();
}
}
}
class DocumentRegistryEntry {
public refCount: number = 0;
public owners: string[] = [];
constructor(public document: Document) {
}
}
export interface IDocumentRegistry {
acquireDocument(
fileName: string,
compilationSettings: ImmutableCompilationSettings,
scriptSnapshot: IScriptSnapshot,
byteOrderMark: ByteOrderMark,
version: number,
isOpen: boolean,
referencedFiles: string[]): TypeScript.Document;
updateDocument(
document: Document,
fileName: string,
compilationSettings: ImmutableCompilationSettings,
scriptSnapshot: IScriptSnapshot,
version: number,
isOpen: boolean,
textChangeRange: TextChangeRange
): TypeScript.Document;
releaseDocument(fileName: string, compilationSettings: ImmutableCompilationSettings): void
}
export class NonCachingDocumentRegistry implements IDocumentRegistry {
public static Instance: IDocumentRegistry = new NonCachingDocumentRegistry();
public acquireDocument(
fileName: string,
compilationSettings: ImmutableCompilationSettings,
scriptSnapshot: IScriptSnapshot,
byteOrderMark: ByteOrderMark,
version: number,
isOpen: boolean,
referencedFiles: string[]= []): TypeScript.Document {
return Document.create(compilationSettings, fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles);
}
public updateDocument(
document: Document,
fileName: string,
compilationSettings: ImmutableCompilationSettings,
scriptSnapshot: IScriptSnapshot,
version: number,
isOpen: boolean,
textChangeRange: TextChangeRange
): TypeScript.Document {
return document.update(scriptSnapshot, version, isOpen, textChangeRange);
}
public releaseDocument(fileName: string, compilationSettings: ImmutableCompilationSettings): void {
// no op since this class doesn't cache anything
}
}
export class DocumentRegistry implements IDocumentRegistry {
private buckets: IIndexable<StringHashTable<DocumentRegistryEntry>> = {};
private getKeyFromCompilationSettings(settings: ImmutableCompilationSettings): string {
return "_" + settings.propagateEnumConstants().toString() + "|" + settings.allowAutomaticSemicolonInsertion().toString() + "|" + LanguageVersion[settings.codeGenTarget()];
}
private getBucketForCompilationSettings(settings: ImmutableCompilationSettings, createIfMissing: boolean): StringHashTable<DocumentRegistryEntry> {
var key = this.getKeyFromCompilationSettings(settings);
var bucket = this.buckets[key];
if (!bucket && createIfMissing) {
this.buckets[key] = bucket = new StringHashTable<DocumentRegistryEntry>();
}
return bucket;
}
public reportStats() {
var bucketInfoArray = Object.keys(this.buckets).filter(name => name && name.charAt(0) === '_').map(name => {
var entries = this.buckets[name];
var documents = entries.getAllKeys().map((name) => {
var entry = entries.lookup(name);
return {
name: name,
refCount: entry.refCount,
references: entry.owners.slice(0)
};
});
documents.sort((x, y) => y.refCount - x.refCount);
return { bucket: name, documents: documents };
});
return JSON.stringify(bucketInfoArray, null, 2);
}
public acquireDocument(
fileName: string,
compilationSettings: ImmutableCompilationSettings,
scriptSnapshot: IScriptSnapshot,
byteOrderMark: ByteOrderMark,
version: number,
isOpen: boolean,
referencedFiles: string[]= []): TypeScript.Document {
var bucket = this.getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true);
var entry = bucket.lookup(fileName);
if (!entry) {
var document = Document.create(compilationSettings, fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles);
entry = new DocumentRegistryEntry(document);
bucket.add(fileName, entry);
}
entry.refCount++;
return entry.document;
}
public updateDocument(
document: Document,
fileName: string,
compilationSettings: ImmutableCompilationSettings,
scriptSnapshot: IScriptSnapshot,
version: number,
isOpen: boolean,
textChangeRange: TextChangeRange
): TypeScript.Document {
var bucket = this.getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ false);
Debug.assert(bucket);
var entry = bucket.lookup(fileName);
Debug.assert(entry);
if (entry.document.isOpen === isOpen && entry.document.version === version) {
return entry.document;
}
entry.document = entry.document.update(scriptSnapshot, version, isOpen, textChangeRange);
return entry.document;
}
public releaseDocument(fileName: string, compilationSettings: ImmutableCompilationSettings): void {
var bucket = this.getBucketForCompilationSettings(compilationSettings, false);
Debug.assert(bucket);
var entry = bucket.lookup(fileName);
entry.refCount--;
Debug.assert(entry.refCount >= 0);
if (entry.refCount === 0) {
bucket.remove(fileName);
}
}
}
interface IExpressionWithArgumentListSyntax extends IExpressionSyntax {
expression: IExpressionSyntax;
argumentList: ArgumentListSyntax;
}
export class TypeScriptCompiler {
private semanticInfoChain: SemanticInfoChain = null;
constructor(public logger: ILogger = new NullLogger(),
private _settings: ImmutableCompilationSettings = ImmutableCompilationSettings.defaultSettings()) {
this.semanticInfoChain = new SemanticInfoChain(this, logger);
}
public getSemanticInfoChain() {
return this.semanticInfoChain;
}
public compilationSettings(): ImmutableCompilationSettings {
return this._settings;
}
public setCompilationSettings(newSettings: ImmutableCompilationSettings) {
var oldSettings = this._settings;
this._settings = newSettings;
if (!compareDataObjects(oldSettings, newSettings)) {
// If our options have changed at all, we have to consider any cached semantic
// data we have invalid.
this.semanticInfoChain.invalidate(oldSettings, newSettings);
}
}
public getDocument(fileName: string): Document {
fileName = TypeScript.switchToForwardSlashes(fileName);
return this.semanticInfoChain.getDocument(fileName);
}
public cleanupSemanticCache(): void {
this.semanticInfoChain.invalidate();
}
public addOrUpdateFile(document: Document): void {
// TODO: TypeScript.sourceCharactersCompiled += document. scriptSnapshot.getLength();
// Note: the semantic info chain will recognize that this is a replacement of an
// existing script, and will handle it appropriately.
this.semanticInfoChain.addDocument(document);
}
public addFile(
fileName: string,
scriptSnapshot: IScriptSnapshot,
byteOrderMark: ByteOrderMark,
version: number,
isOpen: boolean,
referencedFiles: string[]= []): void {
fileName = TypeScript.switchToForwardSlashes(fileName);
var document = Document.create(this.compilationSettings(), fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles);
this.addOrUpdateFile(document);
}
public updateFile(fileName: string, scriptSnapshot: IScriptSnapshot, version: number, isOpen: boolean, textChangeRange: TextChangeRange): void {
fileName = TypeScript.switchToForwardSlashes(fileName);
var document = this.getDocument(fileName);
var updatedDocument = document.update(scriptSnapshot, version, isOpen, textChangeRange);
// Note: the semantic info chain will recognize that this is a replacement of an
// existing script, and will handle it appropriately.
this.addOrUpdateFile(updatedDocument);
}
public removeFile(fileName: string): void {
fileName = TypeScript.switchToForwardSlashes(fileName);
this.semanticInfoChain.removeDocument(fileName);
}
public mapOutputFileName(document: Document, emitOptions: EmitOptions, extensionChanger: (fname: string, wholeFileNameReplaced: boolean) => string) {
if (document.emitToOwnOutputFile()) {
var updatedFileName = document.fileName;
if (emitOptions.outputDirectory() !== "") {
// Replace the common directory path with the option specified
updatedFileName = document.fileName.replace(emitOptions.commonDirectoryPath(), "");
updatedFileName = emitOptions.outputDirectory() + updatedFileName;
}
return extensionChanger(updatedFileName, false);
}
else {
return extensionChanger(emitOptions.sharedOutputFile(), true);
}
}
private writeByteOrderMarkForDocument(document: Document) {
// Set this to 'true' if you want to know why the compiler emitted a document with a
// byte order mark.
var printReason = false;
// If module its always emitted in its own file
if (document.emitToOwnOutputFile()) {
var result = document.byteOrderMark !== ByteOrderMark.None;
if (printReason) {
Environment.standardOut.WriteLine("Emitting byte order mark because of: " + document.fileName);
}
return result;
}
else {
var fileNames = this.fileNames();
var result = false;
for (var i = 0, n = fileNames.length; i < n; i++) {
var document = this.getDocument(fileNames[i]);
if (document.syntaxTree().isExternalModule()) {
// Dynamic module never contributes to the single file
continue;
}
if (document.byteOrderMark !== ByteOrderMark.None) {
if (printReason) {
Environment.standardOut.WriteLine("Emitting byte order mark because of: " + document.fileName);
result = true;
}
else {
return true;
}
}
}
return result;
}
}
static mapToDTSFileName(fileName: string, wholeFileNameReplaced: boolean) {
return getDeclareFilePath(fileName);
}
public _shouldEmit(document: Document) {
// If its already a declare file or is resident or does not contain body
return !document.isDeclareFile();
}
public _shouldEmitDeclarations(document: Document) {
if (!this.compilationSettings().generateDeclarationFiles()) {
return false;
}
return this._shouldEmit(document);
}
// Does the actual work of emittin the declarations from the provided document into the
// provided emitter. If no emitter is provided a new one is created.
private emitDocumentDeclarationsWorker(
document: Document,
emitOptions: EmitOptions,
declarationEmitter?: DeclarationEmitter): DeclarationEmitter {
var sourceUnit = document.sourceUnit();
Debug.assert(this._shouldEmitDeclarations(document));
if (declarationEmitter) {
declarationEmitter.document = document;
}
else {
var declareFileName = this.mapOutputFileName(document, emitOptions, TypeScriptCompiler.mapToDTSFileName);
declarationEmitter = new DeclarationEmitter(declareFileName, document, this, emitOptions, this.semanticInfoChain);
}
declarationEmitter.emitDeclarations(sourceUnit);
return declarationEmitter;
}
public _emitDocumentDeclarations(
document: Document,
emitOptions: EmitOptions,
onSingleFileEmitComplete: (files: OutputFile) => void,
sharedEmitter: DeclarationEmitter): DeclarationEmitter {
var start = new Date().getTime();
if (this._shouldEmitDeclarations(document)) {
if (document.emitToOwnOutputFile()) {
var singleEmitter = this.emitDocumentDeclarationsWorker(document, emitOptions);
if (singleEmitter) {
onSingleFileEmitComplete(singleEmitter.getOutputFile());
}
}
else {
// Create or reuse file
sharedEmitter = this.emitDocumentDeclarationsWorker(document, emitOptions, sharedEmitter);
}
}
declarationEmitTime += new Date().getTime() - start;
return sharedEmitter;
}
// Will not throw exceptions.
public emitAllDeclarations(resolvePath: (path: string) => string): EmitOutput {
var emitOutput = new EmitOutput();
var emitOptions = new EmitOptions(this, resolvePath);
if (emitOptions.diagnostic()) {
emitOutput.emitOutputResult = EmitOutputResult.FailedBecauseOfCompilerOptionsErrors;
return emitOutput;
}
var sharedEmitter: DeclarationEmitter = null;
var fileNames = this.fileNames();
for (var i = 0, n = fileNames.length; i < n; i++) {
var fileName = fileNames[i];
var document = this.getDocument(fileName);
sharedEmitter = this._emitDocumentDeclarations(document, emitOptions,
file => emitOutput.outputFiles.push(file), sharedEmitter);
}
if (sharedEmitter) {
emitOutput.outputFiles.push(sharedEmitter.getOutputFile());
}
return emitOutput;
}
// Will not throw exceptions.
public emitDeclarations(fileName: string, resolvePath: (path: string) => string): EmitOutput {
fileName = TypeScript.switchToForwardSlashes(fileName);
var emitOutput = new EmitOutput();
var emitOptions = new EmitOptions(this, resolvePath);
if (emitOptions.diagnostic()) {
emitOutput.emitOutputResult = EmitOutputResult.FailedBecauseOfCompilerOptionsErrors;
return emitOutput;
}
var document = this.getDocument(fileName);
// Emitting module or multiple files, always goes to single file
if (document.emitToOwnOutputFile()) {
this._emitDocumentDeclarations(document, emitOptions,
file => emitOutput.outputFiles.push(file), /*sharedEmitter:*/ null);
return emitOutput;
}
else {
return this.emitAllDeclarations(resolvePath);
}
}
public canEmitDeclarations(fileName: string) {
fileName = TypeScript.switchToForwardSlashes(fileName);
var document = this.getDocument(fileName);
return this._shouldEmitDeclarations(document);
}
static mapToFileNameExtension(extension: string, fileName: string, wholeFileNameReplaced: boolean) {
if (wholeFileNameReplaced) {
// The complete output is redirected in this file so do not change extension
return fileName;
}
else {
// Change the extension of the file
var splitFname = fileName.split(".");
splitFname.pop();
return splitFname.join(".") + extension;
}
}
static mapToJSFileName(fileName: string, wholeFileNameReplaced: boolean) {
return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced);
}
// Caller is responsible for closing the returned emitter.
// May throw exceptions.
private emitDocumentWorker(document: Document, emitOptions: EmitOptions, emitter?: Emitter): Emitter {
var sourceUnit = document.sourceUnit();
Debug.assert(this._shouldEmit(document));
if (!emitter) {
var javaScriptFileName = this.mapOutputFileName(document, emitOptions, TypeScriptCompiler.mapToJSFileName);
var outFile = new TextWriter(javaScriptFileName, this.writeByteOrderMarkForDocument(document), OutputFileType.JavaScript);
emitter = new Emitter(javaScriptFileName, outFile, emitOptions, this.semanticInfoChain);
if (this.compilationSettings().mapSourceFiles()) {
// We always create map files next to the jsFiles
var sourceMapFile = new TextWriter(javaScriptFileName + SourceMapper.MapFileExtension, /*writeByteOrderMark:*/ false, OutputFileType.SourceMap);
emitter.createSourceMapper(document, javaScriptFileName, outFile, sourceMapFile, emitOptions.resolvePath);
}
}
else if (this.compilationSettings().mapSourceFiles()) {
// Already emitting into js file, update the mapper for new source info
emitter.setSourceMapperNewSourceFile(document);
}
// Set location info
emitter.setDocument(document);
emitter.emitJavascript(sourceUnit, /*startLine:*/false);
return emitter;
}
// Private. only for use by compiler or CompilerIterator
public _emitDocument(
document: Document,
emitOptions: EmitOptions,
onSingleFileEmitComplete: (files: OutputFile[]) => void,
sharedEmitter: Emitter): Emitter {
var start = new Date().getTime();
// Emitting module or multiple files, always goes to single file
if (this._shouldEmit(document)) {
if (document.emitToOwnOutputFile()) {
// We're outputting to mulitple files. We don't want to reuse an emitter in that case.
var singleEmitter = this.emitDocumentWorker(document, emitOptions);
if (singleEmitter) {
onSingleFileEmitComplete(singleEmitter.getOutputFiles());
}
}
else {
// We're not outputting to multiple files. Keep using the same emitter and don't
// close until below.
sharedEmitter = this.emitDocumentWorker(document, emitOptions, sharedEmitter);
}
}
emitTime += new Date().getTime() - start;
return sharedEmitter;
}
// Will not throw exceptions.
public emitAll(resolvePath: (path: string) => string): EmitOutput {
var emitOutput = new EmitOutput();
var emitOptions = new EmitOptions(this, resolvePath);
if (emitOptions.diagnostic()) {
emitOutput.emitOutputResult = EmitOutputResult.FailedBecauseOfCompilerOptionsErrors;
return emitOutput;
}
var fileNames = this.fileNames();
var sharedEmitter: Emitter = null;
// Iterate through the files, as long as we don't get an error.
for (var i = 0, n = fileNames.length; i < n; i++) {
var fileName = fileNames[i];
var document = this.getDocument(fileName);
sharedEmitter = this._emitDocument(document, emitOptions,
files => emitOutput.outputFiles.push.apply(emitOutput.outputFiles, files),
sharedEmitter);
}
if (sharedEmitter) {
emitOutput.outputFiles.push.apply(emitOutput.outputFiles, sharedEmitter.getOutputFiles());
}
return emitOutput;
}
// Emit single file if outputMany is specified, else emit all
// Will not throw exceptions.
public emit(fileName: string, resolvePath: (path: string) => string): EmitOutput {
fileName = TypeScript.switchToForwardSlashes(fileName);
var emitOutput = new EmitOutput();
var emitOptions = new EmitOptions(this, resolvePath);
if (emitOptions.diagnostic()) {
emitOutput.emitOutputResult = EmitOutputResult.FailedBecauseOfCompilerOptionsErrors;
return emitOutput;
}
var document = this.getDocument(fileName);
// Emitting module or multiple files, always goes to single file
if (document.emitToOwnOutputFile()) {
this._emitDocument(document, emitOptions,
files => emitOutput.outputFiles.push.apply(emitOutput.outputFiles, files), /*sharedEmitter:*/ null);
return emitOutput;
}
else {
// In output Single file mode, emit everything
return this.emitAll(resolvePath);
}
}
// Returns an iterator that will stream compilation results from this compiler. Syntactic
// diagnostics will be returned first, then semantic diagnostics, then emit results, then
// declaration emit results.
//
// The continueOnDiagnostics flag governs whether or not iteration follows the batch compiler
// logic and doesn't perform further analysis once diagnostics are produced. For example,
// in batch compilation nothing is done if there are any syntactic diagnostics. Clients
// can override this if they still want to procede in those cases.
public compile(resolvePath: (path: string) => string, continueOnDiagnostics = false): Iterator<CompileResult> {
return new CompilerIterator(this, resolvePath, continueOnDiagnostics);
}
//
// Pull typecheck infrastructure
//
public getSyntacticDiagnostics(fileName: string): Diagnostic[] {
fileName = TypeScript.switchToForwardSlashes(fileName);
return this.getDocument(fileName).diagnostics();
}
/** Used for diagnostics in tests */
private getSyntaxTree(fileName: string): SyntaxTree {
return this.getDocument(fileName).syntaxTree();
}
private getSourceUnit(fileName: string): SourceUnitSyntax {
return this.getDocument(fileName).sourceUnit();
}
public getSemanticDiagnostics(fileName: string): Diagnostic[] {
fileName = TypeScript.switchToForwardSlashes(fileName);
var document = this.getDocument(fileName);
var startTime = (new Date()).getTime();
PullTypeResolver.typeCheck(this.compilationSettings(), this.semanticInfoChain, document);
var endTime = (new Date()).getTime();
typeCheckTime += endTime - startTime;
var errors = this.semanticInfoChain.getDiagnostics(fileName);
errors = ArrayUtilities.distinct(errors, Diagnostic.equals);
errors.sort((d1, d2) => {
if (d1.fileName() < d2.fileName()) {
return -1;
}
else if (d1.fileName() > d2.fileName()) {
return 1;
}
if (d1.start() < d2.start()) {
return -1;
}
else if (d1.start() > d2.start()) {
return 1;
}
// For multiple errors reported on the same file at the same position.
var code1 = diagnosticInformationMap[d1.diagnosticKey()].code;
var code2 = diagnosticInformationMap[d2.diagnosticKey()].code;
if (code1 < code2) {
return -1;
}
else if (code1 > code2) {
return 1;
}
return 0;
});
return errors;
}
public getCompilerOptionsDiagnostics(resolvePath: (path: string) => string): Diagnostic[] {
var emitOptions = new EmitOptions(this, resolvePath);
var emitDiagnostic = emitOptions.diagnostic();
if (emitDiagnostic) {
return [emitDiagnostic];
}
return sentinelEmptyArray;
}
public resolveAllFiles() {
var fileNames = this.fileNames();
for (var i = 0, n = fileNames.length; i < n; i++) {
this.getSemanticDiagnostics(fileNames[i]);
}
}
public getSymbolOfDeclaration(decl: PullDecl): PullSymbol {
if (!decl) {
return null;
}
var resolver = this.semanticInfoChain.getResolver();
var ast = this.semanticInfoChain.getASTForDecl(decl);
if (!ast) {
return null;
}
var enclosingDecl = resolver.getEnclosingDecl(decl);
if (ast.kind() === SyntaxKind.GetAccessor || ast.kind() === SyntaxKind.SetAccessor) {
return this.getSymbolOfDeclaration(enclosingDecl);
}
return resolver.resolveAST(ast, /*inContextuallyTypedAssignment:*/false, new PullTypeResolutionContext(resolver));
}
private extractResolutionContextFromAST(resolver: PullTypeResolver, ast: ISyntaxElement, document: Document, propagateContextualTypes: boolean): { ast: ISyntaxElement; enclosingDecl: PullDecl; resolutionContext: PullTypeResolutionContext; inContextuallyTypedAssignment: boolean; inWithBlock: boolean; } {
var enclosingDecl: PullDecl = null;
var enclosingDeclAST: ISyntaxElement = null;
var inContextuallyTypedAssignment = false;
var inWithBlock = false;
var resolutionContext = new PullTypeResolutionContext(resolver);
if (!ast) {
return null;
}
var path = this.getASTPath(ast);
// Extract infromation from path
for (var i = 0 , n = path.length; i < n; i++) {
var current = path[i];
switch (current.kind()) {
case SyntaxKind.FunctionExpression:
case SyntaxKind.SimpleArrowFunctionExpression:
case SyntaxKind.ParenthesizedArrowFunctionExpression:
if (propagateContextualTypes) {
resolver.resolveAST(current, /*inContextuallyTypedAssignment*/ true, resolutionContext);
}
break;
//case SyntaxKind.Parameter:
// var parameter = <ParameterSyntax> current;
// inContextuallyTypedAssignment = parameter.typeExpr !== null;
// this.extractResolutionContextForVariable(inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, parameter, parameter.init);
// break;
case SyntaxKind.MemberVariableDeclaration:
var memberVariable = <MemberVariableDeclarationSyntax> current;
inContextuallyTypedAssignment = memberVariable.variableDeclarator.typeAnnotation !== null;
this.extractResolutionContextForVariable(inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, memberVariable, memberVariable.variableDeclarator.equalsValueClause);
break;
case SyntaxKind.VariableDeclarator:
var variableDeclarator = <VariableDeclaratorSyntax>current;
inContextuallyTypedAssignment = variableDeclarator.typeAnnotation !== null;
this.extractResolutionContextForVariable(inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, variableDeclarator, variableDeclarator.equalsValueClause);
break;
case SyntaxKind.InvocationExpression:
case SyntaxKind.ObjectCreationExpression:
if (propagateContextualTypes) {
var isNew = current.kind() === SyntaxKind.ObjectCreationExpression;
var callExpression = <IExpressionWithArgumentListSyntax>current;
var contextualType: PullTypeSymbol = null;
// Check if we are in an argumnt for a call, propagate the contextual typing
if ((i + 2 < n) && callExpression.argumentList === path[i + 1] && callExpression.argumentList.arguments === path[i + 2]) {
var callResolutionResults = new PullAdditionalCallResolutionData();
if (isNew) {
resolver.resolveObjectCreationExpression(<ObjectCreationExpressionSyntax>callExpression, resolutionContext, callResolutionResults);
}
else {
resolver.resolveInvocationExpression(<InvocationExpressionSyntax>callExpression, resolutionContext, callResolutionResults);
}
// Find the index in the arguments list
if (callResolutionResults.actualParametersContextTypeSymbols) {
var argExpression = path[i + 3];
if (argExpression) {
for (var j = 0, m = callExpression.argumentList.arguments.length; j < m; j++) {
if (callExpression.argumentList.arguments[j] === argExpression) {
var callContextualType = callResolutionResults.actualParametersContextTypeSymbols[j];
if (callContextualType) {
contextualType = callContextualType;
break;
}
}
}
}
}
}
else {
// Just resolve the call expression
if (isNew) {
resolver.resolveObjectCreationExpression(<ObjectCreationExpressionSyntax>callExpression, resolutionContext);
}
else {
resolver.resolveInvocationExpression(<InvocationExpressionSyntax>callExpression, resolutionContext);
}
}
resolutionContext.pushNewContextualType(contextualType);
}
break;
case SyntaxKind.ArrayLiteralExpression:
if (propagateContextualTypes) {
// Propagate the child element type
var contextualType: PullTypeSymbol = null;
var currentContextualType = resolutionContext.getContextualType();
if (currentContextualType && currentContextualType.isArrayNamedTypeReference()) {
contextualType = currentContextualType.getElementType();
}
resolutionContext.pushNewContextualType(contextualType);
}
break;
case SyntaxKind.ObjectLiteralExpression:
if (propagateContextualTypes) {
var objectLiteralExpression = <ObjectLiteralExpressionSyntax>current;
var objectLiteralResolutionContext = new PullAdditionalObjectLiteralResolutionData();
resolver.resolveObjectLiteralExpression(objectLiteralExpression, inContextuallyTypedAssignment, resolutionContext, objectLiteralResolutionContext);
// find the member in the path
var memeberAST = (path[i + 1] && path[i + 1].kind() === SyntaxKind.SeparatedList) ? path[i + 2] : path[i + 1];
if (memeberAST) {
// Propagate the member contextual type
var contextualType: PullTypeSymbol = null;
var memberDecls = objectLiteralExpression.propertyAssignments;
if (memberDecls && objectLiteralResolutionContext.membersContextTypeSymbols) {
for (var j = 0, m = memberDecls.length; j < m; j++) {
if (memberDecls[j] === memeberAST) {
var memberContextualType = objectLiteralResolutionContext.membersContextTypeSymbols[j];
if (memberContextualType) {
contextualType = memberContextualType;
break;
}
}
}
}
resolutionContext.pushNewContextualType(contextualType);
}
}
break;
case SyntaxKind.AssignmentExpression:
if (propagateContextualTypes) {
var assignmentExpression = <BinaryExpressionSyntax>current;
var contextualType: PullTypeSymbol = null;
if (path[i + 1] && path[i + 1] === assignmentExpression.right) {
// propagate the left hand side type as a contextual type
var leftType = resolver.resolveAST(assignmentExpression.left, inContextuallyTypedAssignment, resolutionContext).type;
if (leftType) {
inContextuallyTypedAssignment = true;
contextualType = leftType;
}
}
resolutionContext.pushNewContextualType(contextualType);
}
break;
case SyntaxKind.CastExpression:
var castExpression = <CastExpressionSyntax>current;
if (!(i + 1 < n && path[i + 1] === castExpression.type)) {
// We are outside the cast term
if (propagateContextualTypes) {
var contextualType: PullTypeSymbol = null;
var typeSymbol = resolver.resolveAST(castExpression, inContextuallyTypedAssignment, resolutionContext).type;
// Set the context type
if (typeSymbol) {
inContextuallyTypedAssignment = true;
contextualType = typeSymbol;
}
resolutionContext.pushNewContextualType(contextualType);
}
}
break;
case SyntaxKind.ReturnStatement:
if (propagateContextualTypes) {
var contextualType: PullTypeSymbol = null;
if (enclosingDecl && (enclosingDecl.kind & PullElementKind.SomeFunction)) {
var typeAnnotation = ASTHelpers.getType(enclosingDeclAST);
if (typeAnnotation) {
// The containing function has a type annotation, propagate it as the contextual type
var returnTypeSymbol = resolver.resolveTypeReference(typeAnnotation, resolutionContext);
if (returnTypeSymbol) {
inContextuallyTypedAssignment = true;
contextualType = returnTypeSymbol;
}
}
else {
// No type annotation, check if there is a contextual type enforced on the function, and propagate that
var currentContextualType = resolutionContext.getContextualType();
if (currentContextualType && currentContextualType.isFunction()) {
var contextualSignatures = currentContextualType.kind == PullElementKind.ConstructorType
? currentContextualType.getConstructSignatures()
: currentContextualType.getCallSignatures();
var currentContextualTypeSignatureSymbol = contextualSignatures[0];