goscript 0.0.21 → 0.0.23
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.
- package/cmd/goscript/cmd_compile.go +2 -2
- package/compiler/analysis.go +229 -51
- package/compiler/assignment.go +412 -0
- package/compiler/compiler.go +185 -5885
- package/compiler/compiler_test.go +40 -8
- package/compiler/composite-lit.go +552 -0
- package/compiler/config.go +3 -0
- package/compiler/decl.go +259 -0
- package/compiler/expr-call.go +479 -0
- package/compiler/expr-selector.go +125 -0
- package/compiler/expr-star.go +90 -0
- package/compiler/expr-type.go +309 -0
- package/compiler/expr-value.go +89 -0
- package/compiler/expr.go +591 -0
- package/compiler/field.go +169 -0
- package/compiler/lit.go +131 -0
- package/compiler/primitive.go +148 -0
- package/compiler/{write-type-spec.go → spec-struct.go} +211 -204
- package/compiler/spec-value.go +226 -0
- package/compiler/spec.go +272 -0
- package/compiler/stmt-assign.go +439 -0
- package/compiler/stmt-for.go +178 -0
- package/compiler/stmt-range.go +235 -0
- package/compiler/stmt-select.go +211 -0
- package/compiler/stmt-type-switch.go +147 -0
- package/compiler/stmt.go +792 -0
- package/compiler/type-assert.go +209 -0
- package/compiler/type-info.go +141 -0
- package/compiler/type.go +618 -0
- package/go.mod +2 -1
- package/go.sum +4 -2
- package/package.json +6 -6
- package/builtin/builtin.go +0 -11
- package/builtin/builtin.ts +0 -2114
- package/dist/builtin/builtin.d.ts +0 -495
- package/dist/builtin/builtin.js +0 -1490
- package/dist/builtin/builtin.js.map +0 -1
- /package/compiler/{writer.go → code-writer.go} +0 -0
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
package compiler
|
|
2
|
+
|
|
3
|
+
import (
|
|
4
|
+
"fmt"
|
|
5
|
+
"go/ast"
|
|
6
|
+
"go/types"
|
|
7
|
+
|
|
8
|
+
"github.com/pkg/errors"
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
// WriteStmtRange translates a Go `for...range` statement (`ast.RangeStmt`)
|
|
12
|
+
// into an equivalent TypeScript loop. The translation depends on the type of
|
|
13
|
+
// the expression being ranged over (`exp.X`), determined using `go/types` info.
|
|
14
|
+
//
|
|
15
|
+
// - **Maps (`*types.Map`):**
|
|
16
|
+
// `for k, v := range myMap` becomes `for (const [k_ts, v_ts] of myMap_ts.entries()) { const k = k_ts; const v = v_ts; ...body... }`.
|
|
17
|
+
// If only `k` or `v` (or neither) is used, the corresponding TypeScript const declaration is adjusted.
|
|
18
|
+
//
|
|
19
|
+
// - **Strings (`*types.Basic` with `IsString` info):**
|
|
20
|
+
// `for i, r := range myString` becomes:
|
|
21
|
+
// `const _runes = $.stringToRunes(myString_ts);`
|
|
22
|
+
// `for (let i_ts = 0; i_ts < _runes.length; i_ts++) { const r_ts = _runes[i_ts]; ...body... }`.
|
|
23
|
+
// The index variable `i_ts` uses the Go key variable name if provided (and not `_`).
|
|
24
|
+
// The rune variable `r_ts` uses the Go value variable name.
|
|
25
|
+
//
|
|
26
|
+
// - **Integers (`*types.Basic` with `IsInteger` info, Go 1.22+):**
|
|
27
|
+
// `for i := range N` becomes `for (let i_ts = 0; i_ts < N_ts; i_ts++) { ...body... }`.
|
|
28
|
+
// `for i, v := range N` becomes `for (let i_ts = 0; i_ts < N_ts; i_ts++) { const v_ts = i_ts; ...body... }`.
|
|
29
|
+
//
|
|
30
|
+
// - **Arrays (`*types.Array`) and Slices (`*types.Slice`):**
|
|
31
|
+
// - If both key (index) and value are used (`for i, val := range arr`):
|
|
32
|
+
// `for (let i_ts = 0; i_ts < arr_ts.length; i_ts++) { const val_ts = arr_ts[i_ts]; ...body... }`.
|
|
33
|
+
// - If only the key (index) is used (`for i := range arr`):
|
|
34
|
+
// `for (let i_ts = 0; i_ts < arr_ts.length; i_ts++) { ...body... }`.
|
|
35
|
+
// - If only the value is used (`for _, val := range arr`):
|
|
36
|
+
// `for (const v_ts of arr_ts) { const val_ts = v_ts; ...body... }`.
|
|
37
|
+
// - If neither is used (e.g., `for range arr`), a simple index loop `for (let _i = 0; ...)` is generated.
|
|
38
|
+
// The index variable `i_ts` uses the Go key variable name if provided.
|
|
39
|
+
//
|
|
40
|
+
// Loop variables (`exp.Key`, `exp.Value`) are declared as `const` inside the loop
|
|
41
|
+
// body if they are not blank identifiers (`_`). The loop body (`exp.Body`) is
|
|
42
|
+
// translated using `WriteStmtBlock` (or `WriteStmt` for array/slice with key and value).
|
|
43
|
+
// If the ranged type is not supported, a comment is written, and an error is returned.
|
|
44
|
+
func (c *GoToTSCompiler) WriteStmtRange(exp *ast.RangeStmt) error {
|
|
45
|
+
// Get the type of the iterable expression
|
|
46
|
+
iterType := c.pkg.TypesInfo.TypeOf(exp.X)
|
|
47
|
+
underlying := iterType.Underlying()
|
|
48
|
+
|
|
49
|
+
// Handle map types
|
|
50
|
+
if _, ok := underlying.(*types.Map); ok {
|
|
51
|
+
// Use for-of with entries() for proper Map iteration
|
|
52
|
+
c.tsw.WriteLiterally("for (const [k, v] of ")
|
|
53
|
+
if err := c.WriteValueExpr(exp.X); err != nil {
|
|
54
|
+
return fmt.Errorf("failed to write range loop map expression: %w", err)
|
|
55
|
+
}
|
|
56
|
+
c.tsw.WriteLiterally(".entries()) {")
|
|
57
|
+
c.tsw.Indent(1)
|
|
58
|
+
c.tsw.WriteLine("")
|
|
59
|
+
// If a key variable is provided and is not blank, declare it as a constant
|
|
60
|
+
if exp.Key != nil {
|
|
61
|
+
if ident, ok := exp.Key.(*ast.Ident); ok && ident.Name != "_" {
|
|
62
|
+
c.tsw.WriteLiterally("const ")
|
|
63
|
+
c.WriteIdent(ident, false)
|
|
64
|
+
c.tsw.WriteLiterally(" = k")
|
|
65
|
+
c.tsw.WriteLine("")
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
// If a value variable is provided and is not blank, use the value from entries()
|
|
69
|
+
if exp.Value != nil {
|
|
70
|
+
if ident, ok := exp.Value.(*ast.Ident); ok && ident.Name != "_" {
|
|
71
|
+
c.tsw.WriteLiterally("const ")
|
|
72
|
+
c.WriteIdent(ident, false)
|
|
73
|
+
c.tsw.WriteLiterally(" = v")
|
|
74
|
+
c.tsw.WriteLine("")
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// Write the loop body
|
|
78
|
+
if err := c.WriteStmtBlock(exp.Body, false); err != nil {
|
|
79
|
+
return fmt.Errorf("failed to write range loop map body: %w", err)
|
|
80
|
+
}
|
|
81
|
+
c.tsw.Indent(-1)
|
|
82
|
+
c.tsw.WriteLine("}")
|
|
83
|
+
return nil
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Handle basic types (string, integer)
|
|
87
|
+
if basic, ok := underlying.(*types.Basic); ok {
|
|
88
|
+
if basic.Info()&types.IsString != 0 {
|
|
89
|
+
// Add a scope to avoid collision of _runes variable
|
|
90
|
+
c.tsw.WriteLine("{")
|
|
91
|
+
c.tsw.Indent(1)
|
|
92
|
+
|
|
93
|
+
// Convert the string to runes using $.stringToRunes
|
|
94
|
+
c.tsw.WriteLiterally("const _runes = $.stringToRunes(")
|
|
95
|
+
if err := c.WriteValueExpr(exp.X); err != nil {
|
|
96
|
+
return fmt.Errorf("failed to write range loop string conversion expression: %w", err)
|
|
97
|
+
}
|
|
98
|
+
c.tsw.WriteLiterally(")")
|
|
99
|
+
c.tsw.WriteLine("")
|
|
100
|
+
|
|
101
|
+
// Determine the index variable name for the generated loop
|
|
102
|
+
indexVarName := "i" // Default name
|
|
103
|
+
if exp.Key != nil {
|
|
104
|
+
if keyIdent, ok := exp.Key.(*ast.Ident); ok && keyIdent.Name != "_" {
|
|
105
|
+
indexVarName = keyIdent.Name
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
c.tsw.WriteLiterallyf("for (let %s = 0; %s < _runes.length; %s++) {", indexVarName, indexVarName, indexVarName)
|
|
109
|
+
c.tsw.Indent(1)
|
|
110
|
+
c.tsw.WriteLine("")
|
|
111
|
+
// Declare value if provided and not blank
|
|
112
|
+
if exp.Value != nil {
|
|
113
|
+
if ident, ok := exp.Value.(*ast.Ident); ok && ident.Name != "_" {
|
|
114
|
+
c.tsw.WriteLiterally("const ")
|
|
115
|
+
c.WriteIdent(ident, false)
|
|
116
|
+
c.tsw.WriteLiterally(" = _runes[i]") // TODO: should be indexVarName?
|
|
117
|
+
c.tsw.WriteLine("")
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if err := c.WriteStmtBlock(exp.Body, false); err != nil {
|
|
121
|
+
return fmt.Errorf("failed to write range loop string body: %w", err)
|
|
122
|
+
}
|
|
123
|
+
c.tsw.Indent(-1)
|
|
124
|
+
c.tsw.WriteLine("}")
|
|
125
|
+
|
|
126
|
+
// outer }
|
|
127
|
+
c.tsw.Indent(-1)
|
|
128
|
+
c.tsw.WriteLine("}")
|
|
129
|
+
return nil
|
|
130
|
+
} else if basic.Info()&types.IsInteger != 0 {
|
|
131
|
+
// The value variable is not allowed ranging over an integer.
|
|
132
|
+
if exp.Value != nil {
|
|
133
|
+
return errors.Errorf("ranging over an integer supports key variable only (not value variable): %v", exp)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Handle ranging over an integer (Go 1.22+)
|
|
137
|
+
// Determine the index variable name for the generated loop
|
|
138
|
+
indexVarName := "_i" // Default name
|
|
139
|
+
if exp.Key != nil {
|
|
140
|
+
if keyIdent, ok := exp.Key.(*ast.Ident); ok && keyIdent.Name != "_" {
|
|
141
|
+
indexVarName = keyIdent.Name
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
c.tsw.WriteLiterallyf("for (let %s = 0; %s < ", indexVarName, indexVarName)
|
|
146
|
+
if err := c.WriteValueExpr(exp.X); err != nil { // This is N
|
|
147
|
+
return fmt.Errorf("failed to write range loop integer expression: %w", err)
|
|
148
|
+
}
|
|
149
|
+
c.tsw.WriteLiterallyf("; %s++) ", indexVarName)
|
|
150
|
+
|
|
151
|
+
// write body
|
|
152
|
+
if err := c.WriteStmtBlock(exp.Body, false); err != nil {
|
|
153
|
+
return fmt.Errorf("failed to write range loop integer body: %w", err)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return nil
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Handle array and slice types
|
|
161
|
+
_, isSlice := underlying.(*types.Slice)
|
|
162
|
+
_, isArray := underlying.(*types.Array)
|
|
163
|
+
if isArray || isSlice {
|
|
164
|
+
// Determine the index variable name for the generated loop
|
|
165
|
+
indexVarName := "_i" // Default name
|
|
166
|
+
if exp.Key != nil {
|
|
167
|
+
if keyIdent, ok := exp.Key.(*ast.Ident); ok && keyIdent.Name != "_" {
|
|
168
|
+
indexVarName = keyIdent.Name
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
// If both key and value are provided, use an index loop and assign both
|
|
172
|
+
if exp.Key != nil && exp.Value != nil {
|
|
173
|
+
c.tsw.WriteLiterallyf("for (let %s = 0; %s < $.len(", indexVarName, indexVarName)
|
|
174
|
+
if err := c.WriteValueExpr(exp.X); err != nil { // Write the expression for the iterable
|
|
175
|
+
return fmt.Errorf("failed to write range loop array/slice expression (key and value): %w", err)
|
|
176
|
+
}
|
|
177
|
+
c.tsw.WriteLiterallyf("); %s++) {", indexVarName)
|
|
178
|
+
c.tsw.Indent(1)
|
|
179
|
+
c.tsw.WriteLine("")
|
|
180
|
+
// Declare value if not blank
|
|
181
|
+
if ident, ok := exp.Value.(*ast.Ident); ok && ident.Name != "_" {
|
|
182
|
+
c.tsw.WriteLiterally("const ")
|
|
183
|
+
c.WriteIdent(ident, false)
|
|
184
|
+
c.tsw.WriteLiterally(" = ")
|
|
185
|
+
if err := c.WriteValueExpr(exp.X); err != nil {
|
|
186
|
+
return fmt.Errorf("failed to write range loop array/slice value expression: %w", err)
|
|
187
|
+
}
|
|
188
|
+
c.tsw.WriteLiterallyf("![%s]", indexVarName) // Use indexVarName with not-null assert
|
|
189
|
+
c.tsw.WriteLine("")
|
|
190
|
+
}
|
|
191
|
+
if err := c.WriteStmt(exp.Body); err != nil {
|
|
192
|
+
return fmt.Errorf("failed to write range loop array/slice body (key and value): %w", err)
|
|
193
|
+
}
|
|
194
|
+
c.tsw.Indent(-1)
|
|
195
|
+
c.tsw.WriteLine("}")
|
|
196
|
+
return nil
|
|
197
|
+
} else if exp.Key != nil && exp.Value == nil { // Only key provided
|
|
198
|
+
c.tsw.WriteLiterallyf("for (let %s = 0; %s < $.len(", indexVarName, indexVarName)
|
|
199
|
+
// Write the expression for the iterable
|
|
200
|
+
if err := c.WriteValueExpr(exp.X); err != nil {
|
|
201
|
+
return fmt.Errorf("failed to write expression for the iterable: %w", err)
|
|
202
|
+
}
|
|
203
|
+
c.tsw.WriteLiterallyf("); %s++) {", indexVarName)
|
|
204
|
+
c.tsw.Indent(1)
|
|
205
|
+
c.tsw.WriteLine("")
|
|
206
|
+
if err := c.WriteStmtBlock(exp.Body, false); err != nil {
|
|
207
|
+
return fmt.Errorf("failed to write range loop array/slice body (only key): %w", err)
|
|
208
|
+
}
|
|
209
|
+
c.tsw.Indent(-1)
|
|
210
|
+
c.tsw.WriteLine("}")
|
|
211
|
+
return nil
|
|
212
|
+
} else if exp.Key == nil && exp.Value != nil { // Only value provided
|
|
213
|
+
// I think this is impossible. See for_range_value_only test.
|
|
214
|
+
return errors.Errorf("unexpected value without key in for range expression: %v", exp)
|
|
215
|
+
} else {
|
|
216
|
+
// Fallback: simple index loop without declaring range variables, use _i
|
|
217
|
+
indexVarName := "_i"
|
|
218
|
+
c.tsw.WriteLiterallyf("for (let %s = 0; %s < $.len(", indexVarName, indexVarName)
|
|
219
|
+
if err := c.WriteValueExpr(exp.X); err != nil {
|
|
220
|
+
return fmt.Errorf("failed to write range loop array/slice length expression (fallback): %w", err)
|
|
221
|
+
}
|
|
222
|
+
c.tsw.WriteLiterallyf("); %s++) {", indexVarName)
|
|
223
|
+
c.tsw.Indent(1)
|
|
224
|
+
c.tsw.WriteLine("")
|
|
225
|
+
if err := c.WriteStmtBlock(exp.Body, false); err != nil {
|
|
226
|
+
return fmt.Errorf("failed to write range loop array/slice body (fallback): %w", err)
|
|
227
|
+
}
|
|
228
|
+
c.tsw.Indent(-1)
|
|
229
|
+
c.tsw.WriteLine("}")
|
|
230
|
+
return nil
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return errors.Errorf("unsupported range loop type: %T for expression %v", underlying, exp)
|
|
235
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
package compiler
|
|
2
|
+
|
|
3
|
+
import (
|
|
4
|
+
"fmt"
|
|
5
|
+
"go/ast"
|
|
6
|
+
"go/token"
|
|
7
|
+
|
|
8
|
+
"github.com/pkg/errors"
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
// WriteStmtSelect translates a Go `select` statement into an asynchronous
|
|
12
|
+
// TypeScript operation using the `$.selectStatement` runtime helper.
|
|
13
|
+
// Go's `select` provides non-deterministic choice over channel operations.
|
|
14
|
+
// This is emulated by constructing an array of `SelectCase` objects, one for
|
|
15
|
+
// each `case` in the Go `select`, and passing it to `$.selectStatement`.
|
|
16
|
+
//
|
|
17
|
+
// Each `SelectCase` object includes:
|
|
18
|
+
// - `id`: A unique identifier for the case.
|
|
19
|
+
// - `isSend`: `true` for send operations (`case ch <- val:`), `false` for receives.
|
|
20
|
+
// - `channel`: The TypeScript channel object.
|
|
21
|
+
// - `value` (for sends): The value being sent.
|
|
22
|
+
// - `onSelected: async (result) => { ... }`: A callback executed when this case
|
|
23
|
+
// is chosen. `result` contains `{ value, ok }` for receives.
|
|
24
|
+
// - Inside `onSelected`, assignments for receive operations (e.g., `v := <-ch`,
|
|
25
|
+
// `v, ok := <-ch`) are handled by declaring/assigning variables from `result.value`
|
|
26
|
+
// and `result.ok`.
|
|
27
|
+
// - The original Go case body is then translated within this callback.
|
|
28
|
+
//
|
|
29
|
+
// A `default` case in Go `select` is translated to a `SelectCase` with `id: -1`
|
|
30
|
+
// and its body in the `onSelected` handler. The `$.selectStatement` helper
|
|
31
|
+
// is informed if a default case exists.
|
|
32
|
+
// The entire `$.selectStatement(...)` call is `await`ed because channel
|
|
33
|
+
// operations are asynchronous in the TypeScript model.
|
|
34
|
+
func (c *GoToTSCompiler) WriteStmtSelect(exp *ast.SelectStmt) error {
|
|
35
|
+
// This is our implementation of the select statement, which will use Promise.race
|
|
36
|
+
// to achieve the same semantics as Go's select statement.
|
|
37
|
+
|
|
38
|
+
// Variable to track whether we have a default case
|
|
39
|
+
hasDefault := false
|
|
40
|
+
|
|
41
|
+
// Start the selectStatement call and the array literal
|
|
42
|
+
c.tsw.WriteLiterally("await $.selectStatement(")
|
|
43
|
+
c.tsw.WriteLine("[") // Put bracket on new line
|
|
44
|
+
c.tsw.Indent(1)
|
|
45
|
+
|
|
46
|
+
// For each case clause, generate a SelectCase object directly into the array literal
|
|
47
|
+
for i, stmt := range exp.Body.List {
|
|
48
|
+
if commClause, ok := stmt.(*ast.CommClause); ok {
|
|
49
|
+
if commClause.Comm == nil {
|
|
50
|
+
// This is a default case
|
|
51
|
+
hasDefault = true
|
|
52
|
+
// Add a SelectCase object for the default case with a special ID
|
|
53
|
+
c.tsw.WriteLiterally("{") // Start object literal
|
|
54
|
+
c.tsw.Indent(1)
|
|
55
|
+
c.tsw.WriteLine("")
|
|
56
|
+
c.tsw.WriteLiterally("id: -1,") // Special ID for default case
|
|
57
|
+
c.tsw.WriteLine("")
|
|
58
|
+
c.tsw.WriteLiterally("isSend: false,") // Default case is neither send nor receive, but needs a value
|
|
59
|
+
c.tsw.WriteLine("")
|
|
60
|
+
c.tsw.WriteLiterally("channel: null,") // No channel for default case
|
|
61
|
+
c.tsw.WriteLine("")
|
|
62
|
+
c.tsw.WriteLiterally("onSelected: async (result) => {") // Mark as async because case body might contain await
|
|
63
|
+
c.tsw.Indent(1)
|
|
64
|
+
c.tsw.WriteLine("")
|
|
65
|
+
// Write the case body
|
|
66
|
+
for _, bodyStmt := range commClause.Body {
|
|
67
|
+
if err := c.WriteStmt(bodyStmt); err != nil {
|
|
68
|
+
return fmt.Errorf("failed to write statement in select default case body (onSelected): %w", err)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
c.tsw.Indent(-1)
|
|
72
|
+
c.tsw.WriteLine("}") // Close onSelected handler
|
|
73
|
+
c.tsw.Indent(-1)
|
|
74
|
+
c.tsw.WriteLiterally("},") // Close SelectCase object and add comma
|
|
75
|
+
c.tsw.WriteLine("")
|
|
76
|
+
|
|
77
|
+
continue
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Generate a unique ID for this case
|
|
81
|
+
caseID := i
|
|
82
|
+
|
|
83
|
+
// Start writing the SelectCase object
|
|
84
|
+
c.tsw.WriteLiterally("{") // Start object literal
|
|
85
|
+
c.tsw.Indent(1)
|
|
86
|
+
c.tsw.WriteLine("")
|
|
87
|
+
c.tsw.WriteLiterallyf("id: %d,", caseID)
|
|
88
|
+
c.tsw.WriteLine("")
|
|
89
|
+
|
|
90
|
+
// Handle different types of comm statements
|
|
91
|
+
switch comm := commClause.Comm.(type) {
|
|
92
|
+
case *ast.AssignStmt:
|
|
93
|
+
// This is a receive operation with assignment: case v := <-ch: or case v, ok := <-ch:
|
|
94
|
+
if len(comm.Rhs) == 1 {
|
|
95
|
+
if unaryExpr, ok := comm.Rhs[0].(*ast.UnaryExpr); ok && unaryExpr.Op == token.ARROW {
|
|
96
|
+
// It's a receive operation
|
|
97
|
+
c.tsw.WriteLiterally("isSend: false,")
|
|
98
|
+
c.tsw.WriteLine("")
|
|
99
|
+
c.tsw.WriteLiterally("channel: ")
|
|
100
|
+
if err := c.WriteValueExpr(unaryExpr.X); err != nil { // The channel expression
|
|
101
|
+
return fmt.Errorf("failed to write channel expression in select receive case: %w", err)
|
|
102
|
+
}
|
|
103
|
+
c.tsw.WriteLiterally(",")
|
|
104
|
+
c.tsw.WriteLine("")
|
|
105
|
+
} else {
|
|
106
|
+
c.tsw.WriteCommentLinef("unhandled RHS in select assignment case: %T", comm.Rhs[0])
|
|
107
|
+
}
|
|
108
|
+
} else {
|
|
109
|
+
c.tsw.WriteCommentLinef("unhandled RHS count in select assignment case: %d", len(comm.Rhs))
|
|
110
|
+
}
|
|
111
|
+
case *ast.ExprStmt:
|
|
112
|
+
// This is a simple receive: case <-ch:
|
|
113
|
+
if unaryExpr, ok := comm.X.(*ast.UnaryExpr); ok && unaryExpr.Op == token.ARROW {
|
|
114
|
+
c.tsw.WriteLiterally("isSend: false,")
|
|
115
|
+
c.tsw.WriteLine("")
|
|
116
|
+
c.tsw.WriteLiterally("channel: ")
|
|
117
|
+
if err := c.WriteValueExpr(unaryExpr.X); err != nil { // The channel expression
|
|
118
|
+
return fmt.Errorf("failed to write channel expression in select receive case: %w", err)
|
|
119
|
+
}
|
|
120
|
+
c.tsw.WriteLiterally(",")
|
|
121
|
+
c.tsw.WriteLine("")
|
|
122
|
+
} else {
|
|
123
|
+
c.tsw.WriteCommentLinef("unhandled expression in select case: %T", comm.X)
|
|
124
|
+
}
|
|
125
|
+
case *ast.SendStmt:
|
|
126
|
+
// This is a send operation: case ch <- v:
|
|
127
|
+
c.tsw.WriteLiterally("isSend: true,")
|
|
128
|
+
c.tsw.WriteLine("")
|
|
129
|
+
c.tsw.WriteLiterally("channel: ")
|
|
130
|
+
if err := c.WriteValueExpr(comm.Chan); err != nil { // The channel expression
|
|
131
|
+
return fmt.Errorf("failed to write channel expression in select send case: %w", err)
|
|
132
|
+
}
|
|
133
|
+
c.tsw.WriteLiterally(",")
|
|
134
|
+
c.tsw.WriteLine("")
|
|
135
|
+
c.tsw.WriteLiterally("value: ")
|
|
136
|
+
if err := c.WriteValueExpr(comm.Value); err != nil { // The value expression
|
|
137
|
+
return fmt.Errorf("failed to write value expression in select send case: %w", err)
|
|
138
|
+
}
|
|
139
|
+
c.tsw.WriteLiterally(",")
|
|
140
|
+
c.tsw.WriteLine("")
|
|
141
|
+
default:
|
|
142
|
+
c.tsw.WriteCommentLinef("unhandled comm statement in select case: %T", comm)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Add the onSelected handler to execute the case body after the select resolves
|
|
146
|
+
c.tsw.WriteLiterally("onSelected: async (result) => {") // Mark as async because case body might contain await
|
|
147
|
+
c.tsw.Indent(1)
|
|
148
|
+
c.tsw.WriteLine("")
|
|
149
|
+
|
|
150
|
+
// Handle assignment for channel receives if needed (inside the onSelected handler)
|
|
151
|
+
if assignStmt, ok := commClause.Comm.(*ast.AssignStmt); ok {
|
|
152
|
+
// This is a receive operation with assignment
|
|
153
|
+
if len(assignStmt.Lhs) == 1 {
|
|
154
|
+
// Simple receive: case v := <-ch:
|
|
155
|
+
valIdent, ok := assignStmt.Lhs[0].(*ast.Ident)
|
|
156
|
+
if ok && valIdent.Name != "_" { // Check for blank identifier
|
|
157
|
+
c.tsw.WriteLiterally("const ")
|
|
158
|
+
c.WriteIdent(valIdent, false)
|
|
159
|
+
c.tsw.WriteLiterally(" = result.value")
|
|
160
|
+
c.tsw.WriteLine("")
|
|
161
|
+
}
|
|
162
|
+
} else if len(assignStmt.Lhs) == 2 {
|
|
163
|
+
// Receive with ok: case v, ok := <-ch:
|
|
164
|
+
valIdent, valOk := assignStmt.Lhs[0].(*ast.Ident)
|
|
165
|
+
okIdent, okOk := assignStmt.Lhs[1].(*ast.Ident)
|
|
166
|
+
|
|
167
|
+
if valOk && valIdent.Name != "_" {
|
|
168
|
+
c.tsw.WriteLiterally("const ")
|
|
169
|
+
c.WriteIdent(valIdent, false)
|
|
170
|
+
c.tsw.WriteLiterally(" = result.value")
|
|
171
|
+
c.tsw.WriteLine("")
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if okOk && okIdent.Name != "_" {
|
|
175
|
+
c.tsw.WriteLiterally("const ")
|
|
176
|
+
c.WriteIdent(okIdent, false)
|
|
177
|
+
c.tsw.WriteLiterally(" = result.ok")
|
|
178
|
+
c.tsw.WriteLine("")
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
// Note: Simple receive (case <-ch:) and send (case ch <- v:) don't require assignment here,
|
|
183
|
+
// as the operation was already performed by selectReceive/selectSend and the result is in 'result'.
|
|
184
|
+
|
|
185
|
+
// Write the case body
|
|
186
|
+
for _, bodyStmt := range commClause.Body {
|
|
187
|
+
if err := c.WriteStmt(bodyStmt); err != nil {
|
|
188
|
+
return fmt.Errorf("failed to write statement in select case body (onSelected): %w", err)
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
c.tsw.Indent(-1)
|
|
193
|
+
c.tsw.WriteLine("}") // Close onSelected handler
|
|
194
|
+
c.tsw.Indent(-1)
|
|
195
|
+
c.tsw.WriteLiterally("},") // Close SelectCase object and add comma
|
|
196
|
+
c.tsw.WriteLine("")
|
|
197
|
+
|
|
198
|
+
} else {
|
|
199
|
+
return errors.Errorf("unknown statement in select body: %T", stmt)
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Close the array literal and the selectStatement call
|
|
204
|
+
c.tsw.Indent(-1)
|
|
205
|
+
c.tsw.WriteLiterally("], ")
|
|
206
|
+
c.tsw.WriteLiterallyf("%t", hasDefault)
|
|
207
|
+
c.tsw.WriteLiterally(")")
|
|
208
|
+
c.tsw.WriteLine("")
|
|
209
|
+
|
|
210
|
+
return nil
|
|
211
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
package compiler
|
|
2
|
+
|
|
3
|
+
import (
|
|
4
|
+
"fmt"
|
|
5
|
+
"go/ast"
|
|
6
|
+
|
|
7
|
+
"github.com/pkg/errors"
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
// WriteStmtTypeSwitch translates a Go `type switch` statement (`ast.TypeSwitchStmt`)
|
|
11
|
+
// into its TypeScript equivalent using the `$.typeSwitch` helper.
|
|
12
|
+
func (c *GoToTSCompiler) WriteStmtTypeSwitch(stmt *ast.TypeSwitchStmt) error {
|
|
13
|
+
// Outer block for scoping Init variable
|
|
14
|
+
if stmt.Init != nil {
|
|
15
|
+
c.tsw.WriteLine("{")
|
|
16
|
+
c.tsw.Indent(1)
|
|
17
|
+
if err := c.WriteStmt(stmt.Init); err != nil {
|
|
18
|
+
return fmt.Errorf("failed to write type switch init statement: %w", err)
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Extract the subject expression and case variable identifier
|
|
23
|
+
var subjectExpr ast.Expr
|
|
24
|
+
var caseVarIdent *ast.Ident // The variable in 'v := x.(type)'
|
|
25
|
+
|
|
26
|
+
switch assignNode := stmt.Assign.(type) {
|
|
27
|
+
case *ast.AssignStmt: // v := x.(type)
|
|
28
|
+
if len(assignNode.Lhs) != 1 || len(assignNode.Rhs) != 1 {
|
|
29
|
+
return errors.Errorf("TypeSwitchStmt AssignStmt: expected 1 LHS and 1 RHS, got %d and %d", len(assignNode.Lhs), len(assignNode.Rhs))
|
|
30
|
+
}
|
|
31
|
+
ident, ok := assignNode.Lhs[0].(*ast.Ident)
|
|
32
|
+
if !ok {
|
|
33
|
+
return errors.Errorf("TypeSwitchStmt AssignStmt LHS is not *ast.Ident: %T", assignNode.Lhs[0])
|
|
34
|
+
}
|
|
35
|
+
caseVarIdent = ident
|
|
36
|
+
typeAssert, ok := assignNode.Rhs[0].(*ast.TypeAssertExpr)
|
|
37
|
+
if !ok {
|
|
38
|
+
return errors.Errorf("TypeSwitchStmt AssignStmt RHS is not *ast.TypeAssertExpr: %T", assignNode.Rhs[0])
|
|
39
|
+
}
|
|
40
|
+
if typeAssert.Type != nil {
|
|
41
|
+
return errors.Errorf("TypeSwitchStmt AssignStmt TypeAssertExpr.Type is not nil")
|
|
42
|
+
}
|
|
43
|
+
subjectExpr = typeAssert.X
|
|
44
|
+
case *ast.ExprStmt: // x.(type)
|
|
45
|
+
typeAssert, ok := assignNode.X.(*ast.TypeAssertExpr)
|
|
46
|
+
if !ok {
|
|
47
|
+
return errors.Errorf("TypeSwitchStmt ExprStmt.X is not *ast.TypeAssertExpr: %T", assignNode.X)
|
|
48
|
+
}
|
|
49
|
+
if typeAssert.Type != nil {
|
|
50
|
+
return errors.Errorf("TypeSwitchStmt ExprStmt TypeAssertExpr.Type is not nil")
|
|
51
|
+
}
|
|
52
|
+
subjectExpr = typeAssert.X
|
|
53
|
+
default:
|
|
54
|
+
return errors.Errorf("unknown Assign type in TypeSwitchStmt: %T", stmt.Assign)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Build the array of case configurations for $.typeSwitch
|
|
58
|
+
c.tsw.WriteLiterally("$.typeSwitch(")
|
|
59
|
+
if err := c.WriteValueExpr(subjectExpr); err != nil {
|
|
60
|
+
c.tsw.Indent(-1)
|
|
61
|
+
c.tsw.WriteLine("} // End TypeSwitchStmt due to error in subject")
|
|
62
|
+
return fmt.Errorf("failed to write subject expression in type switch: %w", err)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// case list
|
|
66
|
+
c.tsw.WriteLiterally(", [")
|
|
67
|
+
|
|
68
|
+
stmtBodyList := stmt.Body.List
|
|
69
|
+
var defaultCaseBody []ast.Stmt
|
|
70
|
+
|
|
71
|
+
for i, caseClauseStmt := range stmtBodyList {
|
|
72
|
+
caseClause, ok := caseClauseStmt.(*ast.CaseClause)
|
|
73
|
+
if !ok {
|
|
74
|
+
return errors.Errorf("unexpected statement in TypeSwitchStmt Body: not *ast.CaseClause but %T", caseClauseStmt)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if len(caseClause.List) == 0 { // Default case
|
|
78
|
+
defaultCaseBody = caseClause.Body
|
|
79
|
+
continue // Process default case after type cases
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Type case(s)
|
|
83
|
+
if i != 0 {
|
|
84
|
+
c.tsw.WriteLiterally(",")
|
|
85
|
+
c.tsw.WriteLine("")
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
c.tsw.WriteLiterally("{ types: [")
|
|
89
|
+
for j, typeExpr := range caseClause.List {
|
|
90
|
+
if j > 0 {
|
|
91
|
+
c.tsw.WriteLiterally(", ")
|
|
92
|
+
}
|
|
93
|
+
c.writeTypeDescription(typeExpr) // Descriptor for $.is or $.typeAssert
|
|
94
|
+
}
|
|
95
|
+
c.tsw.WriteLiterally("], body: (")
|
|
96
|
+
|
|
97
|
+
// Add case variable if it exists and is not '_'
|
|
98
|
+
if caseVarIdent != nil && caseVarIdent.Name != "_" {
|
|
99
|
+
c.WriteIdent(caseVarIdent, false) // isDeclaration = false for the parameter
|
|
100
|
+
// Note: TypeScript type inference should handle the parameter type based on the case type(s)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
c.tsw.WriteLiterally(") => {")
|
|
104
|
+
|
|
105
|
+
caseClauseBody := caseClause.Body
|
|
106
|
+
if len(caseClauseBody) != 0 {
|
|
107
|
+
c.tsw.Indent(1)
|
|
108
|
+
c.tsw.WriteLine("")
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
for _, bodyStmt := range caseClauseBody {
|
|
112
|
+
if err := c.WriteStmt(bodyStmt); err != nil {
|
|
113
|
+
return fmt.Errorf("failed to write statement in type switch case body: %w", err)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if len(caseClauseBody) != 0 {
|
|
118
|
+
c.tsw.Indent(-1)
|
|
119
|
+
}
|
|
120
|
+
c.tsw.WriteLiterally("}") // Close case body function
|
|
121
|
+
c.tsw.WriteLiterally("}") // Close case object
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
c.tsw.WriteLiterally("]") // Close cases array
|
|
125
|
+
|
|
126
|
+
// Add default case function if it exists
|
|
127
|
+
if len(defaultCaseBody) != 0 {
|
|
128
|
+
c.tsw.WriteLiterally(", () => {")
|
|
129
|
+
c.tsw.Indent(1)
|
|
130
|
+
c.tsw.WriteLine("")
|
|
131
|
+
for _, bodyStmt := range defaultCaseBody {
|
|
132
|
+
if err := c.WriteStmt(bodyStmt); err != nil {
|
|
133
|
+
return fmt.Errorf("failed to write statement in type switch default case body: %w", err)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
c.tsw.Indent(-1)
|
|
137
|
+
c.tsw.WriteLiterally("}") // Close default case function
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
c.tsw.WriteLine(")") // Close $.typeSwitch call
|
|
141
|
+
if stmt.Init != nil {
|
|
142
|
+
c.tsw.Indent(-1)
|
|
143
|
+
c.tsw.WriteLine("}") // Close outer block
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return nil
|
|
147
|
+
}
|