@data-vegle/rbxts-go 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +181 -2
  3. package/README.rbxtsgo.md +169 -0
  4. package/THIRD_PARTY_NOTICES.md +745 -0
  5. package/cli/cli.go +454 -0
  6. package/compile/compile.go +388 -0
  7. package/compile/declarations.go +221 -0
  8. package/compile/incremental.go +349 -0
  9. package/compile/times.go +9 -0
  10. package/docs/plugin-api.md +239 -0
  11. package/go.mod +20 -0
  12. package/go.sum +24 -0
  13. package/internal/difftest/difftest.go +530 -0
  14. package/internal/plugintest/plugintest.go +181 -0
  15. package/luau/create.go +351 -0
  16. package/luau/doc.go +71 -0
  17. package/luau/globals.go +178 -0
  18. package/luau/jsnum.go +188 -0
  19. package/luau/kinds.go +128 -0
  20. package/luau/list.go +227 -0
  21. package/luau/nodes.go +479 -0
  22. package/luau/operators.go +46 -0
  23. package/luau/render.go +134 -0
  24. package/luau/render_expressions.go +264 -0
  25. package/luau/render_fields.go +81 -0
  26. package/luau/render_indexable.go +81 -0
  27. package/luau/render_state.go +134 -0
  28. package/luau/render_statements.go +235 -0
  29. package/luau/render_util.go +296 -0
  30. package/luau/solve_temp_ids.go +212 -0
  31. package/luau/typeguards.go +175 -0
  32. package/luau/util.go +184 -0
  33. package/luau/visit.go +138 -0
  34. package/npm/index.d.ts +3 -0
  35. package/npm/rbxts-go.sh +187 -0
  36. package/package.json +45 -5
  37. package/patches/typescript/0001-checker-exports.patch +40 -0
  38. package/patches/typescript/0002-iterable-arity.patch +15 -0
  39. package/patches/typescript/0003-context-sensitive-this.patch +15 -0
  40. package/patches/typescript/0004-printer-keep-parse-tree-parentheses.patch +26 -0
  41. package/pluginapi/host.go +31 -0
  42. package/pluginapi/pluginapi.go +153 -0
  43. package/plugins/LICENSE-rbxts-transformer-setget +18 -0
  44. package/plugins/apply.go +342 -0
  45. package/plugins/config.go +431 -0
  46. package/plugins/fallback.go +84 -0
  47. package/plugins/fixemit.go +60 -0
  48. package/plugins/native.go +262 -0
  49. package/plugins/session.go +223 -0
  50. package/plugins/setget.go +478 -0
  51. package/project/copy.go +333 -0
  52. package/project/include/Promise.lua +2068 -0
  53. package/project/include/RuntimeLib.lua +260 -0
  54. package/project/nodepath/nodepath.go +917 -0
  55. package/project/pathtranslator/pathtranslator.go +214 -0
  56. package/project/project.go +498 -0
  57. package/project/rojoresolver/json.go +248 -0
  58. package/project/rojoresolver/rojoresolver.go +559 -0
  59. package/project/shared/constants.go +83 -0
  60. package/project/shared/diagnostic.go +238 -0
  61. package/project/shared/diagnostics.go +388 -0
  62. package/project/shared/elapsed.go +14 -0
  63. package/project/shared/eol_other.go +6 -0
  64. package/project/shared/eol_windows.go +4 -0
  65. package/project/shared/kleur.go +40 -0
  66. package/project/shared/util.go +183 -0
  67. package/scripts/build-with-plugins.sh +130 -0
  68. package/scripts/setup-third-party.sh +75 -0
  69. package/transformer/add_index_diagnostics.go +21 -0
  70. package/transformer/add_one_if_array_type.go +15 -0
  71. package/transformer/array_binding_pattern_contains_hoists.go +25 -0
  72. package/transformer/assert_never.go +24 -0
  73. package/transformer/assignment.go +64 -0
  74. package/transformer/call_macros.go +70 -0
  75. package/transformer/check_variable_hoist.go +125 -0
  76. package/transformer/clean_module_name.go +28 -0
  77. package/transformer/constructor_macros.go +122 -0
  78. package/transformer/convert_to_indexable_expression.go +12 -0
  79. package/transformer/create_binary_from_operator.go +86 -0
  80. package/transformer/create_continue_statements.go +68 -0
  81. package/transformer/create_get_service.go +15 -0
  82. package/transformer/create_hoist_declaration.go +27 -0
  83. package/transformer/create_import_expression.go +220 -0
  84. package/transformer/create_string_from_literal.go +195 -0
  85. package/transformer/create_truthiness_checks.go +63 -0
  86. package/transformer/create_type_check.go +9 -0
  87. package/transformer/ensure_transform_order.go +53 -0
  88. package/transformer/expression_chain.go +27 -0
  89. package/transformer/expression_might_mutate.go +60 -0
  90. package/transformer/find_constructor.go +15 -0
  91. package/transformer/fixup_whitespace_and_decode_entities.go +377 -0
  92. package/transformer/get_accessor_for_binding_type.go +160 -0
  93. package/transformer/get_add_iterable_to_array_builder.go +363 -0
  94. package/transformer/get_assignable_value.go +15 -0
  95. package/transformer/get_constant_value_literal.go +20 -0
  96. package/transformer/get_declared_variables.go +34 -0
  97. package/transformer/get_extends_node.go +23 -0
  98. package/transformer/get_flags.go +21 -0
  99. package/transformer/get_kind_name.go +18 -0
  100. package/transformer/get_original_symbol_of_node.go +16 -0
  101. package/transformer/get_source_file_from_module_specifier.go +68 -0
  102. package/transformer/get_statements.go +12 -0
  103. package/transformer/has_multiple_definitions.go +18 -0
  104. package/transformer/hoist_functions_past_final_statement.go +43 -0
  105. package/transformer/identifier_macros.go +17 -0
  106. package/transformer/is_blocked_by_try_statement.go +19 -0
  107. package/transformer/is_method.go +104 -0
  108. package/transformer/is_symbol_mutable.go +26 -0
  109. package/transformer/is_symbol_of_value.go +11 -0
  110. package/transformer/is_used_as_statement.go +25 -0
  111. package/transformer/is_valid_method_index_without_call.go +36 -0
  112. package/transformer/macro_manager.go +92 -0
  113. package/transformer/object_accessor.go +32 -0
  114. package/transformer/offset.go +58 -0
  115. package/transformer/pointer.go +53 -0
  116. package/transformer/property_call_macros.go +1035 -0
  117. package/transformer/state.go +606 -0
  118. package/transformer/transform_array_assignment_pattern.go +65 -0
  119. package/transformer/transform_array_binding_pattern.go +49 -0
  120. package/transformer/transform_array_literal_expression.go +97 -0
  121. package/transformer/transform_await_expression.go +12 -0
  122. package/transformer/transform_binary_expression.go +221 -0
  123. package/transformer/transform_binding_name.go +25 -0
  124. package/transformer/transform_block.go +14 -0
  125. package/transformer/transform_boolean_literal.go +13 -0
  126. package/transformer/transform_break_statement.go +26 -0
  127. package/transformer/transform_call_expression.go +266 -0
  128. package/transformer/transform_class_constructor.go +125 -0
  129. package/transformer/transform_class_declaration.go +12 -0
  130. package/transformer/transform_class_expression.go +14 -0
  131. package/transformer/transform_class_like_declaration.go +355 -0
  132. package/transformer/transform_conditional_expression.go +70 -0
  133. package/transformer/transform_continue_statement.go +30 -0
  134. package/transformer/transform_decorators.go +253 -0
  135. package/transformer/transform_delete_expression.go +17 -0
  136. package/transformer/transform_do_statement.go +39 -0
  137. package/transformer/transform_element_access_expression.go +114 -0
  138. package/transformer/transform_entity_name.go +21 -0
  139. package/transformer/transform_enum_declaration.go +135 -0
  140. package/transformer/transform_export_assignment.go +57 -0
  141. package/transformer/transform_export_declaration.go +150 -0
  142. package/transformer/transform_expression.go +120 -0
  143. package/transformer/transform_expression_statement.go +71 -0
  144. package/transformer/transform_for_of_statement.go +461 -0
  145. package/transformer/transform_for_statement.go +599 -0
  146. package/transformer/transform_function_declaration.go +84 -0
  147. package/transformer/transform_function_expression.go +48 -0
  148. package/transformer/transform_identifier.go +194 -0
  149. package/transformer/transform_if_statement.go +44 -0
  150. package/transformer/transform_import_declaration.go +146 -0
  151. package/transformer/transform_import_equals_declaration.go +46 -0
  152. package/transformer/transform_import_expression.go +36 -0
  153. package/transformer/transform_initializer.go +22 -0
  154. package/transformer/transform_interpolated_string_part.go +12 -0
  155. package/transformer/transform_jsx.go +41 -0
  156. package/transformer/transform_jsx_attributes.go +110 -0
  157. package/transformer/transform_jsx_children.go +50 -0
  158. package/transformer/transform_jsx_element.go +14 -0
  159. package/transformer/transform_jsx_expression.go +20 -0
  160. package/transformer/transform_jsx_fragment.go +42 -0
  161. package/transformer/transform_jsx_self_closing_element.go +13 -0
  162. package/transformer/transform_jsx_tag_name.go +53 -0
  163. package/transformer/transform_logical.go +160 -0
  164. package/transformer/transform_logical_or_coalescing_assignment_expression.go +103 -0
  165. package/transformer/transform_method_declaration.go +102 -0
  166. package/transformer/transform_module_declaration.go +143 -0
  167. package/transformer/transform_new_expression.go +27 -0
  168. package/transformer/transform_no_substitution_template_literal.go +16 -0
  169. package/transformer/transform_numeric_literal.go +15 -0
  170. package/transformer/transform_object_assignment_pattern.go +86 -0
  171. package/transformer/transform_object_binding_pattern.go +49 -0
  172. package/transformer/transform_object_literal_expression.go +107 -0
  173. package/transformer/transform_omitted_expression.go +9 -0
  174. package/transformer/transform_optional_chain.go +312 -0
  175. package/transformer/transform_parameters.go +124 -0
  176. package/transformer/transform_parenthesized_expression.go +17 -0
  177. package/transformer/transform_property_access_expression.go +37 -0
  178. package/transformer/transform_property_declaration.go +33 -0
  179. package/transformer/transform_property_name.go +20 -0
  180. package/transformer/transform_return_statement.go +83 -0
  181. package/transformer/transform_source_file.go +230 -0
  182. package/transformer/transform_spread_element.go +35 -0
  183. package/transformer/transform_statement.go +84 -0
  184. package/transformer/transform_statement_list.go +90 -0
  185. package/transformer/transform_string_literal.go +22 -0
  186. package/transformer/transform_super_keyword.go +9 -0
  187. package/transformer/transform_switch_statement.go +145 -0
  188. package/transformer/transform_tagged_template_expression.go +34 -0
  189. package/transformer/transform_template_expression.go +35 -0
  190. package/transformer/transform_this_expression.go +33 -0
  191. package/transformer/transform_throw_statement.go +18 -0
  192. package/transformer/transform_try_statement.go +192 -0
  193. package/transformer/transform_type_expression.go +12 -0
  194. package/transformer/transform_unary_expression.go +79 -0
  195. package/transformer/transform_variable_statement.go +178 -0
  196. package/transformer/transform_void_expression.go +13 -0
  197. package/transformer/transform_while_statement.go +34 -0
  198. package/transformer/transform_writable.go +69 -0
  199. package/transformer/transform_yield_expression.go +56 -0
  200. package/transformer/type_guards.go +30 -0
  201. package/transformer/types.go +381 -0
  202. package/transformer/validate_identifier.go +17 -0
  203. package/transformer/validate_method_assignment.go +106 -0
  204. package/transformer/validate_not_any.go +37 -0
  205. package/transformer/wrap_expression_statement.go +20 -0
  206. package/transformer/wrap_return_if_lua_tuple.go +63 -0
  207. package/transformer/wrap_statements_as_generator.go +22 -0
  208. package/tsbridge/affected.go +141 -0
  209. package/tsbridge/config.go +71 -0
  210. package/tsbridge/diagnostics.go +128 -0
  211. package/tsbridge/doc.go +16 -0
  212. package/tsbridge/macros.go +207 -0
  213. package/tsbridge/macrospec.go +30 -0
  214. package/tsbridge/pool.go +142 -0
  215. package/tsbridge/project.go +137 -0
  216. package/tsbridge/reprint.go +99 -0
  217. package/tsbridge/update.go +128 -0
  218. package/watch/poll.go +126 -0
  219. package/watch/session.go +651 -0
  220. package/watch/watch.go +180 -0
