Repository navigation
Expand file tree
/
Copy pathsyscript.patch
More file actions
852 lines (849 loc) · 32.9 KB
/
Copy pathsyscript.patch
File metadata and controls
852 lines (849 loc) · 32.9 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
diff --git a/syscript.sh b/syscript.sh
new file mode 100755
index 0000000000..12ada22a41
--- /dev/null
+++ b/syscript.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+cd "$(dirname "$0")"
+
+base=$(git log --diff-filter=A --format=%H -- tsc/internal/checker/ssc.go | tail -n 1)^
+git diff "$base" -- . ':(exclude)syscript.patch' > syscript.patch
+
+node_include_dir=$(node -p "require('path').join(process.execPath, '..', '..', 'include', 'node')")
+
+cd tsc
+go build -o ../built/local/tsc ./cmd/tsc
+CGO_CFLAGS="-I$node_include_dir" go build -buildmode=c-shared -o ../built/local/tsc.node ./cmd/sscapi
+rm -f ../built/local/tsc.h
diff --git a/tsc/cmd/sscapi/addon.c b/tsc/cmd/sscapi/addon.c
new file mode 100644
index 0000000000..4bdd0cf362
--- /dev/null
+++ b/tsc/cmd/sscapi/addon.c
@@ -0,0 +1,48 @@
+#include <stdlib.h>
+#include <node_api.h>
+#include "_cgo_export.h"
+
+static napi_value open(napi_env env, napi_callback_info info) {
+ size_t argc = 1;
+ napi_value argv[1];
+ napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
+ char cwd[4096];
+ size_t cwdLength;
+ napi_get_value_string_utf8(env, argv[0], cwd, sizeof cwd, &cwdLength);
+ sscApiOpen(cwd, (int)cwdLength);
+ return NULL;
+}
+
+static napi_value request(napi_env env, napi_callback_info info) {
+ size_t argc = 2;
+ napi_value argv[2];
+ napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
+ char method[256];
+ size_t methodLength;
+ napi_get_value_string_utf8(env, argv[0], method, sizeof method, &methodLength);
+ void *params;
+ size_t paramsLength;
+ napi_get_buffer_info(env, argv[1], ¶ms, ¶msLength);
+ int resultLength = 0;
+ int isError = 0;
+ char *result = sscApiRequest(method, (int)methodLength, params, (int)paramsLength, &resultLength, &isError);
+ napi_value value = NULL;
+ if (isError) {
+ result = realloc(result, resultLength + 1);
+ result[resultLength] = 0;
+ napi_throw_error(env, NULL, result);
+ } else {
+ napi_create_buffer_copy(env, resultLength, result, NULL, &value);
+ }
+ free(result);
+ return value;
+}
+
+NAPI_MODULE_INIT() {
+ napi_value function;
+ napi_create_function(env, "open", NAPI_AUTO_LENGTH, open, NULL, &function);
+ napi_set_named_property(env, exports, "open", function);
+ napi_create_function(env, "request", NAPI_AUTO_LENGTH, request, NULL, &function);
+ napi_set_named_property(env, exports, "request", function);
+ return exports;
+}
diff --git a/tsc/cmd/sscapi/main.go b/tsc/cmd/sscapi/main.go
new file mode 100644
index 0000000000..db1982509b
--- /dev/null
+++ b/tsc/cmd/sscapi/main.go
@@ -0,0 +1,59 @@
+package main
+
+/*
+#include <stdlib.h>
+*/
+import "C"
+
+import (
+ "context"
+ "os"
+ "unsafe"
+
+ "github.com/microsoft/TypeScript/tsc/internal/api"
+ "github.com/microsoft/TypeScript/tsc/internal/bundled"
+ "github.com/microsoft/TypeScript/tsc/internal/json"
+ "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto"
+ "github.com/microsoft/TypeScript/tsc/internal/project"
+ "github.com/microsoft/TypeScript/tsc/internal/tspath"
+ "github.com/microsoft/TypeScript/tsc/internal/vfs/osvfs"
+)
+
+var session *api.Session
+
+func main() {}
+
+//export sscApiOpen
+func sscApiOpen(cwd *C.char, cwdLength C.int) {
+ directory := C.GoStringN(cwd, cwdLength)
+ workingDirectory, _ := os.Getwd()
+ session = api.NewStandaloneSession(&project.SessionInit{
+ BackgroundCtx: context.Background(),
+ FS: bundled.WrapFS(osvfs.FS()),
+ Options: &project.SessionOptions{
+ CurrentDirectory: tspath.ToRootedDirectoryPath(directory, tspath.ToRootedDirectoryPath(workingDirectory, "")),
+ DefaultLibraryPath: bundled.LibPath(),
+ PositionEncoding: lsproto.PositionEncodingKindUTF8,
+ },
+ }, &api.SessionOptions{})
+}
+
+//export sscApiRequest
+func sscApiRequest(method *C.char, methodLength C.int, params *C.char, paramsLength C.int, resultLength *C.int, isError *C.int) unsafe.Pointer {
+ result, err := session.HandleRequest(context.Background(), C.GoStringN(method, methodLength), json.Value(C.GoBytes(unsafe.Pointer(params), paramsLength)))
+ var payload []byte
+ if err != nil {
+ *isError = 1
+ payload = []byte(err.Error())
+ } else if raw, ok := result.(api.RawBinary); ok {
+ payload = raw
+ } else {
+ payload, err = json.Marshal(result)
+ if err != nil {
+ *isError = 1
+ payload = []byte(err.Error())
+ }
+ }
+ *resultLength = C.int(len(payload))
+ return C.CBytes(payload)
+}
diff --git a/tsc/internal/checker/checker.go b/tsc/internal/checker/checker.go
index 73de52e18d..732e2734e9 100644
--- a/tsc/internal/checker/checker.go
+++ b/tsc/internal/checker/checker.go
@@ -922,6 +922,10 @@ type Checker struct {
mu sync.Mutex
tracer *Tracer // Optional tracer for trace events and type recording (for --generateTrace)
+
+ ssc_PreludeSymbolByBrand map[*ast.Symbol]*ast.Symbol // syscript
+ ssc_PreludeSymbolByName map[string]*ast.Symbol // syscript
+ ssc_Enabled bool // syscript
}
func NewChecker(program Program, tracer *Tracer) (*Checker, *sync.Mutex) {
@@ -11127,6 +11131,9 @@ func (c *Checker) checkPrefixUnaryExpression(node *ast.Node) *Type {
if c.maybeTypeOfKindConsideringBaseConstraint(operandType, TypeFlagsESSymbolLike) {
c.error(expr.Operand, diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, scanner.TokenToString(expr.Operator))
}
+ if ssc_type := c.ssc_UnaryResultTypeOrReportError(operandType, expr.Operator, expr.Operand); ssc_type != nil { // syscript
+ return ssc_type
+ }
if expr.Operator == ast.KindPlusToken {
if c.maybeTypeOfKindConsideringBaseConstraint(operandType, TypeFlagsBigIntLike) {
c.error(expr.Operand, diagnostics.Operator_0_cannot_be_applied_to_type_1, scanner.TokenToString(expr.Operator), c.TypeToString(c.getBaseTypeOfLiteralType(operandType)))
@@ -11151,6 +11158,9 @@ func (c *Checker) checkPrefixUnaryExpression(node *ast.Node) *Type {
// run check only if former checks succeeded to avoid reporting cascading errors
c.checkReferenceExpression(expr.Operand, diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access)
}
+ if ssc_type := c.ssc_UnaryResultTypeOrReportError(operandType, expr.Operator, expr.Operand); ssc_type != nil { // syscript
+ return ssc_type
+ }
return c.getUnaryResultType(operandType)
}
return c.errorType
@@ -11167,6 +11177,9 @@ func (c *Checker) checkPostfixUnaryExpression(node *ast.Node) *Type {
// run check only if former checks succeeded to avoid reporting cascading errors
c.checkReferenceExpression(expr.Operand, diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access)
}
+ if ssc_type := c.ssc_UnaryResultTypeOrReportError(operandType, expr.Operator, expr.Operand); ssc_type != nil { // syscript
+ return ssc_type
+ }
return c.getUnaryResultType(operandType)
}
@@ -12636,6 +12649,9 @@ func (c *Checker) checkBinaryLikeExpression(left *ast.Node, operatorToken *ast.N
// If both are any or unknown, allow operation; assume it will resolve to number
if c.isTypeAssignableToKind(leftType, TypeFlagsAnyOrUnknown) && c.isTypeAssignableToKind(rightType, TypeFlagsAnyOrUnknown) || !c.maybeTypeOfKind(leftType, TypeFlagsBigIntLike) && !c.maybeTypeOfKind(rightType, TypeFlagsBigIntLike) {
resultType = c.numberType
+ if ssc_type := c.ssc_BinaryResultTypeOrReportError(leftType, rightType, operator, errorNode); ssc_type != nil { // syscript
+ resultType = ssc_type
+ }
} else if c.bothAreBigIntLike(leftType, rightType) {
switch operator {
case ast.KindGreaterThanGreaterThanGreaterThanToken, ast.KindGreaterThanGreaterThanGreaterThanEqualsToken:
@@ -12677,6 +12693,9 @@ func (c *Checker) checkBinaryLikeExpression(left *ast.Node, operatorToken *ast.N
// Operands of an enum type are treated as having the primitive type Number.
// If both operands are of the Number primitive type, the result is of the Number primitive type.
resultType = c.numberType
+ if ssc_type := c.ssc_BinaryResultTypeOrReportError(leftType, rightType, operator, errorNode); ssc_type != nil { // syscript
+ resultType = ssc_type
+ }
} else if c.isTypeAssignableToKindEx(leftType, TypeFlagsBigIntLike, true /*strict*/) && c.isTypeAssignableToKindEx(rightType, TypeFlagsBigIntLike, true /*strict*/) {
// If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
resultType = c.bigintType
@@ -12690,6 +12709,9 @@ func (c *Checker) checkBinaryLikeExpression(left *ast.Node, operatorToken *ast.N
resultType = c.errorType
} else {
resultType = c.anyType
+ if result := c.ssc_BinaryResultTypeOrReportError(leftType, rightType, operator, errorNode); result != nil { // syscript
+ resultType = result
+ }
}
}
// Symbols are not allowed at all in arithmetic expressions
@@ -12712,6 +12734,9 @@ func (c *Checker) checkBinaryLikeExpression(left *ast.Node, operatorToken *ast.N
}
return resultType
case ast.KindLessThanToken, ast.KindGreaterThanToken, ast.KindLessThanEqualsToken, ast.KindGreaterThanEqualsToken:
+ if c.ssc_BinaryResultTypeOrReportError(leftType, rightType, operator, errorNode) != nil { // syscript
+ return c.booleanType
+ }
if c.checkForDisallowedESSymbolOperand(left, right, leftType, rightType, operator) {
leftType = c.getBaseTypeOfLiteralTypeForComparison(c.checkNonNullType(leftType, left))
rightType = c.getBaseTypeOfLiteralTypeForComparison(c.checkNonNullType(rightType, right))
@@ -12748,7 +12773,9 @@ func (c *Checker) checkBinaryLikeExpression(left *ast.Node, operatorToken *ast.N
return c.checkInExpression(left, right, leftType, rightType)
case ast.KindAmpersandAmpersandToken, ast.KindAmpersandAmpersandEqualsToken:
resultType := leftType
- if c.hasTypeFacts(leftType, TypeFactsTruthy) {
+ if ssc_type := c.ssc_LogicalResultTypeOrReportError(leftType, rightType, operator, errorNode); ssc_type != nil { // syscript
+ resultType = ssc_type
+ } else if c.hasTypeFacts(leftType, TypeFactsTruthy) {
t := leftType
if !c.strictNullChecks {
t = c.getBaseTypeOfLiteralType(rightType)
@@ -12761,7 +12788,9 @@ func (c *Checker) checkBinaryLikeExpression(left *ast.Node, operatorToken *ast.N
return resultType
case ast.KindBarBarToken, ast.KindBarBarEqualsToken:
resultType := leftType
- if c.hasTypeFacts(leftType, TypeFactsFalsy) {
+ if ssc_type := c.ssc_LogicalResultTypeOrReportError(leftType, rightType, operator, errorNode); ssc_type != nil { // syscript
+ resultType = ssc_type
+ } else if c.hasTypeFacts(leftType, TypeFactsFalsy) {
resultType = c.getUnionTypeEx([]*Type{c.GetNonNullableType(c.removeDefinitelyFalsyTypes(leftType)), rightType}, UnionReductionSubtype, nil, nil)
}
if operator == ast.KindBarBarEqualsToken {
diff --git a/tsc/internal/checker/ssc.go b/tsc/internal/checker/ssc.go
new file mode 100644
index 0000000000..778fe5dc70
--- /dev/null
+++ b/tsc/internal/checker/ssc.go
@@ -0,0 +1,226 @@
+package checker
+
+import (
+ "fmt"
+ "slices"
+ "strings"
+
+ "github.com/microsoft/TypeScript/tsc/internal/ast"
+ "github.com/microsoft/TypeScript/tsc/internal/diagnostics"
+ "github.com/microsoft/TypeScript/tsc/internal/scanner"
+)
+
+var ssc_signedTypes = []string{"i8", "i16", "i32", "i64"}
+
+var ssc_unsignedTypes = []string{"u8", "u16", "u32", "u64", "char"}
+
+var ssc_floatTypes = []string{"f32", "f64"}
+
+var ssc_types = slices.Concat(ssc_signedTypes, ssc_unsignedTypes, ssc_floatTypes)
+
+var ssc_bitwiseOperators = []ast.Kind{
+ ast.KindAmpersandEqualsToken,
+ ast.KindAmpersandToken,
+ ast.KindBarEqualsToken,
+ ast.KindBarToken,
+ ast.KindCaretEqualsToken,
+ ast.KindCaretToken,
+ ast.KindGreaterThanGreaterThanEqualsToken,
+ ast.KindGreaterThanGreaterThanGreaterThanEqualsToken,
+ ast.KindGreaterThanGreaterThanGreaterThanToken,
+ ast.KindGreaterThanGreaterThanToken,
+ ast.KindLessThanLessThanEqualsToken,
+ ast.KindLessThanLessThanToken,
+ ast.KindTildeToken,
+}
+
+func (c *Checker) ssc_loadPrelude() (symbolByBrand map[*ast.Symbol]*ast.Symbol, symbolByName map[string]*ast.Symbol) {
+ if c.ssc_PreludeSymbolByBrand != nil {
+ return c.ssc_PreludeSymbolByBrand, c.ssc_PreludeSymbolByName
+ }
+ symbolByBrand = map[*ast.Symbol]*ast.Symbol{}
+ symbolByName = map[string]*ast.Symbol{}
+ for name := range slices.Values(ssc_types) {
+ symbol := c.getGlobalSymbol(name, ast.SymbolFlagsTypeAlias, nil)
+ if symbol == nil {
+ continue
+ }
+ declaration := ast.GetDeclarationOfKind(symbol, ast.KindTypeAliasDeclaration)
+ if declaration == nil {
+ continue
+ }
+ sourceFile := ast.GetSourceFileOfNode(declaration)
+ if sourceFile == nil || sourceFile.FileName().BaseName() != "prelude.d.ts" {
+ continue
+ }
+ packageJsonDirectory := c.program.GetSourceFileMetaData(sourceFile.PathKey()).PackageJsonDirectory
+ if packageJsonDirectory == "" {
+ continue
+ }
+ packageJson := c.program.GetPackageJsonInfo(packageJsonDirectory.ResolveFile("package.json")).GetContents()
+ if packageJson == nil {
+ continue
+ }
+ if packageName, ok := packageJson.Name.GetValue(); ok && packageName == "syscript" {
+ brand := ssc_getSscBrandTypeLiteral(declaration, name)
+ if brand == nil {
+ continue
+ }
+ symbolByBrand[brand.Symbol()] = symbol
+ symbolByName[name] = symbol
+ }
+ }
+ c.ssc_PreludeSymbolByBrand = symbolByBrand
+ c.ssc_PreludeSymbolByName = symbolByName
+ c.ssc_Enabled = len(symbolByName) == len(ssc_types)
+ return symbolByBrand, symbolByName
+}
+
+func ssc_getSscBrandTypeLiteral(declaration *ast.Node, expectedName string) *ast.Node {
+ typeNode := declaration.Type()
+ if !ast.IsIntersectionTypeNode(typeNode) {
+ return nil
+ }
+ expectedProperty := fmt.Sprintf("readonly [ssc]: '%s'", expectedName)
+ for memberTypeNode := range slices.Values(typeNode.AsIntersectionTypeNode().Types.Nodes) {
+ if ast.IsTypeLiteralNode(memberTypeNode) && strings.Contains(scanner.GetTextOfNode(memberTypeNode), expectedProperty) {
+ return memberTypeNode
+ }
+ }
+ return nil
+}
+
+func (c *Checker) ssc_type(t *Type) *Type {
+ symbolByBrand, _ := c.ssc_loadPrelude()
+ if t.flags&(TypeFlagsNumber|TypeFlagsNumberLiteral) != 0 {
+ return c.numberType
+ }
+ if t.flags&TypeFlagsIntersection == 0 {
+ return nil
+ }
+ for memberType := range slices.Values(t.Types()) {
+ if symbol := symbolByBrand[memberType.symbol]; symbol != nil {
+ return c.getDeclaredTypeOfSymbol(symbol)
+ }
+ }
+ return nil
+}
+
+func (c *Checker) ssc_name(t *Type) string {
+ if t == c.numberType {
+ return "number"
+ }
+ _, symbolByName := c.ssc_loadPrelude()
+ for name, symbol := range symbolByName {
+ if t == c.getDeclaredTypeOfSymbol(symbol) {
+ return name
+ }
+ }
+ panic("not a syscript number type: " + c.TypeToString(t))
+}
+
+func (c *Checker) ssc_IsEnabled() bool {
+ c.ssc_loadPrelude()
+ return c.ssc_Enabled
+}
+
+func (c *Checker) ssc_CommonType(types ...*Type) (isSsc bool, commonType *Type) {
+ if !c.ssc_IsEnabled() {
+ return false, nil
+ }
+ var sscTypes []*Type
+ for t := range slices.Values(types) {
+ memberTypes := []*Type{t}
+ if t.flags&TypeFlagsUnion != 0 {
+ memberTypes = t.Types()
+ }
+ for memberType := range slices.Values(memberTypes) {
+ sscType := c.ssc_type(memberType)
+ if sscType == nil {
+ return false, nil
+ }
+ sscTypes = append(sscTypes, sscType)
+ }
+ }
+ if len(sscTypes) == 0 {
+ return false, nil
+ }
+ if slices.ContainsFunc(sscTypes, func(sscType *Type) bool { return sscType != sscTypes[0] }) {
+ return true, nil
+ }
+ return true, sscTypes[0]
+}
+
+func (c *Checker) ssc_UnaryResultTypeOrReportError(operandType *Type, operator ast.Kind, errorNode *ast.Node) *Type {
+ if !c.ssc_IsEnabled() {
+ return nil
+ }
+ isSsc, result := c.ssc_CommonType(operandType)
+ if !isSsc {
+ return nil
+ }
+ if result != nil {
+ name := c.ssc_name(result)
+ if operator == ast.KindMinusToken && slices.Contains(ssc_unsignedTypes, name) ||
+ slices.Contains(ssc_floatTypes, name) && slices.Contains(ssc_bitwiseOperators, operator) {
+ result = nil
+ }
+ }
+ if result == nil {
+ c.error(errorNode, diagnostics.Operator_0_cannot_be_applied_to_type_1, scanner.TokenToString(operator), c.TypeToString(operandType))
+ return c.errorType
+ }
+ return result
+}
+
+func (c *Checker) ssc_BinaryResultType(left *Type, right *Type) (isSsc bool, result *Type) {
+ if !c.ssc_IsEnabled() {
+ return false, nil
+ }
+ leftIsSsc, _ := c.ssc_CommonType(left)
+ rightIsSsc, _ := c.ssc_CommonType(right)
+ if !leftIsSsc && !rightIsSsc {
+ return false, nil
+ }
+ _, result = c.ssc_CommonType(left, right)
+ return true, result
+}
+
+func (c *Checker) ssc_BinaryResultTypeOrReportError(left *Type, right *Type, operator ast.Kind, errorNode *ast.Node) *Type {
+ if !c.ssc_IsEnabled() {
+ return nil
+ }
+ isSsc, result := c.ssc_BinaryResultType(left, right)
+ if !isSsc {
+ return nil
+ }
+ if result != nil {
+ name := c.ssc_name(result)
+ if slices.Contains(ssc_floatTypes, name) && slices.Contains(ssc_bitwiseOperators, operator) {
+ result = nil
+ }
+ }
+ if result == nil {
+ c.reportOperatorError(left, operator, right, errorNode, nil)
+ return c.errorType
+ }
+ return result
+}
+
+func (c *Checker) ssc_LogicalResultTypeOrReportError(left *Type, right *Type, operator ast.Kind, errorNode *ast.Node) *Type {
+ if !c.ssc_IsEnabled() {
+ return nil
+ }
+ if leftIsSsc, _ := c.ssc_CommonType(left); !leftIsSsc {
+ return nil
+ }
+ if rightIsSsc, _ := c.ssc_CommonType(right); !rightIsSsc {
+ return nil
+ }
+ _, result := c.ssc_CommonType(left, right)
+ if result == nil {
+ c.reportOperatorError(left, operator, right, errorNode, nil)
+ return c.errorType
+ }
+ return result
+}
diff --git a/tsc/internal/checker/ssc_test.go b/tsc/internal/checker/ssc_test.go
new file mode 100644
index 0000000000..808239531f
--- /dev/null
+++ b/tsc/internal/checker/ssc_test.go
@@ -0,0 +1,368 @@
+package checker_test
+
+import (
+ "encoding/json"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/microsoft/TypeScript/tsc/internal/ast"
+ "github.com/microsoft/TypeScript/tsc/internal/bundled"
+ "github.com/microsoft/TypeScript/tsc/internal/compiler"
+ "github.com/microsoft/TypeScript/tsc/internal/core"
+ "github.com/microsoft/TypeScript/tsc/internal/diagnosticwriter"
+ "github.com/microsoft/TypeScript/tsc/internal/locale"
+ "github.com/microsoft/TypeScript/tsc/internal/tsoptions"
+ "github.com/microsoft/TypeScript/tsc/internal/tspath"
+ "github.com/microsoft/TypeScript/tsc/internal/vfs/vfstest"
+ "gotest.tools/v3/assert"
+)
+
+const ssc_prelude = `export {};
+declare const ssc: unique symbol;
+declare global {
+ type i8 = number & { readonly [ssc]: 'i8' };
+ type i16 = number & { readonly [ssc]: 'i16' };
+ type i32 = number & { readonly [ssc]: 'i32' };
+ type i64 = number & { readonly [ssc]: 'i64' };
+ type u8 = number & { readonly [ssc]: 'u8' };
+ type u16 = number & { readonly [ssc]: 'u16' };
+ type u32 = number & { readonly [ssc]: 'u32' };
+ type u64 = number & { readonly [ssc]: 'u64' };
+ type f32 = number & { readonly [ssc]: 'f32' };
+ type f64 = number & { readonly [ssc]: 'f64' };
+ type char = number & { readonly [ssc]: 'char' };
+ interface Array<T> { length: u64; [n: number]: T; [n: i64]: T; [n: u64]: T }
+ interface Boolean {}
+ interface CallableFunction {}
+ interface Function {}
+ interface IArguments {}
+ interface NewableFunction {}
+ interface Number {}
+ interface Object {}
+ interface RegExp {}
+ interface String {}
+}
+`
+
+const ssc_declarations = `declare const c: boolean;
+declare const n: number;
+declare const x: any;
+declare const lit: 1 | 2;
+declare const items: string[];
+declare function abs(v: number): number;
+enum E { A, B }
+declare const e: E;
+declare let a8: i8;
+declare let a16: i16;
+declare let a32: i32;
+declare let b32: i32;
+declare let a64: i64;
+declare let ua8: u8;
+declare let ua32: u32;
+declare let ua64: u64;
+declare let fa32: f32;
+declare let fa64: f64;
+declare let ch: char;
+declare let ch2: char;
+`
+
+type ssc_result struct {
+ resultType string
+ codes []int32
+ messages []string
+ suggestionCodes []int32
+}
+
+func ssc_messageTexts(diagnostic *ast.Diagnostic) []string {
+ texts := []string{diagnosticwriter.WrapASTDiagnostic(diagnostic).Localize(locale.Default)}
+ for chained := range slices.Values(diagnostic.MessageChain()) {
+ texts = append(texts, ssc_messageTexts(chained)...)
+ }
+ return texts
+}
+
+func ssc_check(t *testing.T, files map[string]string, rootFiles []string) ssc_result {
+ t.Helper()
+ config, err := json.Marshal(map[string]any{
+ "compilerOptions": map[string]any{"strict": true, "noEmit": true, "noLib": true},
+ "files": rootFiles,
+ })
+ assert.NilError(t, err)
+ files["/tsconfig.json"] = string(config)
+ fs := bundled.WrapFS(vfstest.FromMap(files, tspath.CaseSensitive))
+ host := compiler.NewCompilerHost(fs, bundled.LibPath(), nil, nil, nil)
+ parsed, errors := tsoptions.GetParsedCommandLineOfConfigFile("/tsconfig.json", &core.CompilerOptions{}, nil, fs, nil)
+ assert.Equal(t, len(errors), 0, "Expected no errors in parsed command line")
+ p := compiler.NewProgram(compiler.ProgramOptions{Config: parsed, Host: host})
+ p.BindSourceFiles()
+ file := p.GetSourceFile("/main.ts")
+ var result ssc_result
+ for sourceFile := range slices.Values(p.GetSourceFiles()) {
+ for diagnostic := range slices.Values(p.GetSemanticDiagnostics(t.Context(), sourceFile)) {
+ result.codes = append(result.codes, diagnostic.Code())
+ result.messages = append(result.messages, ssc_messageTexts(diagnostic)...)
+ }
+ }
+ for diagnostic := range slices.Values(p.GetSuggestionDiagnostics(t.Context(), file)) {
+ result.suggestionCodes = append(result.suggestionCodes, diagnostic.Code())
+ }
+ c, done := p.GetTypeChecker(t.Context())
+ defer done()
+ for statement := range slices.Values(file.Statements.Nodes) {
+ if statement.Kind != ast.KindVariableStatement {
+ continue
+ }
+ for declaration := range slices.Values(statement.AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes) {
+ if declaration.Name().Text() == "r" {
+ result.resultType = c.TypeToString(c.GetTypeAtLocation(declaration.Name()))
+ }
+ }
+ }
+ return result
+}
+
+func ssc_checkSource(t *testing.T, source string) ssc_result {
+ t.Helper()
+ return ssc_check(t, map[string]string{
+ "/node_modules/syscript/package.json": `{ "name": "syscript", "version": "0.0.0" }`,
+ "/node_modules/syscript/prelude.d.ts": ssc_prelude,
+ "/main.ts": ssc_declarations + source + "\nexport {};\n",
+ }, []string{"node_modules/syscript/prelude.d.ts", "main.ts"})
+}
+
+func TestSscOperators(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ source string
+ resultType string
+ codes []int32
+ }{
+ {"same type", "const r = a32 + b32;", "i32", nil},
+ {"different types", "const r = a32 + a64;", "any", []int32{2365}},
+ {"literal is a number", "const r = a32 + 1;", "any", []int32{2365}},
+ {"literal with f64", "const r = fa64 + 1;", "any", []int32{2365}},
+ {"number with f64", "const r = fa64 + n;", "any", []int32{2365}},
+ {"f64 with f64", "const r = fa64 * fa64;", "f64", nil},
+ {"number with i32", "const r = a32 + n;", "any", []int32{2365}},
+ {"literals only", "const r = 1 + 2;", "number", nil},
+ {"literal variable stays a literal", "const r = 1;", "1", nil},
+ {"number only", "const r = n + n;", "number", nil},
+ {"constructor result", "declare function i32(v: number): i32;\nconst r = a32 + i32(1);", "i32", nil},
+ {"same type union", "const r = (c ? a32 : b32) + a32;", "i32", nil},
+ {"mixed union", "const r = (c ? a32 : a64) + a32;", "any", []int32{2365}},
+ {"string concatenation", `const r = a32 + "s";`, "string", nil},
+ {"template literal", "const r = `${a64}`;", "string", nil},
+ {"bigint operand", "const r = a32 + 1n;", "any", []int32{2365}},
+ {"boolean operand", "const r = a32 + c;", "any", []int32{2365}},
+ {"any operand", "const r = a32 + x;", "any", []int32{2365}},
+ {"numeric enum", "const r = a32 * e;", "any", []int32{2365}},
+ {"division", "const r = a32 / b32;", "i32", nil},
+ {"remainder", "const r = a32 % b32;", "i32", nil},
+ {"bitwise", "const r = a32 & b32;", "i32", nil},
+ {"shift", "const r = a32 << b32;", "i32", nil},
+ {"unsigned shift", "const r = ua32 >>> ua32;", "u32", nil},
+ {"bitwise on float", "const r = fa32 & fa32;", "any", []int32{2365}},
+ {"bitwise on number like JS", "const r = n | 0;", "number", nil},
+ {"bitwise on f64", "const r = fa64 & fa64;", "any", []int32{2365}},
+ {"shift on f64", "const r = fa64 >>> fa64;", "any", []int32{2365}},
+ {"enum bitwise", "const r = E.A | E.B;", "number", nil},
+ {"unary minus", "const r = -a32;", "i32", nil},
+ {"unary minus on unsigned", "const r = -ua8;", "any", []int32{2736}},
+ {"unary minus on f32", "const r = -fa32;", "f32", nil},
+ {"unary plus keeps type", "const r = +a32;", "i32", nil},
+ {"unary bitwise", "const r = ~ua8;", "u8", nil},
+ {"unary bitwise on f32", "const r = ~fa32;", "any", []int32{2736}},
+ {"unary bitwise on f64", "const r = ~fa64;", "any", []int32{2736}},
+ {"unary minus on number", "const r = -n;", "number", nil},
+ {"unary bitwise on number", "const r = ~n;", "number", nil},
+ {"prefix increment", "const r = ++a64;", "i64", nil},
+ {"postfix increment", "const r = a32++;", "i32", nil},
+ {"compound assignment", "a32 += b32;", "", nil},
+ {"compound assignment with literal", "a32 += 1;", "", []int32{2365}},
+ {"compound assignment with other type", "a64 += a32;", "", []int32{2365}},
+ {"relational", "const r = a32 < b32;", "boolean", nil},
+ {"relational different types", "const r = a32 < a64;", "boolean", []int32{2365}},
+ {"relational literal", "const r = a32 < 1;", "boolean", []int32{2365}},
+ {"relational f64 literal", "const r = fa64 < 1;", "boolean", []int32{2365}},
+ {"equality same type", "const r = a32 === b32;", "boolean", nil},
+ {"equality different types", "const r = a32 === a64;", "boolean", []int32{2367}},
+ {"array length", "const r = items.length - ua64;", "u64", nil},
+ {"compare with length", "const r = ua64 < items.length;", "boolean", nil},
+ {"logical and same type", "const r = a32 && b32;", "i32", nil},
+ {"logical or different types", "const r = a32 || a64;", "any", []int32{2365}},
+ {"logical and boolean left", "const r = c && a32;", "false | i32", nil},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ result := ssc_checkSource(t, tc.source)
+ if tc.resultType != "" {
+ assert.Equal(t, result.resultType, tc.resultType)
+ }
+ assert.DeepEqual(t, result.codes, tc.codes)
+ })
+ }
+}
+
+func TestSscRelations(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ source string
+ resultType string
+ codes []int32
+ }{
+ {"same type assignment", "const r: i32 = a32;", "i32", nil},
+ {"no widening", "const r: i64 = a32;", "i64", []int32{2322}},
+ {"no narrowing", "const r: i32 = a64;", "i32", []int32{2322}},
+ {"literal assignment", "const r: i32 = 1;", "i32", []int32{2322}},
+ {"literal to f64", "const r: f64 = 1.5;", "f64", []int32{2322}},
+ {"number assignment", "const r: i32 = n;", "i32", []int32{2322}},
+ {"number to f64", "const r: f64 = n;", "f64", []int32{2322}},
+ {"f64 to number", "const r: number = fa64;", "number", nil},
+ {"literal argument", "declare function take(v: i32): void;\ntake(1);", "", []int32{2345}},
+ {"literal return", "function f(): i32 { return 0; }", "", []int32{2322}},
+ {"literal array element", "const r: i32[] = [1];", "i32[]", []int32{2322}},
+ {"literal as assertion", "const r = 1 as i32;", "i32", nil},
+ {"number as assertion", "const r = n as i32;", "i32", nil},
+ {"ssc to number", "const r: number = a32;", "number", nil},
+ {"constructor", "declare function i32(v: number): i32;\nconst r: i32 = i32(1);", "i32", nil},
+ {"conditional keeps union", "const r = c ? a32 : a64;", "i32 | i64", nil},
+ {"index with u64", "const r = items[ua64];", "string", nil},
+ {"length", "const r = items.length;", "u64", nil},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ result := ssc_checkSource(t, tc.source)
+ if tc.resultType != "" {
+ assert.Equal(t, result.resultType, tc.resultType)
+ }
+ assert.DeepEqual(t, result.codes, tc.codes)
+ })
+ }
+}
+
+func TestSscPreludeIdentification(t *testing.T) {
+ t.Parallel()
+ const localAliases = `type i32 = number & {};
+type u32 = number & {};
+declare const p: i32;
+declare const q: u32;
+const r = p + q;
+export {};
+`
+ t.Run("same name aliases without prelude", func(t *testing.T) {
+ t.Parallel()
+ result := ssc_check(t, map[string]string{
+ "/node_modules/other/package.json": `{ "name": "other", "version": "0.0.0" }`,
+ "/node_modules/other/prelude.d.ts": ssc_prelude,
+ "/main.ts": localAliases,
+ }, []string{"node_modules/other/prelude.d.ts", "main.ts"})
+ assert.Equal(t, result.resultType, "number")
+ assert.DeepEqual(t, result.codes, []int32(nil))
+ })
+ t.Run("partial prelude disables ssc mode", func(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ source string
+ resultType string
+ codes []int32
+ }{
+ {"different types add as numbers", "declare const p: i32;\ndeclare const q: i64;\nconst r = p + q;", "number", nil},
+ {"unary plus", "declare const p: i32;\nconst r = +p;", "number", nil},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ result := ssc_check(t, map[string]string{
+ "/node_modules/syscript/package.json": `{ "name": "syscript", "version": "0.0.0" }`,
+ "/node_modules/syscript/prelude.d.ts": strings.Replace(ssc_prelude, " type f32 = number & { readonly [ssc]: 'f32' };\n", "", 1),
+ "/main.ts": tc.source + "\nexport {};\n",
+ }, []string{"node_modules/syscript/prelude.d.ts", "main.ts"})
+ assert.Equal(t, result.resultType, tc.resultType)
+ assert.DeepEqual(t, result.codes, tc.codes)
+ })
+ }
+ })
+ t.Run("prelude outside the syscript package", func(t *testing.T) {
+ t.Parallel()
+ result := ssc_check(t, map[string]string{
+ "/node_modules/other/package.json": `{ "name": "other", "version": "0.0.0" }`,
+ "/node_modules/other/prelude.d.ts": ssc_prelude,
+ "/main.ts": ssc_declarations + "const r = a64 + ua64;\nexport {};\n",
+ }, []string{"node_modules/other/prelude.d.ts", "main.ts"})
+ assert.Equal(t, result.resultType, "number")
+ assert.DeepEqual(t, result.codes, []int32(nil))
+ })
+ t.Run("value merged into a prelude type", func(t *testing.T) {
+ t.Parallel()
+ result := ssc_check(t, map[string]string{
+ "/user.d.ts": "declare function i32(): void;\n",
+ "/node_modules/syscript/package.json": `{ "name": "syscript", "version": "0.0.0" }`,
+ "/node_modules/syscript/prelude.d.ts": ssc_prelude,
+ "/main.ts": ssc_declarations + "const r = a32 + b32;\nexport {};\n",
+ }, []string{"user.d.ts", "node_modules/syscript/prelude.d.ts", "main.ts"})
+ assert.Equal(t, result.resultType, "i32")
+ assert.DeepEqual(t, result.codes, []int32(nil))
+ })
+}
+
+func TestSscBrand(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ source string
+ resultType string
+ codes []int32
+ }{
+ {"identity survives generic inference", "declare function id<T>(v: T): T;\nconst r = id(a32) + b32;", "i32", nil},
+ {"identity survives a user alias", "type MyInt = i32;\ndeclare const m: MyInt;\nconst r = m + a32;", "i32", nil},
+ {"different brands do not intersect", "declare const both: i32 & u8;\nconst r = both;", "never", nil},
+ {"the brand symbol is not visible outside the prelude", "declare const fake: number & { readonly [ssc]: 'i32' };\nconst r = 0;", "", []int32{2304}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ result := ssc_checkSource(t, tc.source)
+ if tc.resultType != "" {
+ assert.Equal(t, result.resultType, tc.resultType)
+ }
+ assert.DeepEqual(t, result.codes, tc.codes)
+ })
+ }
+}
+
+func TestSscChar(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ source string
+ resultType string
+ codes []int32
+ }{
+ {"comparison between chars", "const r = ch === ch2;", "boolean", nil},
+ {"ordering between chars", "const r = ch < ch2;", "boolean", nil},
+ {"conditional keeps char", "const r = c ? ch : ch2;", "char", nil},
+ {"arithmetic like an unsigned integer", "const r = ch + ch2;", "char", nil},
+ {"bitwise like an unsigned integer", "const r = ch & ch2;", "char", nil},
+ {"negation like an unsigned integer", "const r = -ch;", "any", []int32{2736}},
+ {"increment", "const r = ch++;", "char", nil},
+ {"no mixing with u32", "const r = ch + ua32;", "any", []int32{2365}},
+ {"string literal is not a char", "const r: char = 'A';", "char", []int32{2322}},
+ {"no widening to u32", "const r: u32 = ch;", "u32", []int32{2322}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ result := ssc_checkSource(t, tc.source)
+ if tc.resultType != "" {
+ assert.Equal(t, result.resultType, tc.resultType)
+ }
+ assert.DeepEqual(t, result.codes, tc.codes)
+ })
+ }
+}