/
evaluator_spec.ts
994 lines (865 loc) Β· 36.5 KB
/
evaluator_spec.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {absoluteFrom, getSourceFileOrError} from '../../file_system';
import {runInEachFileSystem} from '../../file_system/testing';
import {Reference} from '../../imports';
import {DependencyTracker} from '../../incremental/api';
import {Declaration, KnownDeclaration, SpecialDeclarationKind, TypeScriptReflectionHost} from '../../reflection';
import {getDeclaration, makeProgram} from '../../testing';
import {DynamicValue} from '../src/dynamic';
import {PartialEvaluator} from '../src/interface';
import {EnumValue, ResolvedValue} from '../src/result';
import {evaluate, firstArgFfr, makeEvaluator, makeExpression, owningModuleOf} from './utils';
runInEachFileSystem(() => {
describe('ngtsc metadata', () => {
let _: typeof absoluteFrom;
beforeEach(() => _ = absoluteFrom);
it('reads a file correctly', () => {
const value = evaluate(
`
import {Y} from './other';
const A = Y;
`,
'A', [
{
name: _('/other.ts'),
contents: `
export const Y = 'test';
`
},
]);
expect(value).toEqual('test');
});
it('map access works', () => {
expect(evaluate('const obj = {a: "test"};', 'obj.a')).toEqual('test');
});
it('resolves undefined property access', () => {
expect(evaluate('const obj: any = {}', 'obj.bar')).toEqual(undefined);
});
it('function calls work', () => {
expect(evaluate(`function foo(bar) { return bar; }`, 'foo("test")')).toEqual('test');
});
it('function call default value works', () => {
expect(evaluate(`function foo(bar = 1) { return bar; }`, 'foo()')).toEqual(1);
expect(evaluate(`function foo(bar = 1) { return bar; }`, 'foo(2)')).toEqual(2);
expect(evaluate(`function foo(a, c = a) { return c; }; const a = 1;`, 'foo(2)')).toEqual(2);
});
it('function call spread works', () => {
expect(evaluate(`function foo(a, ...b) { return [a, b]; }`, 'foo(1, ...[2, 3])')).toEqual([
1, [2, 3]
]);
});
it('conditionals work', () => {
expect(evaluate(`const x = false; const y = x ? 'true' : 'false';`, 'y')).toEqual('false');
});
it('addition works', () => {
expect(evaluate(`const x = 1 + 2;`, 'x')).toEqual(3);
});
it('static property on class works', () => {
expect(evaluate(`class Foo { static bar = 'test'; }`, 'Foo.bar')).toEqual('test');
});
it('static property call works', () => {
expect(evaluate(`class Foo { static bar(test) { return test; } }`, 'Foo.bar("test")'))
.toEqual('test');
});
it('indirected static property call works', () => {
expect(
evaluate(
`class Foo { static bar(test) { return test; } }; const fn = Foo.bar;`, 'fn("test")'))
.toEqual('test');
});
it('array works', () => {
expect(evaluate(`const x = 'test'; const y = [1, x, 2];`, 'y')).toEqual([1, 'test', 2]);
});
it('array spread works', () => {
expect(evaluate(`const a = [1, 2]; const b = [4, 5]; const c = [...a, 3, ...b];`, 'c'))
.toEqual([1, 2, 3, 4, 5]);
});
it('&& operations work', () => {
expect(evaluate(`const a = 'hello', b = 'world';`, 'a && b')).toEqual('world');
expect(evaluate(`const a = false, b = 'world';`, 'a && b')).toEqual(false);
expect(evaluate(`const a = 'hello', b = 0;`, 'a && b')).toEqual(0);
});
it('|| operations work', () => {
expect(evaluate(`const a = 'hello', b = 'world';`, 'a || b')).toEqual('hello');
expect(evaluate(`const a = false, b = 'world';`, 'a || b')).toEqual('world');
expect(evaluate(`const a = 'hello', b = 0;`, 'a || b')).toEqual('hello');
});
it('evaluates arithmetic operators', () => {
expect(evaluate('const a = 6, b = 3;', 'a + b')).toEqual(9);
expect(evaluate('const a = 6, b = 3;', 'a - b')).toEqual(3);
expect(evaluate('const a = 6, b = 3;', 'a * b')).toEqual(18);
expect(evaluate('const a = 6, b = 3;', 'a / b')).toEqual(2);
expect(evaluate('const a = 6, b = 3;', 'a % b')).toEqual(0);
expect(evaluate('const a = 6, b = 3;', 'a & b')).toEqual(2);
expect(evaluate('const a = 6, b = 3;', 'a | b')).toEqual(7);
expect(evaluate('const a = 6, b = 3;', 'a ^ b')).toEqual(5);
expect(evaluate('const a = 6, b = 3;', 'a ** b')).toEqual(216);
expect(evaluate('const a = 6, b = 3;', 'a << b')).toEqual(48);
expect(evaluate('const a = -6, b = 2;', 'a >> b')).toEqual(-2);
expect(evaluate('const a = -6, b = 2;', 'a >>> b')).toEqual(1073741822);
});
it('evaluates comparison operators', () => {
expect(evaluate('const a = 2, b = 3;', 'a < b')).toEqual(true);
expect(evaluate('const a = 3, b = 3;', 'a < b')).toEqual(false);
expect(evaluate('const a = 3, b = 3;', 'a <= b')).toEqual(true);
expect(evaluate('const a = 4, b = 3;', 'a <= b')).toEqual(false);
expect(evaluate('const a = 4, b = 3;', 'a > b')).toEqual(true);
expect(evaluate('const a = 3, b = 3;', 'a > b')).toEqual(false);
expect(evaluate('const a = 3, b = 3;', 'a >= b')).toEqual(true);
expect(evaluate('const a = 2, b = 3;', 'a >= b')).toEqual(false);
expect(evaluate('const a: any = 3, b = "3";', 'a == b')).toEqual(true);
expect(evaluate('const a: any = 2, b = "3";', 'a == b')).toEqual(false);
expect(evaluate('const a: any = 2, b = "3";', 'a != b')).toEqual(true);
expect(evaluate('const a: any = 3, b = "3";', 'a != b')).toEqual(false);
expect(evaluate('const a: any = 3, b = 3;', 'a === b')).toEqual(true);
expect(evaluate('const a: any = 3, b = "3";', 'a === b')).toEqual(false);
expect(evaluate('const a: any = 3, b = "3";', 'a !== b')).toEqual(true);
expect(evaluate('const a: any = 3, b = 3;', 'a !== b')).toEqual(false);
});
it('parentheticals work', () => {
expect(evaluate(`const a = 3, b = 4;`, 'a * (a + b)')).toEqual(21);
});
it('array access works', () => {
expect(evaluate(`const a = [1, 2, 3];`, 'a[1] + a[0]')).toEqual(3);
});
it('array access out of bounds is `undefined`', () => {
expect(evaluate(`const a = [1, 2, 3];`, 'a[-1]')).toEqual(undefined);
expect(evaluate(`const a = [1, 2, 3];`, 'a[3]')).toEqual(undefined);
});
it('array `length` property access works', () => {
expect(evaluate(`const a = [1, 2, 3];`, 'a[\'length\'] + 1')).toEqual(4);
});
it('array `slice` function works', () => {
expect(evaluate(`const a = [1, 2, 3];`, 'a[\'slice\']()')).toEqual([1, 2, 3]);
});
it('array `concat` function works', () => {
expect(evaluate(`const a = [1, 2], b = [3, 4];`, 'a[\'concat\'](b)')).toEqual([1, 2, 3, 4]);
expect(evaluate(`const a = [1, 2], b = 3;`, 'a[\'concat\'](b)')).toEqual([1, 2, 3]);
expect(evaluate(`const a = [1, 2], b = 3, c = [4, 5];`, 'a[\'concat\'](b, c)')).toEqual([
1, 2, 3, 4, 5
]);
expect(evaluate(`const a = [1, 2], b = [3, 4]`, 'a[\'concat\'](...b)')).toEqual([1, 2, 3, 4]);
});
it('negation works', () => {
expect(evaluate(`const x = 3;`, '!x')).toEqual(false);
expect(evaluate(`const x = 3;`, '!!x')).toEqual(true);
});
it('supports boolean literals', () => {
expect(evaluate('const a = true;', 'a')).toEqual(true);
expect(evaluate('const a = false;', 'a')).toEqual(false);
});
it('supports undefined', () => {
expect(evaluate('const a = undefined;', 'a')).toEqual(undefined);
});
it('supports null', () => {
expect(evaluate('const a = null;', 'a')).toEqual(null);
});
it('supports destructuring array variable declarations', () => {
const code = `
const [a, b, c, d] = [0, 1, 2, 3];
const e = c;
`;
expect(evaluate(code, 'a')).toBe(0);
expect(evaluate(code, 'b')).toBe(1);
expect(evaluate(code, 'c')).toBe(2);
expect(evaluate(code, 'd')).toBe(3);
expect(evaluate(code, 'e')).toBe(2);
});
it('supports destructuring object variable declaration', () => {
const code = `
const {a, b, c, d} = {a: 0, b: 1, c: 2, d: 3};
const e = c;
`;
expect(evaluate(code, 'a')).toBe(0);
expect(evaluate(code, 'b')).toBe(1);
expect(evaluate(code, 'c')).toBe(2);
expect(evaluate(code, 'd')).toBe(3);
expect(evaluate(code, 'e')).toBe(2);
});
it('supports destructuring object variable declaration with an alias', () => {
expect(evaluate(`const {a: value} = {a: 5}; const e = value;`, 'e')).toBe(5);
});
it('supports nested destructuring object variable declarations', () => {
expect(evaluate(`const {a: {b: {c}}} = {a: {b: {c: 0}}};`, 'c')).toBe(0);
});
it('supports nested destructuring array variable declarations', () => {
expect(evaluate(`const [[[a]]] = [[[1]]];`, 'a')).toBe(1);
});
it('supports nested destructuring variable declarations mixing arrays and objects', () => {
expect(evaluate(`const {a: {b: [[c]]}} = {a: {b: [[1337]]}};`, 'c')).toBe(1337);
});
it('resolves unknown values in a destructured variable declaration as dynamic values', () => {
const value = evaluate(
`const {a: {body}} = {a: window};`, 'body',
[{name: _('/window.ts'), contents: `declare const window: any;`}]);
if (!(value instanceof DynamicValue)) {
return fail(`Should have resolved to a DynamicValue`);
}
expect(value.node.getText()).toBe('body');
});
it('resolves unknown binary operators as dynamic value', () => {
const value = evaluate('declare const window: any;', '"location" in window');
if (!(value instanceof DynamicValue)) {
return fail(`Should have resolved to a DynamicValue`);
}
expect(value.node.getText()).toEqual('"location" in window');
expect(value.isFromUnsupportedSyntax()).toBe(true);
});
it('resolves unknown unary operators as dynamic value', () => {
const value = evaluate('let index = 0;', '++index');
if (!(value instanceof DynamicValue)) {
return fail(`Should have resolved to a DynamicValue`);
}
expect(value.node.getText()).toEqual('++index');
expect(value.isFromUnsupportedSyntax()).toBe(true);
});
it('resolves invalid element accesses as dynamic value', () => {
const value = evaluate('const a = {}; const index: any = true;', 'a[index]');
if (!(value instanceof DynamicValue)) {
return fail(`Should have resolved to a DynamicValue`);
}
expect(value.node.getText()).toEqual('a[index]');
if (!value.isFromInvalidExpressionType()) {
return fail('Should have an invalid expression type as reason');
}
expect(value.reason).toEqual(true);
});
it('resolves invalid array accesses as dynamic value', () => {
const value = evaluate('const a = []; const index = 1.5;', 'a[index]');
if (!(value instanceof DynamicValue)) {
return fail(`Should have resolved to a DynamicValue`);
}
expect(value.node.getText()).toEqual('a[index]');
if (!value.isFromInvalidExpressionType()) {
return fail('Should have an invalid expression type as reason');
}
expect(value.reason).toEqual(1.5);
});
it('resolves binary operator on non-literals as dynamic value', () => {
const value = evaluate('const a: any = []; const b: any = [];', 'a + b');
if (!(value instanceof DynamicValue)) {
return fail(`Should have resolved to a DynamicValue`);
}
expect(value.node.getText()).toEqual('a + b');
if (!(value.reason instanceof DynamicValue)) {
return fail(`Should have a DynamicValue as reason`);
}
if (!value.reason.isFromInvalidExpressionType()) {
return fail('Should have an invalid expression type as reason');
}
expect(value.reason.node.getText()).toEqual('a');
expect(value.reason.reason).toEqual([]);
});
it('resolves invalid spreads in array literals as dynamic value', () => {
const array = evaluate('const a: any = true;', '[1, ...a]');
if (!Array.isArray(array)) {
return fail(`Should have resolved to an array`);
}
expect(array[0]).toBe(1);
const value = array[1];
if (!(value instanceof DynamicValue)) {
return fail(`Should have resolved to a DynamicValue`);
}
expect(value.node.getText()).toEqual('...a');
if (!value.isFromInvalidExpressionType()) {
return fail('Should have an invalid spread element as reason');
}
expect(value.reason).toEqual(true);
});
it('resolves invalid spreads in object literals as dynamic value', () => {
const value = evaluate('const a: any = true;', '{b: true, ...a}');
if (!(value instanceof DynamicValue)) {
return fail(`Should have resolved to a DynamicValue`);
}
expect(value.node.getText()).toEqual('{b: true, ...a}');
if (!value.isFromDynamicInput()) {
return fail('Should have a dynamic input as reason');
}
expect(value.reason.node.getText()).toEqual('...a');
if (!value.reason.isFromInvalidExpressionType()) {
return fail('Should have an invalid spread element as reason');
}
expect(value.reason.reason).toEqual(true);
});
it('resolves access from external variable declarations as dynamic value', () => {
const value = evaluate('declare const window: any;', 'window.location');
if (!(value instanceof DynamicValue)) {
return fail(`Should have resolved to a DynamicValue`);
}
expect(value.isFromDynamicInput()).toEqual(true);
expect(value.node.getText()).toEqual('window.location');
if (!(value.reason instanceof DynamicValue)) {
return fail(`Should have a DynamicValue as reason`);
}
expect(value.reason.isFromExternalReference()).toEqual(true);
expect(value.reason.node.getText()).toEqual('window: any');
});
it('imports work', () => {
const {program} = makeProgram([
{name: _('/second.ts'), contents: 'export function foo(bar) { return bar; }'},
{
name: _('/entry.ts'),
contents: `
import {foo} from './second';
const target$ = foo;
`
},
]);
const checker = program.getTypeChecker();
const result = getDeclaration(program, _('/entry.ts'), 'target$', ts.isVariableDeclaration);
const expr = result.initializer!;
const evaluator = makeEvaluator(checker);
const resolved = evaluator.evaluate(expr);
if (!(resolved instanceof Reference)) {
return fail('Expected expression to resolve to a reference');
}
expect(ts.isFunctionDeclaration(resolved.node)).toBe(true);
const reference = resolved.getIdentityIn(getSourceFileOrError(program, _('/entry.ts')));
if (reference === null) {
return fail('Expected to get an identifier');
}
expect(reference.getSourceFile()).toEqual(getSourceFileOrError(program, _('/entry.ts')));
});
it('absolute imports work', () => {
const {program} = makeProgram([
{
name: _('/node_modules/some_library/index.d.ts'),
contents: 'export declare function foo(bar);'
},
{
name: _('/entry.ts'),
contents: `
import {foo} from 'some_library';
const target$ = foo;
`
},
]);
const checker = program.getTypeChecker();
const result = getDeclaration(program, _('/entry.ts'), 'target$', ts.isVariableDeclaration);
const expr = result.initializer!;
const evaluator = makeEvaluator(checker);
const resolved = evaluator.evaluate(expr);
if (!(resolved instanceof Reference)) {
return fail('Expected expression to resolve to an absolute reference');
}
expect(owningModuleOf(resolved)).toBe('some_library');
expect(ts.isFunctionDeclaration(resolved.node)).toBe(true);
const reference = resolved.getIdentityIn(getSourceFileOrError(program, _('/entry.ts')));
expect(reference).not.toBeNull();
expect(reference!.getSourceFile()).toEqual(getSourceFileOrError(program, _('/entry.ts')));
});
it('reads values from default exports', () => {
const value = evaluate(
`
import mod from './second';
`,
'mod.property', [
{name: _('/second.ts'), contents: 'export default {property: "test"}'},
]);
expect(value).toEqual('test');
});
it('reads values from named exports', () => {
const value = evaluate(`import * as mod from './second';`, 'mod.a.property', [
{name: _('/second.ts'), contents: 'export const a = {property: "test"};'},
]);
expect(value).toEqual('test');
});
it('chain of re-exports works', () => {
const value = evaluate(`import * as mod from './direct-reexport';`, 'mod.value.property', [
{name: _('/const.ts'), contents: 'export const value = {property: "test"};'},
{name: _('/def.ts'), contents: `import {value} from './const'; export default value;`},
{name: _('/indirect-reexport.ts'), contents: `import value from './def'; export {value};`},
{name: _('/direct-reexport.ts'), contents: `export {value} from './indirect-reexport';`},
]);
expect(value).toEqual('test');
});
it('map spread works', () => {
const map: Map<string, number> = evaluate<Map<string, number>>(
`const a = {a: 1}; const b = {b: 2, c: 1}; const c = {...a, ...b, c: 3};`, 'c');
const obj: {[key: string]: number} = {};
map.forEach((value, key) => obj[key] = value);
expect(obj).toEqual({
a: 1,
b: 2,
c: 3,
});
});
it('module spread works', () => {
const map = evaluate<Map<string, number>>(
`import * as mod from './module'; const c = {...mod, c: 3};`, 'c', [
{name: _('/module.ts'), contents: `export const a = 1; export const b = 2;`},
]);
const obj: {[key: string]: number} = {};
map.forEach((value, key) => obj[key] = value);
expect(obj).toEqual({
a: 1,
b: 2,
c: 3,
});
});
it('evaluates module exports lazily to avoid infinite recursion', () => {
const value = evaluate(`import * as mod1 from './mod1';`, 'mod1.primary', [
{
name: _('/mod1.ts'),
contents: `
import * as mod2 from './mod2';
export const primary = mod2.indirection;
export const secondary = 2;`
},
{
name: _('/mod2.ts'),
contents: `import * as mod1 from './mod1'; export const indirection = mod1.secondary;`
},
]);
expect(value).toEqual(2);
});
it('indirected-via-object function call works', () => {
expect(evaluate(
`
function fn(res) { return res; }
const obj = {fn};
`,
'obj.fn("test")'))
.toEqual('test');
});
it('template expressions work', () => {
expect(evaluate('const a = 2, b = 4;', '`1${a}3${b}5`')).toEqual('12345');
});
it('template expressions should resolve enums', () => {
expect(evaluate('enum Test { VALUE = "test" };', '`a.${Test.VALUE}.b`')).toBe('a.test.b');
});
it('string concatenation should resolve enums', () => {
expect(evaluate('enum Test { VALUE = "test" };', '"a." + Test.VALUE + ".b"'))
.toBe('a.test.b');
});
it('should resolve non-literals as dynamic string', () => {
const value = evaluate(`const a: any = [];`, '`a.${a}.b`');
if (!(value instanceof DynamicValue)) {
return fail(`Should have resolved to a DynamicValue`);
}
expect(value.node.getText()).toEqual('`a.${a}.b`');
if (!value.isFromDynamicInput()) {
return fail('Should originate from dynamic input');
} else if (!value.reason.isFromDynamicString()) {
return fail('Should refer to a dynamic string part');
}
expect(value.reason.node.getText()).toEqual('a');
});
it('enum resolution works', () => {
const result = evaluate(
`
enum Foo {
A,
B,
C,
}
const r = Foo.B;
`,
'r');
if (!(result instanceof EnumValue)) {
return fail(`result is not an EnumValue`);
}
expect((result.enumRef.node as ts.EnumDeclaration).name.text).toBe('Foo');
expect(result.name).toBe('B');
});
it('enum resolution works when recognized in reflection host', () => {
const {checker, expression} = makeExpression('var Foo;', 'Foo.ValueB');
const reflectionHost = new DownleveledEnumReflectionHost(checker);
const evaluator = new PartialEvaluator(reflectionHost, checker, null);
const result = evaluator.evaluate(expression);
if (!(result instanceof EnumValue)) {
return fail(`result is not an EnumValue`);
}
expect(result.enumRef.node.parent.parent.getText()).toBe('var Foo;');
expect(result.name).toBe('ValueB');
expect(result.resolved).toBe('b');
});
it('variable declaration resolution works', () => {
const value = evaluate(`import {value} from './decl';`, 'value', [
{name: _('/decl.d.ts'), contents: 'export declare let value: number;'},
]);
expect(value instanceof Reference).toBe(true);
});
it('should resolve shorthand properties to values', () => {
const {program} = makeProgram([
{name: _('/entry.ts'), contents: `const prop = 42; const target$ = {prop};`},
]);
const checker = program.getTypeChecker();
const result = getDeclaration(program, _('/entry.ts'), 'target$', ts.isVariableDeclaration);
const expr = result.initializer! as ts.ObjectLiteralExpression;
const prop = expr.properties[0] as ts.ShorthandPropertyAssignment;
const evaluator = makeEvaluator(checker);
const resolved = evaluator.evaluate(prop.name);
expect(resolved).toBe(42);
});
it('should resolve dynamic values in object literals', () => {
const {program} = makeProgram([
{name: _('/decl.d.ts'), contents: 'export declare const fn: any;'},
{
name: _('/entry.ts'),
contents:
`import {fn} from './decl'; const prop = fn.foo(); const target$ = {value: prop};`
},
]);
const checker = program.getTypeChecker();
const result = getDeclaration(program, _('/entry.ts'), 'target$', ts.isVariableDeclaration);
const expr = result.initializer! as ts.ObjectLiteralExpression;
const evaluator = makeEvaluator(checker);
const resolved = evaluator.evaluate(expr);
if (!(resolved instanceof Map)) {
return fail('Should have resolved to a Map');
}
const value = resolved.get('value')!;
if (!(value instanceof DynamicValue)) {
return fail(`Should have resolved 'value' to a DynamicValue`);
}
const prop = expr.properties[0] as ts.PropertyAssignment;
expect(value.node).toBe(prop.initializer);
});
it('should not attach identifiers to FFR-resolved values', () => {
const value = evaluate(
`
declare function foo(arg: any): any;
class Target {}
const indir = foo(Target);
const value = indir;
`,
'value', [], firstArgFfr);
if (!(value instanceof Reference)) {
return fail('Expected value to be a Reference');
}
const id = value.getIdentityIn(value.node.getSourceFile());
if (id === null) {
return fail('Expected value to have an identity');
}
expect(id.text).toEqual('Target');
});
it('should resolve functions with more than one statement to a complex function call', () => {
const value = evaluate(`function foo(bar) { const b = bar; return b; }`, 'foo("test")');
if (!(value instanceof DynamicValue)) {
return fail(`Should have resolved to a DynamicValue`);
}
if (!value.isFromComplexFunctionCall()) {
return fail('Expected DynamicValue to be from complex function call');
}
expect((value.node as ts.CallExpression).expression.getText()).toBe('foo');
expect((value.reason.node as ts.FunctionDeclaration).getText())
.toContain('const b = bar; return b;');
});
describe('(with imported TypeScript helpers)', () => {
// Helpers
const evaluateExpression = <T extends ResolvedValue>(code: string, expr: string) => {
const {checker, expression} = makeExpression(code, expr, [
{
name: _('/node_modules/tslib/index.d.ts'),
contents: `
export declare function __assign(t: any, ...sources: any[]): any;
export declare function __spread(...args: any[][]): any[];
export declare function __spreadArrays(...args: any[][]): any[];
`,
},
]);
const reflectionHost = new TsLibAwareReflectionHost(checker);
const evaluator = new PartialEvaluator(reflectionHost, checker, null);
return evaluator.evaluate(expression) as T;
};
it('should evaluate `__assign()` (named import)', () => {
const map: Map<string, boolean> = evaluateExpression(
`
import {__assign} from 'tslib';
const a = {a: true};
const b = {b: true};
`,
'__assign(a, b)');
expect([...map]).toEqual([
['a', true],
['b', true],
]);
});
it('should evaluate `__assign()` (star import)', () => {
const map: Map<string, boolean> = evaluateExpression(
`
import * as tslib from 'tslib';
const a = {a: true};
const b = {b: true};
`,
'tslib.__assign(a, b)');
expect([...map]).toEqual([
['a', true],
['b', true],
]);
});
it('should evaluate `__spread()` (named import)', () => {
const arr: number[] = evaluateExpression(
`
import {__spread} from 'tslib';
const a = [1];
const b = [2, 3];
`,
'__spread(a, b)');
expect(arr).toEqual([1, 2, 3]);
});
it('should evaluate `__spread()` (star import)', () => {
const arr: number[] = evaluateExpression(
`
import * as tslib from 'tslib';
const a = [1];
const b = [2, 3];
`,
'tslib.__spread(a, b)');
expect(arr).toEqual([1, 2, 3]);
});
it('should evaluate `__spreadArrays()` (named import)', () => {
const arr: number[] = evaluateExpression(
`
import {__spreadArrays} from 'tslib';
const a = [4];
const b = [5, 6];
`,
'__spreadArrays(a, b)');
expect(arr).toEqual([4, 5, 6]);
});
it('should evaluate `__spreadArrays()` (star import)', () => {
const arr: number[] = evaluateExpression(
`
import * as tslib from 'tslib';
const a = [4];
const b = [5, 6];
`,
'tslib.__spreadArrays(a, b)');
expect(arr).toEqual([4, 5, 6]);
});
});
describe('(with emitted TypeScript helpers as functions)', () => {
// Helpers
const evaluateExpression = <T extends ResolvedValue>(code: string, expr: string) => {
const helpers = `
function __assign(t, ...sources) { /* ... */ }
function __spread(...args) { /* ... */ }
function __spreadArrays(...args) { /* ... */ }
`;
const {checker, expression} = makeExpression(helpers + code, expr);
const reflectionHost = new TsLibAwareReflectionHost(checker);
const evaluator = new PartialEvaluator(reflectionHost, checker, null);
return evaluator.evaluate(expression) as T;
};
it('should evaluate `__assign()`', () => {
const map: Map<string, boolean> = evaluateExpression(
`
const a = {a: true};
const b = {b: true};
`,
'__assign(a, b)');
expect([...map]).toEqual([
['a', true],
['b', true],
]);
});
it('should evaluate `__spread()`', () => {
const arr: number[] = evaluateExpression(
`
const a = [1];
const b = [2, 3];
`,
'__spread(a, b)');
expect(arr).toEqual([1, 2, 3]);
});
it('should evaluate `__spreadArrays()`', () => {
const arr: number[] = evaluateExpression(
`
const a = [4];
const b = [5, 6];
`,
'__spreadArrays(a, b)');
expect(arr).toEqual([4, 5, 6]);
});
});
describe('(with emitted TypeScript helpers as variables)', () => {
// Helpers
const evaluateExpression = <T extends ResolvedValue>(code: string, expr: string) => {
const helpers = `
var __assign = (this && this.__assign) || function (t, ...sources) { /* ... */ }
var __spread = (this && this.__spread) || function (...args) { /* ... */ }
var __spreadArrays = (this && this.__spreadArrays) || function (...args) { /* ... */ }
`;
const {checker, expression} = makeExpression(helpers + code, expr);
const reflectionHost = new TsLibAwareReflectionHost(checker);
const evaluator = new PartialEvaluator(reflectionHost, checker, null);
return evaluator.evaluate(expression) as T;
};
it('should evaluate `__assign()`', () => {
const map: Map<string, boolean> = evaluateExpression(
`
const a = {a: true};
const b = {b: true};
`,
'__assign(a, b)');
expect([...map]).toEqual([
['a', true],
['b', true],
]);
});
it('should evaluate `__spread()`', () => {
const arr: number[] = evaluateExpression(
`
const a = [1];
const b = [2, 3];
`,
'__spread(a, b)');
expect(arr).toEqual([1, 2, 3]);
});
it('should evaluate `__spreadArrays()`', () => {
const arr: number[] = evaluateExpression(
`
const a = [4];
const b = [5, 6];
`,
'__spreadArrays(a, b)');
expect(arr).toEqual([4, 5, 6]);
});
});
describe('(visited file tracking)', () => {
it('should track each time a source file is visited', () => {
const addDependency =
jasmine.createSpy<DependencyTracker['addDependency']>('DependencyTracker');
const {expression, checker, program} = makeExpression(
`class A { static foo = 42; } function bar() { return A.foo; }`, 'bar()');
const entryPath = getSourceFileOrError(program, _('/entry.ts')).fileName;
const evaluator = makeEvaluator(checker, {...fakeDepTracker, addDependency});
evaluator.evaluate(expression);
expect(addDependency).toHaveBeenCalledTimes(2); // two declaration visited
expect(
addDependency.calls.allArgs().map(
(args: Parameters<typeof addDependency>) => [args[0].fileName, args[1].fileName]))
.toEqual([[entryPath, entryPath], [entryPath, entryPath]]);
});
it('should track imported source files', () => {
const addDependency =
jasmine.createSpy<DependencyTracker['addDependency']>('DependencyTracker');
const {expression, checker, program} =
makeExpression(`import {Y} from './other'; const A = Y;`, 'A', [
{name: _('/other.ts'), contents: `export const Y = 'test';`},
{name: _('/not-visited.ts'), contents: `export const Z = 'nope';`}
]);
const entryPath = getSourceFileOrError(program, _('/entry.ts')).fileName;
const otherPath = getSourceFileOrError(program, _('/other.ts')).fileName;
const evaluator = makeEvaluator(checker, {...fakeDepTracker, addDependency});
evaluator.evaluate(expression);
expect(addDependency).toHaveBeenCalledTimes(2);
expect(
addDependency.calls.allArgs().map(
(args: Parameters<typeof addDependency>) => [args[0].fileName, args[1].fileName]))
.toEqual([
[entryPath, entryPath],
[entryPath, otherPath],
]);
});
it('should track files passed through during re-exports', () => {
const addDependency =
jasmine.createSpy<DependencyTracker['addDependency']>('DependencyTracker');
const {expression, checker, program} =
makeExpression(`import * as mod from './direct-reexport';`, 'mod.value.property', [
{name: _('/const.ts'), contents: 'export const value = {property: "test"};'},
{
name: _('/def.ts'),
contents: `import {value} from './const'; export default value;`
},
{
name: _('/indirect-reexport.ts'),
contents: `import value from './def'; export {value};`
},
{
name: _('/direct-reexport.ts'),
contents: `export {value} from './indirect-reexport';`
},
]);
const evaluator = makeEvaluator(checker, {...fakeDepTracker, addDependency});
const entryPath = getSourceFileOrError(program, _('/entry.ts')).fileName;
const directReexportPath = getSourceFileOrError(program, _('/direct-reexport.ts')).fileName;
const constPath = getSourceFileOrError(program, _('/const.ts')).fileName;
evaluator.evaluate(expression);
expect(addDependency).toHaveBeenCalledTimes(2);
expect(
addDependency.calls.allArgs().map(
(args: Parameters<typeof addDependency>) => [args[0].fileName, args[1].fileName]))
.toEqual([
[entryPath, directReexportPath],
// Not '/indirect-reexport.ts' or '/def.ts'.
// TS skips through them when finding the original symbol for `value`
[entryPath, constPath],
]);
});
});
});
class DownleveledEnumReflectionHost extends TypeScriptReflectionHost {
getDeclarationOfIdentifier(id: ts.Identifier): Declaration|null {
const declaration = super.getDeclarationOfIdentifier(id);
if (declaration !== null && declaration.node !== null) {
const enumMembers = [
{name: ts.createStringLiteral('ValueA'), initializer: ts.createStringLiteral('a')},
{name: ts.createStringLiteral('ValueB'), initializer: ts.createStringLiteral('b')},
];
declaration.identity = {kind: SpecialDeclarationKind.DownleveledEnum, enumMembers};
}
return declaration;
}
}
/**
* Customizes the resolution of module exports and identifier declarations to recognize known
* helper functions from `tslib`. Such functions are not handled specially in the default
* TypeScript host, as only ngcc's ES5 hosts will have special powers to recognize such functions.
*/
class TsLibAwareReflectionHost extends TypeScriptReflectionHost {
getExportsOfModule(node: ts.Node): Map<string, Declaration>|null {
const map = super.getExportsOfModule(node);
if (map !== null) {
map.forEach(decl => decl.known = decl.known || (decl.node && getTsHelperFn(decl.node)));
}
return map;
}
getDeclarationOfIdentifier(id: ts.Identifier): Declaration|null {
const superDeclaration = super.getDeclarationOfIdentifier(id);
if (superDeclaration === null || superDeclaration.node === null) {
return superDeclaration;
}
const tsHelperFn = getTsHelperFn(superDeclaration.node);
if (tsHelperFn !== null) {
return {
known: tsHelperFn,
node: id,
viaModule: null,
importName: null,
identity: null,
};
}
return superDeclaration;
}
}
function getTsHelperFn(node: ts.Declaration): KnownDeclaration|null {
const id = (node as ts.Declaration & {name?: ts.Identifier}).name || null;
const name = id && id.text;
switch (name) {
case '__assign':
return KnownDeclaration.TsHelperAssign;
case '__spread':
return KnownDeclaration.TsHelperSpread;
case '__spreadArrays':
return KnownDeclaration.TsHelperSpreadArrays;
default:
return null;
}
}
});
const fakeDepTracker: DependencyTracker = {
addDependency: () => undefined,
addResourceDependency: () => undefined,
addTransitiveDependency: () => undefined,
addTransitiveResources: () => undefined,
};