@@ -0,0 +1,141 @@
1
+ package tsbridge
2
+
3
+ import (
4
+ "slices"
5
+ "sync"
6
+
7
+ "github.com/microsoft/TypeScript/tsc/internal/ast"
8
+ "github.com/microsoft/TypeScript/tsc/internal/tspath"
9
+ )
10
+
11
+ // Change says what a stage that reads a whole program has to redo, given the program it last ran on.
12
+ type Change struct {
13
+ // Full says that anything can have changed. Affected is nil then.
14
+ Full bool
15
+ // Reason says why, for --verbose.
16
+ Reason string
17
+ // Changed counts the files that are different objects in the two programs.
18
+ Changed int
19
+ // Affected holds the changed files and everything that reaches them through imports.
20
+ Affected map[tspath.PathKey]bool
21
+ }
22
+
23
+ // Reaches says whether the file has to be redone.
24
+ func (c *Change) Reaches(file *ast.SourceFile) bool { return c.Full || c.Affected[file.PathKey()] }
25
+
26
+ // AffectedFiles compares two programs on the same options. A stage's answer for a file can only depend on that file and
27
+ // on what the checker sees from it. The checker sees what the file imports, transitively, plus the global scope. So:
28
+ //
29
+ // - A file is affected if it reaches a changed file through imports, including `import type`, `import("...")` types,
30
+ // module augmentation names and `/// <reference path>`.
31
+ // - Anything that adds to the global scope, or to another module without being imported, reaches every file. That's a
32
+ // declaration file, a file that isn't a module, and any file with `declare global`, `declare module`, or an ambient
33
+ // module. The old version counts too, because removing one of those matters as much as adding it.
34
+ // - So does any change in which files exist, or in where an unchanged file's imports go.
35
+ //
36
+ // Parsed files are shared between programs while they're unchanged, so comparing pointers finds the changes. A file that
37
+ // got parsed again with the same text counts as changed, which only costs time.
38
+ func AffectedFiles(previous, next *Project) *Change {
39
+ if previous == nil {
40
+ return &Change{Full: true, Reason: "no earlier program"}
41
+ }
42
+ if previous.program == next.program {
43
+ return &Change{Affected: map[tspath.PathKey]bool{}}
44
+ }
45
+ before, after := previous.program.FilesByPath(), next.program.FilesByPath()
46
+ if len(before) != len(after) {
47
+ return &Change{Full: true, Reason: "files added or removed"}
48
+ }
49
+ var changed []tspath.PathKey
50
+ for path, file := range after {
51
+ old, ok := before[path]
52
+ if !ok {
53
+ return &Change{Full: true, Reason: "files added or removed"}
54
+ }
55
+ if old != file {
56
+ if HasGlobalEffects(old) || HasGlobalEffects(file) {
57
+ return &Change{Full: true, Reason: file.FileName().AsString() + " can affect the global scope"}
58
+ }
59
+ changed = append(changed, path)
60
+ }
61
+ }
62
+ importsBefore, importsAfter := previous.ImportGraph(), next.ImportGraph()
63
+ for path, targets := range importsAfter {
64
+ if before[path] == after[path] && !slices.Equal(targets, importsBefore[path]) {
65
+ return &Change{Full: true, Reason: after[path].FileName().AsString() + " resolves its imports differently"}
66
+ }
67
+ }
68
+
69
+ return &Change{Changed: len(changed), Affected: next.Closure(changed)}
70
+ }
71
+
72
+ // Closure gives the files and everything that reaches them through imports.
73
+ func (p *Project) Closure(changed []tspath.PathKey) map[tspath.PathKey]bool {
74
+ graph := p.ImportGraph()
75
+ importers := make(map[tspath.PathKey][]tspath.PathKey, len(graph))
76
+ for path, targets := range graph {
77
+ for _, target := range targets {
78
+ importers[target] = append(importers[target], path)
79
+ }
80
+ }
81
+ affected := make(map[tspath.PathKey]bool, len(changed))
82
+ queue := slices.Clone(changed)
83
+ for len(queue) > 0 {
84
+ path := queue[len(queue)-1]
85
+ queue = queue[:len(queue)-1]
86
+ if affected[path] {
87
+ continue
88
+ }
89
+ affected[path] = true
90
+ queue = append(queue, importers[path]...)
91
+ }
92
+ return affected
93
+ }
94
+
95
+ // HasGlobalEffects says a change to this file can reach files that don't import it.
96
+ func HasGlobalEffects(file *ast.SourceFile) bool {
97
+ if ast.IsJsonSourceFile(file) {
98
+ return false
99
+ }
100
+ return file.IsDeclarationFile ||
101
+ !ast.IsExternalOrCommonJSModule(file) ||
102
+ len(file.ModuleAugmentations) > 0 ||
103
+ len(file.AmbientModuleNames) > 0
104
+ }
105
+
106
+ // ImportGraph lists, per file, the program files it reaches directly, sorted. It's worked out once per project.
107
+ func (p *Project) ImportGraph() map[tspath.PathKey][]tspath.PathKey {
108
+ p.graphOnce.Do(func() {
109
+ program := p.program
110
+ files := program.FilesByPath()
111
+ graph := make(map[tspath.PathKey][]tspath.PathKey, len(files))
112
+ resolved := program.GetResolvedModules()
113
+ for path, file := range files {
114
+ var targets []tspath.PathKey
115
+ for _, module := range resolved[path] {
116
+ if module == nil || !module.IsResolved() {
117
+ continue
118
+ }
119
+ if target := program.GetSourceFileForResolvedModule(module); target != nil {
120
+ targets = append(targets, target.PathKey())
121
+ }
122
+ }
123
+ for _, reference := range file.ReferencedFiles {
124
+ name := tspath.ToRootedFilePath(reference.FileName, file.FileName().Directory())
125
+ if target := program.GetSourceFileByPath(program.CaseSensitivity().PathKey(name.AsPath())); target != nil {
126
+ targets = append(targets, target.PathKey())
127
+ }
128
+ }
129
+ slices.Sort(targets)
130
+ graph[path] = slices.Compact(targets)
131
+ }
132
+ p.graph = graph
133
+ })
134
+ return p.graph
135
+ }
136
+
137
+ // graphState is embedded in Project.
138
+ type graphState struct {
139
+ graphOnce sync.Once
140
+ graph map[tspath.PathKey][]tspath.PathKey
141
+ }
@@ -0,0 +1,71 @@
1
+ package tsbridge
2
+
3
+ import (
4
+ "fmt"
5
+
6
+ "github.com/microsoft/TypeScript/tsc/internal/collections"
7
+ "github.com/microsoft/TypeScript/tsc/internal/core"
8
+ )
9
+
10
+ // NormalizeOptions returns a copy of opts with the options TS 7 removed rewritten, so users don't have
11
+ // to edit a tsconfig that works with rbxtsc. It must run after parsing and before compiler.NewProgram,
12
+ // whose verifyCompilerOptions reports TS5102 and TS5108 for the old options. Notes describe each change,
13
+ // for verbose output. Running it twice changes nothing the second time.
14
+ //
15
+ // A classic module option is left alone. commonjs stays, see 0003 item 4.
16
+ func NormalizeOptions(in *core.CompilerOptions) (*core.CompilerOptions, []string) {
17
+ opts := in.Clone()
18
+ var notes []string
19
+
20
+ // A config written for TS 7 compiles as the classic pair, so one set of programs is accepted and the Luau is the same.
21
+ // Left as written, a package's "exports" would change import paths, and top-level await would compile. See 0007.
22
+ if opts.Module == core.ModuleKindPreserve && opts.ModuleResolution == core.ModuleResolutionKindBundler {
23
+ opts.Module = core.ModuleKindCommonJS
24
+ opts.ModuleResolution = core.ModuleResolutionKindNode10
25
+ notes = append(notes, "module preserve and moduleResolution bundler -> the classic commonjs and node10")
26
+ }
27
+ if opts.BaseUrl != "" {
28
+ paths := collections.NewOrderedMapWithSizeHint[string, []string](1)
29
+ if opts.Paths != nil {
30
+ for key, value := range opts.Paths.Entries() {
31
+ paths.Set(key, value)
32
+ }
33
+ }
34
+ if !paths.Has("*") {
35
+ paths.Set("*", []string{"./*"})
36
+ }
37
+ opts.Paths = paths
38
+ // Before TS 7, paths were relative to baseUrl when it was set.
39
+ opts.PathsBasePath = opts.BaseUrl
40
+ notes = append(notes, fmt.Sprintf(`baseUrl %q -> paths {"*": ["./*"]} based there`, opts.BaseUrl))
41
+ opts.BaseUrl = ""
42
+ }
43
+ if opts.ModuleResolution == core.ModuleResolutionKindNode10 {
44
+ opts.ModuleResolution = core.ModuleResolutionKindBundler
45
+ notes = append(notes, "moduleResolution node10 -> bundler")
46
+ // node10 ignores these package.json fields, so deep imports only resolve the same way with them off.
47
+ if opts.ResolvePackageJsonExports.IsUnknown() {
48
+ opts.ResolvePackageJsonExports = core.TSFalse
49
+ notes = append(notes, "resolvePackageJsonExports unset -> false")
50
+ }
51
+ if opts.ResolvePackageJsonImports.IsUnknown() {
52
+ opts.ResolvePackageJsonImports = core.TSFalse
53
+ notes = append(notes, "resolvePackageJsonImports unset -> false")
54
+ }
55
+ }
56
+ if !opts.DownlevelIteration.IsUnknown() {
57
+ opts.DownlevelIteration = core.TSUnknown
58
+ notes = append(notes, "downlevelIteration dropped")
59
+ }
60
+ if opts.Types == nil {
61
+ // TS 5 included every package under typeRoots by default. TS 7 includes none.
62
+ opts.Types = []string{"*"}
63
+ notes = append(notes, `types unset -> ["*"]`)
64
+ }
65
+ // Not removed, but the default changed in TS 6, which adds TS2882 errors that rbxtsc doesn't report.
66
+ if opts.NoUncheckedSideEffectImports.IsUnknown() {
67
+ opts.NoUncheckedSideEffectImports = core.TSFalse
68
+ notes = append(notes, "noUncheckedSideEffectImports unset -> false")
69
+ }
70
+ return opts, notes
71
+ }
@@ -0,0 +1,128 @@
1
+ package tsbridge
2
+
3
+ import (
4
+ "context"
5
+ "slices"
6
+ "sync"
7
+
8
+ "github.com/microsoft/TypeScript/tsc/internal/ast"
9
+ "github.com/microsoft/TypeScript/tsc/internal/compiler"
10
+ "github.com/microsoft/TypeScript/tsc/internal/core"
11
+ "github.com/microsoft/TypeScript/tsc/internal/diagnostics"
12
+ )
13
+
14
+ // PreEmitDiagnostics mirrors ts.getPreEmitDiagnostics(program, sourceFile), which is what compileFiles.ts
15
+ // calls per source file: config, options, this file's syntax, globals, this file's semantics, and declaration
16
+ // diagnostics when declaration emit is on. Program.GetSemanticDiagnostics applies @ts-ignore and
17
+ // @ts-expect-error, and includes bind diagnostics. Package .d.ts files are not checked unless passed in.
18
+ func (p *Project) PreEmitDiagnostics(ctx context.Context, file *ast.SourceFile) []*ast.Diagnostic {
19
+ p.waitPrecheck()
20
+ p.assertNotInWorkerPhase()
21
+ // Check first, because the global diagnostics of a checker can grow during checking.
22
+ p.program.GetSemanticDiagnostics(ctx, file)
23
+ return p.preEmitDiagnostics(ctx, file, p.programWideDiagnostics(ctx))
24
+ }
25
+
26
+ // PreEmitDiagnosticsForFiles returns PreEmitDiagnostics for each file, checking in parallel with one goroutine
27
+ // per checker. Results are per input file, so program-wide diagnostics repeat for each file, as they do when
28
+ // compileFiles.ts collects them file by file. Concatenating in input order gives the same list as rbxtsc.
29
+ func (p *Project) PreEmitDiagnosticsForFiles(ctx context.Context, files []*ast.SourceFile) [][]*ast.Diagnostic {
30
+ p.waitPrecheck()
31
+ p.assertNotInWorkerPhase()
32
+ p.checkFiles(ctx, files)
33
+ global := p.programWideDiagnostics(ctx)
34
+ results := make([][]*ast.Diagnostic, len(files))
35
+ for i, file := range files {
36
+ results[i] = p.preEmitDiagnostics(ctx, file, global)
37
+ }
38
+ return results
39
+ }
40
+
41
+ // checkFiles type-checks files with one goroutine per checker, and waits. It only forces the check: the results stay
42
+ // in the checkers' caches, where GetSemanticDiagnostics finds them again.
43
+ func (p *Project) checkFiles(ctx context.Context, files []*ast.SourceFile) {
44
+ var wg sync.WaitGroup
45
+ for _, group := range p.groupByChecker(ctx, files) {
46
+ wg.Add(1)
47
+ go func() {
48
+ defer wg.Done()
49
+ for _, file := range group.files {
50
+ p.program.GetSemanticDiagnostics(ctx, file)
51
+ }
52
+ }()
53
+ }
54
+ wg.Wait()
55
+ }
56
+
57
+ // Precheck starts type-checking files in the background and returns at once. Checking is the longest phase of a
58
+ // build and needs nothing from the phases before it (cleaning the output folder, copying files, reading the Rojo
59
+ // project), so a build can run those in the meantime. Every method that uses a checker waits for the precheck first,
60
+ // so the rules in the package comment hold: nothing else touches a checker while it runs. The diagnostics come
61
+ // from PreEmitDiagnosticsForFiles as usual, which then finds every file already checked.
62
+ //
63
+ // Call it at most once per Project, before any other method that uses a checker.
64
+ func (p *Project) Precheck(ctx context.Context, files []*ast.SourceFile) {
65
+ if p.precheck != nil {
66
+ return
67
+ }
68
+ done := make(chan struct{})
69
+ p.precheck = done
70
+ go func() {
71
+ defer close(done)
72
+ // A panic in the checker must not take the process down from a background goroutine. It is raised again, with
73
+ // its real stack, when the build reaches the same file in PreEmitDiagnosticsForFiles.
74
+ defer func() { _ = recover() }()
75
+ p.checkFiles(ctx, files)
76
+ }()
77
+ }
78
+
79
+ // waitPrecheck blocks until a precheck that was started has finished.
80
+ func (p *Project) waitPrecheck() {
81
+ if p.precheck != nil {
82
+ <-p.precheck
83
+ }
84
+ }
85
+
86
+ // programWideDiagnostics returns the parts that don't depend on the file.
87
+ func (p *Project) programWideDiagnostics(ctx context.Context) []*ast.Diagnostic {
88
+ return slices.Concat(
89
+ p.program.GetConfigFileParsingDiagnostics(),
90
+ p.program.GetProgramDiagnostics(),
91
+ p.program.GetGlobalDiagnostics(ctx),
92
+ )
93
+ }
94
+
95
+ func (p *Project) preEmitDiagnostics(ctx context.Context, file *ast.SourceFile, global []*ast.Diagnostic) []*ast.Diagnostic {
96
+ all := slices.Concat(global, p.program.GetSyntacticDiagnostics(ctx, file), p.program.GetSemanticDiagnostics(ctx, file))
97
+ if p.Options().GetEmitDeclarations() {
98
+ all = append(all, p.program.GetDeclarationDiagnostics(ctx, file)...)
99
+ }
100
+ return compiler.SortAndDeduplicateDiagnostics(FilterDiagnostics(all, p.Options()))
101
+ }
102
+
103
+ // FilterDiagnostics removes diagnostics that TS 7 reports and rbxtsc doesn't.
104
+ //
105
+ // TS2441 on `Object` is new in TS 7 and means nothing for Luau output. TS2441 on `exports` and `require`
106
+ // stays: TS 5.5.3 reports those under CommonJS as well, so rbxtsc rejects them.
107
+ //
108
+ // With rootDirs and no rootDir, TS 6 and later add TS5011 and TS6059, because they default rootDir to the
109
+ // tsconfig's folder. roblox-ts accepts rootDirs on its own, and TS 5.5.3 reports neither. See 0004.
110
+ func FilterDiagnostics(all []*ast.Diagnostic, options *core.CompilerOptions) []*ast.Diagnostic {
111
+ return slices.DeleteFunc(slices.Clone(all), func(d *ast.Diagnostic) bool {
112
+ switch d.Code() {
113
+ case diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module.Code():
114
+ args := d.MessageArgs()
115
+ return len(args) > 0 && args[0] == "Object"
116
+ case diagnostics.The_common_source_directory_of_0_is_1_The_rootDir_setting_must_be_explicitly_set_to_this_or_another_path_to_adjust_your_output_s_file_layout.Code(),
117
+ diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files.Code():
118
+ return options.RootDir == ""
119
+ }
120
+ return false
121
+ })
122
+ }
123
+
124
+ func (p *Project) assertNotInWorkerPhase() {
125
+ if p.workersRunning.Load() {
126
+ panic("tsbridge: diagnostics must not run while workers are running, because workers hold no checker lock")
127
+ }
128
+ }
@@ -0,0 +1,16 @@
1
+ // Package tsbridge is the one place the port touches TypeScript 7 internals where traps exist:
2
+ // program creation, config normalization, diagnostics and checker access.
3
+ //
4
+ // The rules it enforces are explained in docs/bridge.md:
5
+ //
6
+ // - One worker per checker. A checker is only ever used by the worker that owns it.
7
+ // - Types and symbols never cross checkers. Each worker has its own macro symbol table.
8
+ // - An emit resolver only comes from Worker.CheckFileAndGetResolver, which checks the file first.
9
+ // - Diagnostics run as a separate phase, before the workers start. The phases must not overlap.
10
+ // - The native plugin pass is the one exception to "one worker per checker": it uses the first checker for every
11
+ // file, on one goroutine, through Project.PluginChecker. Nothing else may use that project's checkers while it
12
+ // runs, and in a build with native plugins nothing else ever does.
13
+ //
14
+ // Code outside this package must not call Program.GetTypeCheckerForFileExclusive,
15
+ // Program.ForEachCheckerParallel or Checker.NewEmitResolver. TestNoTrapCallsOutsideBridge enforces it.
16
+ package tsbridge
@@ -0,0 +1,207 @@
1
+ package tsbridge
2
+
3
+ import (
4
+ "errors"
5
+
6
+ "github.com/microsoft/TypeScript/tsc/internal/ast"
7
+ "github.com/microsoft/TypeScript/tsc/internal/checker"
8
+ )
9
+
10
+ const typesNotice = "\nYou may need to update your @rbxts/compiler-types!"
11
+
12
+ // NominalLuaTupleName is NOMINAL_LUA_TUPLE_NAME in MacroManager.ts.
13
+ const NominalLuaTupleName = "_nominal_LuaTuple"
14
+
15
+ // SymbolNames is the values of SYMBOL_NAMES in MacroManager.ts at roblox-ts 3.0.0, in source order.
16
+ var SymbolNames = []string{
17
+ "globalThis",
18
+ "ArrayConstructor", "SetConstructor", "MapConstructor", "WeakSetConstructor", "WeakMapConstructor",
19
+ "ReadonlyMapConstructor", "ReadonlySetConstructor",
20
+ "Array", "Generator", "IterableFunction", "LuaTuple", "Map", "Object", "ReadonlyArray", "ReadonlyMap",
21
+ "ReadonlySet", "ReadVoxelsArray", "Set", "String", "TemplateStringsArray", "WeakMap", "WeakSet",
22
+ "Iterable",
23
+ "$range", "$tuple",
24
+ }
25
+
26
+ var macroOnlyClasses = map[string]bool{
27
+ "ReadonlyArray": true, "Array": true, "ReadonlyMap": true, "WeakMap": true, "Map": true,
28
+ "ReadonlySet": true, "WeakSet": true, "Set": true, "String": true,
29
+ }
30
+
31
+ // PropertyMacroClass is one entry of PROPERTY_CALL_MACROS: a class and its macro method names.
32
+ type PropertyMacroClass struct {
33
+ Class string
34
+ Methods []string
35
+ }
36
+
37
+ // MacroSpec names the macros to look up. The macro bodies belong to the transformer, so this only has names,
38
+ // and lookups below return the name. The order is the upstream Object.entries order, which decides which
39
+ // error is reported first when compiler-types is out of date.
40
+ type MacroSpec struct {
41
+ Identifiers []string
42
+ Calls []string
43
+ Constructors []string
44
+ PropertyCalls []PropertyMacroClass
45
+ }
46
+
47
+ // MacroSymbols is the symbol side of MacroManager.ts for one checker. It maps symbols to macro names.
48
+ //
49
+ // Never share one across checkers. Globals declared in several files are cloned per checker, so a table from
50
+ // another checker gives wrong answers with no error, and only once a project adds an augmentation such as
51
+ // `declare global { interface Array<T> }`. See 0002.
52
+ type MacroSymbols struct {
53
+ checker *checker.Checker
54
+ symbols map[string]*ast.Symbol
55
+ identifiers map[*ast.Symbol]string
56
+ calls map[*ast.Symbol]string
57
+ constructor map[*ast.Symbol]string
58
+ property map[*ast.Symbol]string
59
+ // methodOrder is the order in which MacroManager's constructor first asks for the type of each method of a macro
60
+ // class. In TS 5.5.3 that's the order of those types' ids, because nothing else has run yet.
61
+ methodOrder map[*ast.Symbol]int
62
+ }
63
+
64
+ // NewMacroSymbols ports the MacroManager constructor. Errors have the upstream ProjectError text.
65
+ func NewMacroSymbols(c *checker.Checker, spec MacroSpec) (*MacroSymbols, error) {
66
+ m := &MacroSymbols{
67
+ checker: c,
68
+ symbols: map[string]*ast.Symbol{},
69
+ identifiers: map[*ast.Symbol]string{},
70
+ calls: map[*ast.Symbol]string{},
71
+ constructor: map[*ast.Symbol]string{},
72
+ property: map[*ast.Symbol]string{},
73
+ methodOrder: map[*ast.Symbol]int{},
74
+ }
75
+ global := func(name string, meaning ast.SymbolFlags) (*ast.Symbol, error) {
76
+ if symbol := c.ResolveName(name, nil, meaning, false); symbol != nil {
77
+ return symbol, nil
78
+ }
79
+ return nil, errors.New("MacroManager could not find symbol for " + name + typesNotice)
80
+ }
81
+ for _, name := range spec.Identifiers {
82
+ symbol, err := global(name, ast.SymbolFlagsVariable)
83
+ if err != nil {
84
+ return nil, err
85
+ }
86
+ m.identifiers[symbol] = name
87
+ }
88
+ for _, name := range spec.Calls {
89
+ symbol, err := global(name, ast.SymbolFlagsFunction)
90
+ if err != nil {
91
+ return nil, err
92
+ }
93
+ m.calls[symbol] = name
94
+ }
95
+ for _, name := range spec.Constructors {
96
+ symbol, err := global(name, ast.SymbolFlagsInterface)
97
+ if err != nil {
98
+ return nil, err
99
+ }
100
+ construct, err := firstConstructSymbol(symbol, name)
101
+ if err != nil {
102
+ return nil, err
103
+ }
104
+ m.constructor[construct] = name
105
+ }
106
+ for _, class := range spec.PropertyCalls {
107
+ symbol, err := global(class.Class, ast.SymbolFlagsInterface)
108
+ if err != nil {
109
+ return nil, err
110
+ }
111
+ methods := map[string]*ast.Symbol{}
112
+ for _, decl := range symbol.Declarations() {
113
+ if !ast.IsInterfaceDeclaration(decl) {
114
+ continue
115
+ }
116
+ for _, member := range decl.AsInterfaceDeclaration().Members.Nodes {
117
+ if ast.IsMethodSignatureDeclaration(member) && ast.IsIdentifier(member.Name()) {
118
+ methodSymbol := c.GetTypeAtLocation(member).Symbol()
119
+ if methodSymbol == nil {
120
+ panic("tsbridge: method signature " + member.Name().Text() + " has no type symbol")
121
+ }
122
+ methods[member.Name().Text()] = methodSymbol
123
+ if _, seen := m.methodOrder[methodSymbol]; !seen {
124
+ m.methodOrder[methodSymbol] = len(m.methodOrder)
125
+ }
126
+ }
127
+ }
128
+ }
129
+ for _, method := range class.Methods {
130
+ methodSymbol := methods[method]
131
+ if methodSymbol == nil {
132
+ return nil, errors.New("MacroManager could not find method for " + class.Class + "." + method + typesNotice)
133
+ }
134
+ m.property[methodSymbol] = class.Class + "." + method
135
+ }
136
+ }
137
+ for _, name := range SymbolNames {
138
+ symbol, err := global(name, ast.SymbolFlagsAll)
139
+ if err != nil {
140
+ return nil, err
141
+ }
142
+ m.symbols[name] = symbol
143
+ }
144
+ for _, decl := range m.symbols["LuaTuple"].Declarations() {
145
+ if ast.IsTypeAliasDeclaration(decl) {
146
+ if symbol := c.GetPropertyOfType(c.GetTypeAtLocation(decl), NominalLuaTupleName); symbol != nil {
147
+ m.symbols[NominalLuaTupleName] = symbol
148
+ }
149
+ break
150
+ }
151
+ }
152
+ return m, nil
153
+ }
154
+
155
+ func firstConstructSymbol(symbol *ast.Symbol, name string) (*ast.Symbol, error) {
156
+ for _, decl := range symbol.Declarations() {
157
+ if !ast.IsInterfaceDeclaration(decl) {
158
+ continue
159
+ }
160
+ // getFirstDeclarationOrThrow takes the first interface declaration only.
161
+ for _, member := range decl.AsInterfaceDeclaration().Members.Nodes {
162
+ if ast.IsConstructSignatureDeclaration(member) {
163
+ return member.Symbol(), nil
164
+ }
165
+ }
166
+ return nil, errors.New("MacroManager could not find constructor for " + name + typesNotice)
167
+ }
168
+ return nil, errors.New("")
169
+ }
170
+
171
+ // Checker returns the checker this table belongs to.
172
+ func (m *MacroSymbols) Checker() *checker.Checker { return m.checker }
173
+
174
+ // Symbol returns the named global, or nil. Upstream's getSymbolOrThrow asserts on nil.
175
+ func (m *MacroSymbols) Symbol(name string) *ast.Symbol { return m.symbols[name] }
176
+
177
+ // MethodCreationOrder returns where a method of a macro class falls in TS 5.5.3's type id order, and false for any
178
+ // other symbol.
179
+ func (m *MacroSymbols) MethodCreationOrder(symbol *ast.Symbol) (int, bool) {
180
+ order, ok := m.methodOrder[symbol]
181
+ return order, ok
182
+ }
183
+
184
+ // IsMacroOnlyClass is MacroManager.isMacroOnlyClass.
185
+ func (m *MacroSymbols) IsMacroOnlyClass(symbol *ast.Symbol) bool {
186
+ return m.symbols[symbol.Name()] == symbol && macroOnlyClasses[symbol.Name()]
187
+ }
188
+
189
+ // IdentifierMacro returns the macro name for symbol, or "" if it has none.
190
+ func (m *MacroSymbols) IdentifierMacro(symbol *ast.Symbol) string { return m.identifiers[symbol] }
191
+
192
+ // CallMacro returns the macro name for symbol, or "" if it has none.
193
+ func (m *MacroSymbols) CallMacro(symbol *ast.Symbol) string { return m.calls[symbol] }
194
+
195
+ // ConstructorMacro returns the macro name for symbol, or "" if it has none.
196
+ func (m *MacroSymbols) ConstructorMacro(symbol *ast.Symbol) string { return m.constructor[symbol] }
197
+
198
+ // PropertyCallMacro returns the macro name as "Class.method" for symbol, or "" if it has none.
199
+ // Upstream's assert on an unimplemented macro-only method is left to the caller, which has the macro bodies.
200
+ func (m *MacroSymbols) PropertyCallMacro(symbol *ast.Symbol) string { return m.property[symbol] }
201
+
202
+ // IsUnimplementedMacroMethod is the condition upstream's getPropertyCallMacro asserts on: no macro for this
203
+ // method, but its class is macro-only.
204
+ func (m *MacroSymbols) IsUnimplementedMacroMethod(symbol *ast.Symbol) bool {
205
+ parent := symbol.Parent()
206
+ return m.property[symbol] == "" && parent != nil && m.symbols[parent.Name()] == parent && m.IsMacroOnlyClass(parent)
207
+ }
@@ -0,0 +1,30 @@
1
+ package tsbridge
2
+
3
+ // DefaultMacroSpec returns the macro names of roblox-ts 3.0.0, read from the keys of IDENTIFIER_MACROS,
4
+ // CALL_MACROS, CONSTRUCTOR_MACROS and PROPERTY_CALL_MACROS in the built package, in Object.entries order.
5
+ func DefaultMacroSpec() MacroSpec {
6
+ return MacroSpec{
7
+ Identifiers: []string{"Promise"},
8
+ Calls: []string{"assert", "typeOf", "typeIs", "classIs", "identity", "$range", "$tuple", "$getModuleTree"},
9
+ Constructors: []string{"ArrayConstructor", "SetConstructor", "MapConstructor", "WeakSetConstructor", "WeakMapConstructor", "ReadonlyMapConstructor", "ReadonlySetConstructor"},
10
+ PropertyCalls: []PropertyMacroClass{
11
+ {Class: "CFrame", Methods: []string{"add", "sub", "mul"}},
12
+ {Class: "UDim", Methods: []string{"add", "sub"}},
13
+ {Class: "UDim2", Methods: []string{"add", "sub"}},
14
+ {Class: "Vector2", Methods: []string{"add", "sub", "mul", "div", "idiv"}},
15
+ {Class: "Vector2int16", Methods: []string{"add", "sub", "mul", "div"}},
16
+ {Class: "Vector3", Methods: []string{"add", "sub", "mul", "div", "idiv"}},
17
+ {Class: "Vector3int16", Methods: []string{"add", "sub", "mul", "div"}},
18
+ {Class: "Number", Methods: []string{"idiv"}},
19
+ {Class: "String", Methods: []string{"size", "byte", "find", "format", "gmatch", "gsub", "lower", "match", "rep", "reverse", "split", "sub", "upper"}},
20
+ {Class: "ArrayLike", Methods: []string{"size"}},
21
+ {Class: "ReadonlyArray", Methods: []string{"isEmpty", "join", "move", "includes", "indexOf", "every", "some", "forEach", "map", "mapFiltered", "filterUndefined", "filter", "reduce", "find", "findIndex"}},
22
+ {Class: "Array", Methods: []string{"push", "pop", "shift", "unshift", "insert", "remove", "unorderedRemove", "sort", "clear"}},
23
+ {Class: "ReadonlySet", Methods: []string{"isEmpty", "size", "has", "forEach"}},
24
+ {Class: "Set", Methods: []string{"delete", "clear", "add"}},
25
+ {Class: "ReadonlyMap", Methods: []string{"isEmpty", "size", "has", "forEach", "get"}},
26
+ {Class: "Map", Methods: []string{"delete", "clear", "set"}},
27
+ {Class: "Promise", Methods: []string{"then"}},
28
+ },
29
+ }
30
+ }