@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,606 @@
1
+ // Package transformer is the port of src/TSTransformer from roblox-ts 3.0.0. This file is
2
+ // classes/TransformState.ts, classes/MultiTransformState.ts, util/traversal.ts and util/valueToIdStr.ts.
3
+ // See docs/bridge.md for the rules on checker access.
4
+ package transformer
5
+
6
+ import (
7
+ "cmp"
8
+ "context"
9
+ "slices"
10
+ "strings"
11
+
12
+ "github.com/microsoft/TypeScript/tsc/internal/ast"
13
+ "github.com/microsoft/TypeScript/tsc/internal/checker"
14
+ "github.com/microsoft/TypeScript/tsc/internal/compiler"
15
+ "github.com/microsoft/TypeScript/tsc/internal/core"
16
+ "github.com/microsoft/TypeScript/tsc/internal/scanner"
17
+ "github.com/microsoft/TypeScript/tsc/internal/tspath"
18
+ "github.com/microsoft/TypeScript/tsc/rbxtsgo/luau"
19
+ "github.com/microsoft/TypeScript/tsc/rbxtsgo/project"
20
+ "github.com/microsoft/TypeScript/tsc/rbxtsgo/project/nodepath"
21
+ "github.com/microsoft/TypeScript/tsc/rbxtsgo/project/pathtranslator"
22
+ "github.com/microsoft/TypeScript/tsc/rbxtsgo/project/rojoresolver"
23
+ "github.com/microsoft/TypeScript/tsc/rbxtsgo/project/shared"
24
+ "github.com/microsoft/TypeScript/tsc/rbxtsgo/tsbridge"
25
+ )
26
+
27
+ func init() {
28
+ // Globals and Strings are shared by every worker.
29
+ luau.PinShared()
30
+ }
31
+
32
+ // MultiTransformState is state that lives for one compile step, for one worker. Upstream has one per compile.
33
+ // It's keyed by symbols, so here each worker has its own, because symbols can't cross checkers.
34
+ //
35
+ // isReportedByNoAnyCache and isReportedByMultipleDefinitionsCache make a diagnostic report once per symbol. With
36
+ // several workers, a symbol is reported once per checker that reaches it, so the same error can appear more than
37
+ // once. Sort and deduplicate the combined diagnostics at the end of a compile.
38
+ type MultiTransformState struct {
39
+ IsMethodCache map[*ast.Symbol]bool
40
+ IsDefinedAsLetCache map[*ast.Symbol]bool
41
+ IsReportedByNoAnyCache map[*ast.Symbol]bool
42
+ IsReportedByMultipleDefinitionsCache map[*ast.Symbol]bool
43
+ GetModuleExportsCache map[*ast.Symbol][]*ast.Symbol
44
+ GetModuleExportsAliasMapCache map[*ast.Symbol]map[*ast.Symbol]string
45
+
46
+ // IsRobloxTypesFileCache and robloxTypesPath are not upstream's: see isRobloxTypesFile.
47
+ IsRobloxTypesFileCache map[*ast.SourceFile]bool
48
+ robloxTypesPath string
49
+ }
50
+
51
+ // NewMultiTransformState makes the state for one worker.
52
+ func NewMultiTransformState() *MultiTransformState {
53
+ return &MultiTransformState{
54
+ IsMethodCache: map[*ast.Symbol]bool{},
55
+ IsDefinedAsLetCache: map[*ast.Symbol]bool{},
56
+ IsReportedByNoAnyCache: map[*ast.Symbol]bool{},
57
+ IsReportedByMultipleDefinitionsCache: map[*ast.Symbol]bool{},
58
+ GetModuleExportsCache: map[*ast.Symbol][]*ast.Symbol{},
59
+ GetModuleExportsAliasMapCache: map[*ast.Symbol]map[*ast.Symbol]string{},
60
+ IsRobloxTypesFileCache: map[*ast.SourceFile]bool{},
61
+ }
62
+ }
63
+
64
+ // TransformServices is the interface of the same name. The macro table is this worker's own.
65
+ type TransformServices struct {
66
+ MacroManager *tsbridge.MacroSymbols
67
+ }
68
+
69
+ // TryUses is the interface of the same name.
70
+ type TryUses struct {
71
+ UsesReturn bool
72
+ UsesBreak bool
73
+ UsesContinue bool
74
+ }
75
+
76
+ // StateOptions is the part of TransformState's constructor arguments that one compile shares across workers.
77
+ // None of it is keyed by types or symbols. CompileContext comes from project.PrepareCompile.
78
+ type StateOptions struct {
79
+ Program *compiler.Program
80
+ Data *shared.ProjectData
81
+ PathTranslator *pathtranslator.Translator
82
+ Compile *project.CompileContext
83
+ Options *core.CompilerOptions
84
+ }
85
+
86
+ // TransformState represents the state of the transformation between TS and the Luau AST, for one source file.
87
+ //
88
+ // Upstream's constructor takes the type checker and calls typeChecker.getEmitResolver(sourceFile). Here it takes a
89
+ // worker, and the resolver can only come from Worker.CheckFileAndGetResolver.
90
+ type TransformState struct {
91
+ StateOptions
92
+
93
+ Worker *tsbridge.Worker
94
+ Checker *checker.Checker
95
+ Resolver *checker.EmitResolver
96
+ Services *TransformServices
97
+ Multi *MultiTransformState
98
+ Diagnostic *shared.DiagnosticService
99
+ SourceFile *ast.SourceFile
100
+
101
+ sourceFileText string
102
+ isInReplicatedFirst bool
103
+
104
+ HasExportEquals bool
105
+ HasExportFrom bool
106
+ UsesRuntimeLib bool
107
+
108
+ ClassIdentifierMap map[*ast.Node]luau.AnyIdentifier
109
+
110
+ TryUsesStack []*TryUses
111
+ PrereqStatementsStack []*luau.List
112
+
113
+ // With fixEmit. See createContinueStatements and hoistFunctionsPastFinalStatement.
114
+ switchContinueFlags map[*ast.Node]*luau.TemporaryIdentifier
115
+ hoistedPastFinal map[*ast.Node]bool
116
+
117
+ HoistsByStatement map[*ast.Node][]*ast.Node
118
+ IsHoisted map[*ast.Symbol]bool
119
+ SymbolToIDMap map[*ast.Symbol]*luau.TemporaryIdentifier
120
+
121
+ // CaseSensitivity is what upstream's getCanonicalFileName decides.
122
+ CaseSensitivity tspath.CaseSensitivity
123
+
124
+ getTypeCache map[*ast.Node]*checker.Type
125
+ moduleIDBySymbol map[*ast.Symbol]luau.AnyIdentifier
126
+ classElementToObjectKeyMap map[*ast.Node]luau.Expression
127
+ }
128
+
129
+ // NewTransformState is the constructor. The worker must own file. Multi, services and the diagnostic service
130
+ // belong to the worker. Output paths go through this platform's path rules, as in upstream.
131
+ func NewTransformState(ctx context.Context, worker *tsbridge.Worker, options StateOptions, services *TransformServices, multi *MultiTransformState, diagnostic *shared.DiagnosticService, file *ast.SourceFile) *TransformState {
132
+ state := &TransformState{
133
+ StateOptions: options,
134
+ Worker: worker,
135
+ Checker: worker.Checker(),
136
+ Resolver: worker.CheckFileAndGetResolver(ctx, file),
137
+ Services: services,
138
+ Multi: multi,
139
+ Diagnostic: diagnostic,
140
+ SourceFile: file,
141
+ sourceFileText: file.Text(),
142
+ CaseSensitivity: options.Program.CaseSensitivity(),
143
+ ClassIdentifierMap: map[*ast.Node]luau.AnyIdentifier{},
144
+ HoistsByStatement: map[*ast.Node][]*ast.Node{},
145
+ IsHoisted: map[*ast.Symbol]bool{},
146
+ SymbolToIDMap: map[*ast.Symbol]*luau.TemporaryIdentifier{},
147
+ getTypeCache: map[*ast.Node]*checker.Type{},
148
+ moduleIDBySymbol: map[*ast.Symbol]luau.AnyIdentifier{},
149
+ classElementToObjectKeyMap: map[*ast.Node]luau.Expression{},
150
+ }
151
+ sourceOutPath := options.PathTranslator.GetOutputPath(nodepath.Native.Normalize(file.FileName().AsString()))
152
+ rbxPath := options.Compile.RojoResolver.GetRbxPathFromFilePath(sourceOutPath)
153
+ state.isInReplicatedFirst = len(rbxPath) > 0 && rbxPath[0] == "ReplicatedFirst"
154
+ return state
155
+ }
156
+
157
+ // RojoResolver is state.rojoResolver.
158
+ func (s *TransformState) RojoResolver() *rojoresolver.Resolver { return s.Compile.RojoResolver }
159
+
160
+ // PushTryUsesStack pushes tryUses information onto the stack and returns it.
161
+ func (s *TransformState) PushTryUsesStack() *TryUses {
162
+ uses := &TryUses{}
163
+ s.TryUsesStack = append(s.TryUsesStack, uses)
164
+ return uses
165
+ }
166
+
167
+ // MarkTryUses marks the current try statement as exiting with return, break or continue. Pass a function that sets
168
+ // the field: mark(func(u *TryUses) { u.UsesReturn = true }).
169
+ func (s *TransformState) MarkTryUses(mark func(*TryUses)) {
170
+ if len(s.TryUsesStack) != 0 {
171
+ mark(s.TryUsesStack[len(s.TryUsesStack)-1])
172
+ }
173
+ }
174
+
175
+ // PopTryUsesStack pops tryUses information from the stack.
176
+ func (s *TransformState) PopTryUsesStack() {
177
+ s.TryUsesStack = s.TryUsesStack[:len(s.TryUsesStack)-1]
178
+ }
179
+
180
+ // Prereq pushes a prerequisite statement onto the current list.
181
+ func (s *TransformState) Prereq(statement luau.Statement) {
182
+ s.PrereqStatementsStack[len(s.PrereqStatementsStack)-1].Push(statement)
183
+ }
184
+
185
+ // PrereqList pushes a list of prerequisite statements onto the current list.
186
+ func (s *TransformState) PrereqList(statements *luau.List) {
187
+ s.PrereqStatementsStack[len(s.PrereqStatementsStack)-1].PushList(statements)
188
+ }
189
+
190
+ // PushPrereqStatementsStack makes and pushes a new prerequisite list.
191
+ func (s *TransformState) PushPrereqStatementsStack() *luau.List {
192
+ statements := luau.NewList()
193
+ s.PrereqStatementsStack = append(s.PrereqStatementsStack, statements)
194
+ return statements
195
+ }
196
+
197
+ // PopPrereqStatementsStack pops and returns the top prerequisite list.
198
+ func (s *TransformState) PopPrereqStatementsStack() *luau.List {
199
+ last := len(s.PrereqStatementsStack) - 1
200
+ if last < 0 {
201
+ panic(shared.AssertionMessage(""))
202
+ }
203
+ popped := s.PrereqStatementsStack[last]
204
+ s.PrereqStatementsStack = s.PrereqStatementsStack[:last]
205
+ return popped
206
+ }
207
+
208
+ // GetLeadingComments returns a node's leading comments as Luau comments. Offsets are bytes into the UTF-8 text.
209
+ func (s *TransformState) GetLeadingComments(node *ast.Node) *luau.List {
210
+ comments := luau.NewList()
211
+ var factory ast.NodeFactory
212
+ for commentRange := range scanner.GetLeadingCommentRanges(&factory, s.sourceFileText, node.Pos()) {
213
+ end := commentRange.End()
214
+ if commentRange.Kind != ast.KindSingleLineCommentTrivia {
215
+ end -= 2
216
+ }
217
+ comments.Push(luau.NewComment(s.sourceFileText[commentRange.Pos()+2 : end]))
218
+ }
219
+ return comments
220
+ }
221
+
222
+ // CapturePrereqs returns the prerequisite statements that callback makes.
223
+ func (s *TransformState) CapturePrereqs(callback func()) *luau.List {
224
+ s.PushPrereqStatementsStack()
225
+ callback()
226
+ return s.PopPrereqStatementsStack()
227
+ }
228
+
229
+ // Capture returns the result and the prerequisite statements that callback makes.
230
+ func Capture[T any](s *TransformState, callback func() T) (T, *luau.List) {
231
+ var value T
232
+ prereqs := s.CapturePrereqs(func() { value = callback() })
233
+ return value, prereqs
234
+ }
235
+
236
+ // NoPrereqs runs callback and asserts that it made no prerequisite statements.
237
+ func (s *TransformState) NoPrereqs(callback func() luau.Expression) luau.Expression {
238
+ expression, statements := Capture(s, callback)
239
+ if !statements.IsEmpty() {
240
+ panic(shared.AssertionMessage(""))
241
+ }
242
+ return expression
243
+ }
244
+
245
+ // GetType is state.getType: the type at a node, skipping up through wrappers such as parentheses, with a cache.
246
+ func (s *TransformState) GetType(node *ast.Node) *checker.Type {
247
+ if t, ok := s.getTypeCache[node]; ok {
248
+ return t
249
+ }
250
+ t := s.Checker.GetTypeAtLocation(SkipUpwards(node))
251
+ s.getTypeCache[node] = t
252
+ return t
253
+ }
254
+
255
+ // TS is state.TS: a property of the runtime library, which it also marks as used.
256
+ func (s *TransformState) TS(node *ast.Node, name string) *luau.PropertyAccessExpression {
257
+ s.UsesRuntimeLib = true
258
+ if s.Compile.ProjectType == shared.ProjectTypeGame && s.isInReplicatedFirst {
259
+ s.Diagnostic.AddDiagnostic(shared.Warnings.RuntimeLibUsedInReplicatedFirst.At(shared.AtNode(node)))
260
+ }
261
+ return luau.NewProperty(Global(luau.Globals.TS), name)
262
+ }
263
+
264
+ // Global returns a private copy of a luau.Globals node for use from a worker. Globals are shared and mutable: the
265
+ // first Create that takes one adopts it, which races between workers. See luau/doc.go. A copy renders the same.
266
+ func Global[T luau.Node](node T) T {
267
+ return luau.ShallowClone(node).(T)
268
+ }
269
+
270
+ // PushToVar declares a new Luau variable and pushes expression to it. expression can be nil, to declare without a
271
+ // value. name can be "", to get one from the expression.
272
+ func (s *TransformState) PushToVar(expression luau.Expression, name string) *luau.TemporaryIdentifier {
273
+ if name == "" && expression != nil {
274
+ name = valueToIDStr(expression)
275
+ }
276
+ temp := luau.NewTempID(name)
277
+ declaration := &luau.VariableDeclaration{Left: temp}
278
+ if expression != nil {
279
+ declaration.Right = expression
280
+ }
281
+ s.Prereq(luau.Create(declaration))
282
+ return temp
283
+ }
284
+
285
+ // PushToVarIfComplex uses PushToVar unless the expression is simple.
286
+ func (s *TransformState) PushToVarIfComplex(expression luau.Expression, name string) luau.Expression {
287
+ if luau.IsSimple(expression) {
288
+ return expression
289
+ }
290
+ return s.PushToVar(expression, name)
291
+ }
292
+
293
+ // PushToVarIfNonID uses PushToVar unless the expression is an identifier.
294
+ func (s *TransformState) PushToVarIfNonID(expression luau.Expression, name string) luau.AnyIdentifier {
295
+ if luau.IsAnyIdentifier(expression) {
296
+ return expression.(luau.AnyIdentifier)
297
+ }
298
+ return s.PushToVar(expression, name)
299
+ }
300
+
301
+ // GetModuleExports is state.getModuleExports.
302
+ func (s *TransformState) GetModuleExports(moduleSymbol *ast.Symbol) []*ast.Symbol {
303
+ if exports, ok := s.Multi.GetModuleExportsCache[moduleSymbol]; ok {
304
+ return exports
305
+ }
306
+ exports := sortExportsInBindOrder(moduleSymbol, s.Checker.GetExportsOfModule(moduleSymbol))
307
+ s.Multi.GetModuleExportsCache[moduleSymbol] = exports
308
+ return exports
309
+ }
310
+
311
+ // GetModuleExportsAliasMap is state.getModuleExportsAliasMap.
312
+ func (s *TransformState) GetModuleExportsAliasMap(moduleSymbol *ast.Symbol) map[*ast.Symbol]string {
313
+ if aliasMap, ok := s.Multi.GetModuleExportsAliasMapCache[moduleSymbol]; ok {
314
+ return aliasMap
315
+ }
316
+ aliasMap := map[*ast.Symbol]string{}
317
+ for _, exportSymbol := range s.GetModuleExports(moduleSymbol) {
318
+ originalSymbol := s.Checker.SkipAlias(exportSymbol)
319
+ declarations := exportSymbol.Declarations()
320
+ if len(declarations) > 0 && ast.IsExportSpecifier(declarations[0]) {
321
+ aliasMap[originalSymbol] = declarations[0].Name().Text()
322
+ } else {
323
+ aliasMap[originalSymbol] = exportSymbol.Name()
324
+ }
325
+ }
326
+ s.Multi.GetModuleExportsAliasMapCache[moduleSymbol] = aliasMap
327
+ return aliasMap
328
+ }
329
+
330
+ func (s *TransformState) getModuleSymbolFromNode(node *ast.Node) *ast.Symbol {
331
+ moduleAncestor := GetModuleAncestor(node)
332
+ location := moduleAncestor
333
+ if !ast.IsSourceFile(moduleAncestor) {
334
+ location = moduleAncestor.Name()
335
+ }
336
+ exportSymbol := s.Checker.GetSymbolAtLocation(location)
337
+ if exportSymbol == nil {
338
+ panic(shared.AssertionMessage(""))
339
+ }
340
+ return exportSymbol
341
+ }
342
+
343
+ func (s *TransformState) getModuleIDFromSymbol(moduleSymbol *ast.Symbol) luau.AnyIdentifier {
344
+ moduleID, ok := s.moduleIDBySymbol[moduleSymbol]
345
+ if !ok {
346
+ panic(shared.AssertionMessage(""))
347
+ }
348
+ return moduleID
349
+ }
350
+
351
+ // SetModuleIDBySymbol is state.setModuleIdBySymbol.
352
+ func (s *TransformState) SetModuleIDBySymbol(moduleSymbol *ast.Symbol, moduleID luau.AnyIdentifier) {
353
+ s.moduleIDBySymbol[moduleSymbol] = moduleID
354
+ }
355
+
356
+ // GetModuleIDFromNode is state.getModuleIdFromNode.
357
+ func (s *TransformState) GetModuleIDFromNode(node *ast.Node) luau.AnyIdentifier {
358
+ return s.getModuleIDFromSymbol(s.getModuleSymbolFromNode(node))
359
+ }
360
+
361
+ // GetModuleIDPropertyAccess is state.getModuleIdPropertyAccess. It returns nil where JS returns undefined.
362
+ func (s *TransformState) GetModuleIDPropertyAccess(idSymbol *ast.Symbol) *luau.PropertyAccessExpression {
363
+ if declaration := idSymbol.ValueDeclaration(); declaration != nil {
364
+ moduleSymbol := s.getModuleSymbolFromNode(declaration)
365
+ if alias := s.GetModuleExportsAliasMap(moduleSymbol)[idSymbol]; alias != "" {
366
+ return luau.NewProperty(s.getModuleIDFromSymbol(moduleSymbol), alias)
367
+ }
368
+ }
369
+ return nil
370
+ }
371
+
372
+ // SetClassElementObjectKey stores the key in `obj[key] = value` for a class element, so it can be used later.
373
+ func (s *TransformState) SetClassElementObjectKey(classElement *ast.Node, key luau.Expression) {
374
+ if _, exists := s.classElementToObjectKeyMap[classElement]; exists {
375
+ panic(shared.AssertionMessage(""))
376
+ }
377
+ s.classElementToObjectKeyMap[classElement] = key
378
+ }
379
+
380
+ // GetClassElementObjectKey is state.getClassElementObjectKey. It returns nil where JS returns undefined.
381
+ func (s *TransformState) GetClassElementObjectKey(classElement *ast.Node) luau.Expression {
382
+ return s.classElementToObjectKeyMap[classElement]
383
+ }
384
+
385
+ func isWrapperExpression(node *ast.Node) bool {
386
+ return ast.IsNonNullExpression(node) || ast.IsParenthesizedExpression(node) || ast.IsAsExpression(node) ||
387
+ ast.IsTypeAssertion(node) || ast.IsSatisfiesExpression(node)
388
+ }
389
+
390
+ // isAncestorOf is isAncestorOf in util/traversal.ts.
391
+ func isAncestorOf(ancestor *ast.Node, node *ast.Node) bool {
392
+ for node != nil {
393
+ if ancestor == node {
394
+ return true
395
+ }
396
+ node = node.Parent
397
+ }
398
+ return false
399
+ }
400
+
401
+ // SkipDownwards is skipDownwards in util/traversal.ts.
402
+ func SkipDownwards(node *ast.Node) *ast.Node {
403
+ for isWrapperExpression(node) {
404
+ node = node.Expression()
405
+ }
406
+ return node
407
+ }
408
+
409
+ // SkipUpwards is skipUpwards in util/traversal.ts.
410
+ func SkipUpwards(node *ast.Node) *ast.Node {
411
+ parent := node.Parent
412
+ for parent != nil && isWrapperExpression(parent) {
413
+ node = parent
414
+ parent = node.Parent
415
+ }
416
+ return node
417
+ }
418
+
419
+ // GetAncestor is getAncestor in util/traversal.ts. It returns nil where JS returns undefined.
420
+ func GetAncestor(node *ast.Node, check func(*ast.Node) bool) *ast.Node {
421
+ current := node
422
+ for current != nil && !check(current) {
423
+ current = current.Parent
424
+ }
425
+ return current
426
+ }
427
+
428
+ // GetModuleAncestor is getModuleAncestor in util/traversal.ts.
429
+ func GetModuleAncestor(node *ast.Node) *ast.Node {
430
+ return GetAncestor(node, func(n *ast.Node) bool { return ast.IsSourceFile(n) || ast.IsModuleDeclaration(n) })
431
+ }
432
+
433
+ // valueToIDStr is valueToIdStr in util/valueToIdStr.ts.
434
+ func valueToIDStr(value luau.Expression) string {
435
+ valueStr, ok := expressionToStr(value)
436
+ if ok && luau.IsValidIdentifier(valueStr) {
437
+ return uncapitalizeFirstLetter(valueStr)
438
+ }
439
+ return ""
440
+ }
441
+
442
+ func expressionToStr(expression luau.Node) (string, bool) {
443
+ switch v := expression.(type) {
444
+ case *luau.Identifier:
445
+ return v.Name, true // X -> "X"
446
+ case *luau.PropertyAccessExpression:
447
+ return v.Name, true // A.B -> "B"
448
+ case *luau.CallExpression:
449
+ // X.new() -> "X"
450
+ if property, ok := v.Expression.(*luau.PropertyAccessExpression); ok && property.Name == "new" {
451
+ return expressionToStr(property.Expression)
452
+ }
453
+ }
454
+ return "", false
455
+ }
456
+
457
+ func uncapitalizeFirstLetter(str string) string {
458
+ if str == "" {
459
+ return str
460
+ }
461
+ return strings.ToLower(str[:1]) + str[1:]
462
+ }
463
+
464
+ // sortExportsInBindOrder puts a module's exports in the order JS has them. TS 5.5.3 keeps symbol tables in insertion
465
+ // order, which is the order the binder declares them: function declarations of a statement list first, then the rest
466
+ // in source order, and exports that came through `export *` after the module's own. TS 7's symbol tables are Go maps,
467
+ // so GetExportsOfModule returns a different order on every call. The order reaches output in handleExports, and it
468
+ // decides which alias wins in getModuleExportsAliasMap. moduleSymbol's own declarations tell its own exports from the
469
+ // others. The order among `export *` symbols is only made stable, not matched to JS, because handleExports ignores them.
470
+ func sortExportsInBindOrder(moduleSymbol *ast.Symbol, exports []*ast.Symbol) []*ast.Symbol {
471
+ type key struct {
472
+ star bool
473
+ file string
474
+ notFunction bool
475
+ pos int
476
+ name string
477
+ }
478
+ moduleFiles := map[string]bool{}
479
+ for _, declaration := range moduleSymbol.Declarations() {
480
+ moduleFiles[ast.GetSourceFileOfNode(declaration).FileName().AsString()] = true
481
+ }
482
+ keys := make(map[*ast.Symbol]key, len(exports))
483
+ for _, symbol := range exports {
484
+ k := key{notFunction: true, pos: int(^uint(0) >> 1), name: symbol.Name()}
485
+ found := false
486
+ for _, declaration := range symbol.Declarations() {
487
+ isFunction := ast.IsFunctionDeclaration(declaration) && declaration.Parent != nil &&
488
+ (ast.IsSourceFile(declaration.Parent) || ast.IsModuleBlock(declaration.Parent))
489
+ if !found || (isFunction && k.notFunction) || (isFunction == !k.notFunction && declaration.Pos() < k.pos) {
490
+ found = true
491
+ k.file = ast.GetSourceFileOfNode(declaration).FileName().AsString()
492
+ k.notFunction = !isFunction
493
+ k.pos = declaration.Pos()
494
+ }
495
+ }
496
+ k.star = found && !moduleFiles[k.file]
497
+ keys[symbol] = k
498
+ }
499
+ sorted := slices.Clone(exports)
500
+ slices.SortStableFunc(sorted, func(a, b *ast.Symbol) int {
501
+ ka, kb := keys[a], keys[b]
502
+ if ka.star != kb.star {
503
+ if ka.star {
504
+ return 1
505
+ }
506
+ return -1
507
+ }
508
+ return cmp.Or(
509
+ cmp.Compare(ka.file, kb.file),
510
+ cmp.Compare(boolInt(ka.notFunction), boolInt(kb.notFunction)),
511
+ cmp.Compare(ka.pos, kb.pos),
512
+ cmp.Compare(ka.name, kb.name),
513
+ )
514
+ })
515
+ return sorted
516
+ }
517
+
518
+ func boolInt(value bool) int {
519
+ if value {
520
+ return 1
521
+ }
522
+ return 0
523
+ }
524
+
525
+ // CreateRuntimeLibImport is createRuntimeLibImport. It returns `local TS = ...`.
526
+ func (s *TransformState) CreateRuntimeLibImport(sourceFile *ast.SourceFile) luau.Statement {
527
+ runtimeLibRbxPath := s.Compile.RuntimeLibRbxPath
528
+ if runtimeLibRbxPath != nil {
529
+ if s.Compile.ProjectType == shared.ProjectTypeGame {
530
+ // create an expression to obtain the service where RuntimeLib is stored
531
+ if len(runtimeLibRbxPath) == 0 {
532
+ panic(shared.AssertionMessage(""))
533
+ }
534
+ var expression luau.IndexableExpression = createGetService(runtimeLibRbxPath[0])
535
+ // iterate through the rest of the path
536
+ // for each instance in the path, create a new WaitForChild call to be added on to the end of the final expression
537
+ for _, name := range runtimeLibRbxPath[1:] {
538
+ expression = luau.Create(&luau.MethodCallExpression{
539
+ Expression: expression,
540
+ Name: "WaitForChild",
541
+ Args: luau.MakeList[luau.Node](luau.NewString(name)),
542
+ })
543
+ }
544
+ // nest the chain of `WaitForChild`s inside a require call
545
+ expression = luau.NewCall(luau.Globals.Require, expression)
546
+ // create a variable declaration for this call
547
+ return luau.Create(&luau.VariableDeclaration{Left: luau.Globals.TS, Right: expression})
548
+ }
549
+ sourceOutPath := s.PathTranslator.GetOutputPath(nodepath.Native.Normalize(sourceFile.FileName().AsString()))
550
+ rbxPath := s.RojoResolver().GetRbxPathFromFilePath(sourceOutPath)
551
+ if rbxPath == nil {
552
+ s.Diagnostic.AddDiagnostic(shared.Errors.NoRojoData.At(shared.AtNode(sourceFile.AsNode()), nodepath.Native.Relative(s.Data.ProjectPath, sourceOutPath), false))
553
+ return luau.Create(&luau.VariableDeclaration{Left: luau.Globals.TS, Right: luau.NewNone()})
554
+ }
555
+ path := rojoresolver.Relative(rbxPath, runtimeLibRbxPath)
556
+ names := make([]string, len(path))
557
+ for i, name := range path {
558
+ if name == rojoresolver.RbxPathParent {
559
+ name = shared.ParentField
560
+ }
561
+ names[i] = name
562
+ }
563
+ return luau.Create(&luau.VariableDeclaration{
564
+ Left: luau.Globals.TS,
565
+ Right: luau.NewCall(luau.Globals.Require, propertyAccessExpressionChain(luau.Globals.Script, names)),
566
+ })
567
+ }
568
+ // we pass RuntimeLib access to packages via `_G[script] = TS`
569
+ // access it here via `local TS = _G[script]`
570
+ return luau.Create(&luau.VariableDeclaration{
571
+ Left: luau.Globals.TS,
572
+ Right: luau.Create(&luau.ComputedIndexExpression{
573
+ Expression: luau.Globals.G,
574
+ Index: luau.Globals.Script,
575
+ }),
576
+ })
577
+ }
578
+
579
+ // GuessVirtualPath is guessVirtualPath: it attempts to reverse a symlink lookup. It returns "" where JS returns
580
+ // undefined. The program's symlink cache holds the same data as TS 5.5.3's getSymlinkCache.
581
+ func (s *TransformState) GuessVirtualPath(fsPath string) string {
582
+ reverseSymlinkMap := s.Program.GetSymlinkCache().DirectoriesByRealpath()
583
+ original := fsPath
584
+ for {
585
+ // reverseSymlinkMap always has trailing slashes, as it is constructed from `SymlinkedDirectory.real`
586
+ parent := tspath.EnsureTrailingDirectorySeparator(nodepath.Native.Dirname(fsPath))
587
+ if fsPath == parent {
588
+ return ""
589
+ }
590
+ fsPath = parent
591
+ key := s.CaseSensitivity.PathKey(tspath.ToRootedPath(fsPath, s.Program.GetCurrentDirectory()))
592
+ if symlinks, ok := reverseSymlinkMap.Load(key); ok {
593
+ // TS keeps these in an array and takes the first. Here they're a set, so take the smallest for a fixed answer.
594
+ first := ""
595
+ symlinks.Range(func(symlink tspath.RootedDirectoryPath) bool {
596
+ if text := symlink.AsString(); first == "" || text < first {
597
+ first = text
598
+ }
599
+ return true
600
+ })
601
+ if first != "" {
602
+ return nodepath.Native.Join(first, nodepath.Native.Relative(fsPath, original))
603
+ }
604
+ }
605
+ }
606
+ }
@@ -0,0 +1,65 @@
1
+ package transformer
2
+
3
+ // Port of src/TSTransformer/nodes/binding/transformArrayAssignmentPattern.ts.
4
+
5
+ import (
6
+ "github.com/microsoft/TypeScript/tsc/internal/ast"
7
+ "github.com/microsoft/TypeScript/tsc/rbxtsgo/luau"
8
+ "github.com/microsoft/TypeScript/tsc/rbxtsgo/project/shared"
9
+ )
10
+
11
+ func transformArrayAssignmentPattern(state *TransformState, assignmentPattern *ast.Node, parentID luau.AnyIdentifier) {
12
+ index := 0
13
+ idStack := []luau.AnyIdentifier{}
14
+ accessor := getAccessorForBindingType(
15
+ state,
16
+ assignmentPattern,
17
+ state.Checker.GetTypeOfAssignmentPattern(assignmentPattern),
18
+ )
19
+ for _, element := range assignmentPattern.AsArrayLiteralExpression().Elements.Nodes {
20
+ if ast.IsOmittedExpression(element) {
21
+ accessor(state, parentID, index, &idStack, true)
22
+ } else if ast.IsSpreadElement(element) {
23
+ state.Diagnostic.AddDiagnostic(shared.Errors.NoSpreadDestructuring.At(shared.AtNode(element)))
24
+ } else {
25
+ var initializer *ast.Node
26
+ // JS 3.0.0 crashes on [(a)] = b. From upstream's master, in transformAssignmentPatternElement.
27
+ element = SkipDownwards(element)
28
+ if ast.IsBinaryExpression(element) {
29
+ binary := element.AsBinaryExpression()
30
+ initializer = SkipDownwards(binary.Right)
31
+ element = SkipDownwards(binary.Left)
32
+ }
33
+
34
+ value := accessor(state, parentID, index, &idStack, false)
35
+ if ast.IsIdentifier(element) ||
36
+ ast.IsElementAccessExpression(element) ||
37
+ ast.IsPropertyAccessExpression(element) {
38
+ id := transformWritableExpression(state, element, initializer != nil)
39
+ state.Prereq(luau.Create(&luau.Assignment{
40
+ Left: id,
41
+ Operator: luau.AssignEqual,
42
+ Right: value,
43
+ }))
44
+ if initializer != nil {
45
+ state.Prereq(transformInitializer(state, id, initializer))
46
+ }
47
+ } else if ast.IsArrayLiteralExpression(element) {
48
+ id := state.PushToVar(value, "binding")
49
+ if initializer != nil {
50
+ state.Prereq(transformInitializer(state, id, initializer))
51
+ }
52
+ transformArrayAssignmentPattern(state, element, id)
53
+ } else if ast.IsObjectLiteralExpression(element) {
54
+ id := state.PushToVar(value, "binding")
55
+ if initializer != nil {
56
+ state.Prereq(transformInitializer(state, id, initializer))
57
+ }
58
+ transformObjectAssignmentPattern(state, element, id)
59
+ } else {
60
+ panic(shared.AssertionMessage("transformArrayAssignmentPattern invalid element: " + getKindName(element.Kind)))
61
+ }
62
+ }
63
+ index++
64
+ }
65
+ }