goscript 0.0.61 → 0.0.62
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/README.md +9 -0
- package/compiler/analysis.go +536 -15
- package/compiler/assignment.go +72 -0
- package/compiler/compiler.go +64 -11
- package/compiler/composite-lit.go +29 -8
- package/compiler/decl.go +20 -11
- package/compiler/expr-call-async.go +26 -1
- package/compiler/expr-call-builtins.go +60 -4
- package/compiler/expr-call-type-conversion.go +37 -5
- package/compiler/expr-call.go +16 -3
- package/compiler/expr-selector.go +35 -2
- package/compiler/expr-type.go +12 -2
- package/compiler/expr.go +37 -0
- package/compiler/index.test.ts +3 -1
- package/compiler/lit.go +13 -4
- package/compiler/spec-struct.go +30 -8
- package/compiler/spec-value.go +2 -2
- package/compiler/spec.go +21 -4
- package/compiler/stmt-assign.go +71 -0
- package/compiler/stmt-range.go +2 -2
- package/compiler/stmt.go +128 -0
- package/compiler/type-utils.go +40 -1
- package/compiler/type.go +50 -12
- package/dist/gs/builtin/builtin.d.ts +8 -1
- package/dist/gs/builtin/builtin.js +26 -1
- package/dist/gs/builtin/builtin.js.map +1 -1
- package/dist/gs/builtin/errors.d.ts +1 -0
- package/dist/gs/builtin/errors.js +8 -0
- package/dist/gs/builtin/errors.js.map +1 -1
- package/dist/gs/builtin/slice.d.ts +5 -4
- package/dist/gs/builtin/slice.js +45 -14
- package/dist/gs/builtin/slice.js.map +1 -1
- package/dist/gs/builtin/type.d.ts +23 -2
- package/dist/gs/builtin/type.js +125 -0
- package/dist/gs/builtin/type.js.map +1 -1
- package/dist/gs/bytes/reader.gs.d.ts +1 -1
- package/dist/gs/bytes/reader.gs.js +1 -1
- package/dist/gs/bytes/reader.gs.js.map +1 -1
- package/dist/gs/reflect/index.d.ts +2 -2
- package/dist/gs/reflect/index.js +1 -1
- package/dist/gs/reflect/index.js.map +1 -1
- package/dist/gs/reflect/map.d.ts +3 -2
- package/dist/gs/reflect/map.js +37 -3
- package/dist/gs/reflect/map.js.map +1 -1
- package/dist/gs/reflect/type.d.ts +50 -12
- package/dist/gs/reflect/type.js +820 -27
- package/dist/gs/reflect/type.js.map +1 -1
- package/dist/gs/reflect/types.d.ts +11 -12
- package/dist/gs/reflect/types.js +26 -15
- package/dist/gs/reflect/types.js.map +1 -1
- package/dist/gs/reflect/value.d.ts +4 -4
- package/dist/gs/reflect/value.js +8 -2
- package/dist/gs/reflect/value.js.map +1 -1
- package/dist/gs/slices/slices.d.ts +21 -0
- package/dist/gs/slices/slices.js +48 -0
- package/dist/gs/slices/slices.js.map +1 -1
- package/dist/gs/sync/atomic/type.gs.d.ts +2 -2
- package/dist/gs/sync/atomic/type.gs.js +12 -2
- package/dist/gs/sync/atomic/type.gs.js.map +1 -1
- package/dist/gs/unicode/utf8/utf8.d.ts +2 -2
- package/dist/gs/unicode/utf8/utf8.js +10 -6
- package/dist/gs/unicode/utf8/utf8.js.map +1 -1
- package/go.mod +4 -4
- package/go.sum +8 -8
- package/gs/builtin/builtin.ts +27 -2
- package/gs/builtin/errors.ts +12 -0
- package/gs/builtin/slice.ts +71 -7
- package/gs/builtin/type.ts +159 -2
- package/gs/bytes/reader.gs.ts +2 -2
- package/gs/math/hypot.gs.test.ts +3 -1
- package/gs/math/pow10.gs.test.ts +5 -4
- package/gs/reflect/index.ts +3 -2
- package/gs/reflect/map.test.ts +7 -6
- package/gs/reflect/map.ts +49 -7
- package/gs/reflect/type.ts +1053 -54
- package/gs/reflect/types.ts +34 -21
- package/gs/reflect/value.ts +12 -6
- package/gs/slices/slices.ts +55 -0
- package/gs/sync/atomic/type.gs.ts +14 -5
- package/gs/unicode/utf8/utf8.ts +12 -8
- package/package.json +13 -13
package/compiler/assignment.go
CHANGED
|
@@ -219,6 +219,15 @@ func (c *GoToTSCompiler) writeAssignmentCore(lhs, rhs []ast.Expr, tok token.Toke
|
|
|
219
219
|
if shouldApplyClone(c.pkg, r) {
|
|
220
220
|
// When cloning for value assignment, mark the result as struct value
|
|
221
221
|
c.tsw.WriteLiterally("$.markAsStructValue(")
|
|
222
|
+
|
|
223
|
+
// Check if RHS is an async call - if so, wrap in parentheses so .clone() binds correctly
|
|
224
|
+
// Example: (await asyncFunc()).clone() instead of await asyncFunc().clone()
|
|
225
|
+
needsParensForAsync := false
|
|
226
|
+
if callExpr, isCall := r.(*ast.CallExpr); isCall && c.isCallExprAsync(callExpr) {
|
|
227
|
+
needsParensForAsync = true
|
|
228
|
+
c.tsw.WriteLiterally("(")
|
|
229
|
+
}
|
|
230
|
+
|
|
222
231
|
// For other expressions, we need to handle variable referenced access differently
|
|
223
232
|
if _, isIdent := r.(*ast.Ident); isIdent {
|
|
224
233
|
// For identifiers, WriteValueExpr already adds .value if needed
|
|
@@ -236,6 +245,9 @@ func (c *GoToTSCompiler) writeAssignmentCore(lhs, rhs []ast.Expr, tok token.Toke
|
|
|
236
245
|
}
|
|
237
246
|
}
|
|
238
247
|
|
|
248
|
+
if needsParensForAsync {
|
|
249
|
+
c.tsw.WriteLiterally(")")
|
|
250
|
+
}
|
|
239
251
|
c.tsw.WriteLiterally(".clone())") // Always add clone for struct values
|
|
240
252
|
} else {
|
|
241
253
|
// Check if this is a pointer variable assignment to an interface type
|
|
@@ -270,6 +282,11 @@ func (c *GoToTSCompiler) writeAssignmentCore(lhs, rhs []ast.Expr, tok token.Toke
|
|
|
270
282
|
}
|
|
271
283
|
|
|
272
284
|
// Non-struct case: write RHS normally
|
|
285
|
+
// Check if this is a primitive error type being assigned to an error interface
|
|
286
|
+
if c.writePrimitiveErrorWrapperForAssign(lhs, r, i) {
|
|
287
|
+
continue
|
|
288
|
+
}
|
|
289
|
+
|
|
273
290
|
if err := c.WriteValueExpr(r); err != nil { // RHS is a non-struct value
|
|
274
291
|
return err
|
|
275
292
|
}
|
|
@@ -288,6 +305,61 @@ func (c *GoToTSCompiler) writeAssignmentCore(lhs, rhs []ast.Expr, tok token.Toke
|
|
|
288
305
|
return nil
|
|
289
306
|
}
|
|
290
307
|
|
|
308
|
+
// writePrimitiveErrorWrapperForAssign checks if an RHS value is a primitive type
|
|
309
|
+
// that implements the error interface being assigned to an error-typed LHS,
|
|
310
|
+
// and if so, wraps it with $.wrapPrimitiveError.
|
|
311
|
+
// Returns true if the wrapper was written, false otherwise.
|
|
312
|
+
func (c *GoToTSCompiler) writePrimitiveErrorWrapperForAssign(lhs []ast.Expr, rhs ast.Expr, rhsIndex int) bool {
|
|
313
|
+
// Only handle single assignments for now
|
|
314
|
+
if len(lhs) != 1 || rhsIndex != 0 {
|
|
315
|
+
return false
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Get the LHS type
|
|
319
|
+
lhsType := c.pkg.TypesInfo.TypeOf(lhs[0])
|
|
320
|
+
if lhsType == nil {
|
|
321
|
+
return false
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// Check if the LHS type is the error interface
|
|
325
|
+
if iface, ok := lhsType.Underlying().(*types.Interface); !ok || iface.String() != "interface{Error() string}" {
|
|
326
|
+
return false
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Get the actual type of the RHS expression
|
|
330
|
+
rhsType := c.pkg.TypesInfo.TypeOf(rhs)
|
|
331
|
+
if rhsType == nil {
|
|
332
|
+
return false
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Check if the RHS type is a wrapper type (named type with basic underlying type)
|
|
336
|
+
if !c.isWrapperType(rhsType) {
|
|
337
|
+
return false
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// Check if the RHS type has an Error() method
|
|
341
|
+
if !c.typeHasMethods(rhsType, "Error") {
|
|
342
|
+
return false
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// Get the qualified type name for the Error function
|
|
346
|
+
typeName := c.getQualifiedTypeName(rhsType)
|
|
347
|
+
if typeName == "" {
|
|
348
|
+
return false
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// Write: $.wrapPrimitiveError(value, TypeName_Error)
|
|
352
|
+
c.tsw.WriteLiterally("$.wrapPrimitiveError(")
|
|
353
|
+
if err := c.WriteValueExpr(rhs); err != nil {
|
|
354
|
+
return false
|
|
355
|
+
}
|
|
356
|
+
c.tsw.WriteLiterally(", ")
|
|
357
|
+
c.tsw.WriteLiterally(typeName)
|
|
358
|
+
c.tsw.WriteLiterally("_Error)")
|
|
359
|
+
|
|
360
|
+
return true
|
|
361
|
+
}
|
|
362
|
+
|
|
291
363
|
// writeBlankIdentifierAssign handles assignment to blank identifier (_)
|
|
292
364
|
func (c *GoToTSCompiler) writeBlankIdentifierAssign(rhs ast.Expr) error {
|
|
293
365
|
c.tsw.WriteLiterally("/* _ = */ ")
|
package/compiler/compiler.go
CHANGED
|
@@ -13,7 +13,6 @@ import (
|
|
|
13
13
|
"os"
|
|
14
14
|
"path/filepath"
|
|
15
15
|
"slices"
|
|
16
|
-
"sort"
|
|
17
16
|
"strings"
|
|
18
17
|
|
|
19
18
|
gs "github.com/aperturerobotics/goscript"
|
|
@@ -487,7 +486,7 @@ func (c *PackageCompiler) generateIndexFile(compiledFiles []string) error {
|
|
|
487
486
|
|
|
488
487
|
// Write exports if this file has exported symbols
|
|
489
488
|
if len(valueSymbols) > 0 {
|
|
490
|
-
|
|
489
|
+
slices.Sort(valueSymbols)
|
|
491
490
|
exportLine := fmt.Sprintf("export { %s } from \"./%s.js\"\n",
|
|
492
491
|
strings.Join(valueSymbols, ", "), fileName)
|
|
493
492
|
if _, err := indexFile.WriteString(exportLine); err != nil {
|
|
@@ -497,7 +496,7 @@ func (c *PackageCompiler) generateIndexFile(compiledFiles []string) error {
|
|
|
497
496
|
|
|
498
497
|
// Write struct exports (both as types and values)
|
|
499
498
|
if len(structSymbols) > 0 {
|
|
500
|
-
|
|
499
|
+
slices.Sort(structSymbols)
|
|
501
500
|
// Export classes as values (which makes them available as both types and values in TypeScript)
|
|
502
501
|
exportLine := fmt.Sprintf("export { %s } from \"./%s.js\"\n",
|
|
503
502
|
strings.Join(structSymbols, ", "), fileName)
|
|
@@ -507,7 +506,7 @@ func (c *PackageCompiler) generateIndexFile(compiledFiles []string) error {
|
|
|
507
506
|
}
|
|
508
507
|
|
|
509
508
|
if len(typeSymbols) > 0 {
|
|
510
|
-
|
|
509
|
+
slices.Sort(typeSymbols)
|
|
511
510
|
exportLine := fmt.Sprintf("export type { %s } from \"./%s.js\"\n",
|
|
512
511
|
strings.Join(typeSymbols, ", "), fileName)
|
|
513
512
|
if _, err := indexFile.WriteString(exportLine); err != nil {
|
|
@@ -612,7 +611,7 @@ func (c *FileCompiler) Compile(ctx context.Context) error {
|
|
|
612
611
|
for sourceFile := range imports {
|
|
613
612
|
sourceFiles = append(sourceFiles, sourceFile)
|
|
614
613
|
}
|
|
615
|
-
|
|
614
|
+
slices.Sort(sourceFiles)
|
|
616
615
|
|
|
617
616
|
for _, sourceFile := range sourceFiles {
|
|
618
617
|
functions := imports[sourceFile]
|
|
@@ -623,7 +622,7 @@ func (c *FileCompiler) Compile(ctx context.Context) error {
|
|
|
623
622
|
sanitizedFunctions = append(sanitizedFunctions, sanitizeIdentifier(fn))
|
|
624
623
|
}
|
|
625
624
|
// Sort functions for consistent output
|
|
626
|
-
|
|
625
|
+
slices.Sort(sanitizedFunctions)
|
|
627
626
|
c.codeWriter.WriteLinef("import { %s } from \"./%s.gs.js\";",
|
|
628
627
|
strings.Join(sanitizedFunctions, ", "), sourceFile)
|
|
629
628
|
}
|
|
@@ -637,7 +636,7 @@ func (c *FileCompiler) Compile(ctx context.Context) error {
|
|
|
637
636
|
for sourceFile := range typeImports {
|
|
638
637
|
sourceFiles = append(sourceFiles, sourceFile)
|
|
639
638
|
}
|
|
640
|
-
|
|
639
|
+
slices.Sort(sourceFiles)
|
|
641
640
|
|
|
642
641
|
for _, sourceFile := range sourceFiles {
|
|
643
642
|
typeImports := typeImports[sourceFile]
|
|
@@ -668,7 +667,7 @@ func (c *FileCompiler) Compile(ctx context.Context) error {
|
|
|
668
667
|
sanitizedTypes = append(sanitizedTypes, sanitizeIdentifier(typeName))
|
|
669
668
|
}
|
|
670
669
|
// Sort types for consistent output
|
|
671
|
-
|
|
670
|
+
slices.Sort(sanitizedTypes)
|
|
672
671
|
c.codeWriter.WriteLinef("import { %s } from \"./%s.gs.js\";",
|
|
673
672
|
strings.Join(sanitizedTypes, ", "), sourceFile)
|
|
674
673
|
}
|
|
@@ -676,6 +675,43 @@ func (c *FileCompiler) Compile(ctx context.Context) error {
|
|
|
676
675
|
}
|
|
677
676
|
}
|
|
678
677
|
|
|
678
|
+
// Generate auto-imports for variables from other files in the same package
|
|
679
|
+
if varImports := c.PackageAnalysis.VariableCalls[currentFileName]; varImports != nil {
|
|
680
|
+
// Sort source files for consistent import order
|
|
681
|
+
var sourceFiles []string
|
|
682
|
+
for sourceFile := range varImports {
|
|
683
|
+
sourceFiles = append(sourceFiles, sourceFile)
|
|
684
|
+
}
|
|
685
|
+
slices.Sort(sourceFiles)
|
|
686
|
+
|
|
687
|
+
for _, sourceFile := range sourceFiles {
|
|
688
|
+
variables := varImports[sourceFile]
|
|
689
|
+
if len(variables) > 0 {
|
|
690
|
+
// Apply sanitization to variable names
|
|
691
|
+
var sanitizedVariables []string
|
|
692
|
+
for _, varName := range variables {
|
|
693
|
+
sanitizedVariables = append(sanitizedVariables, sanitizeIdentifier(varName))
|
|
694
|
+
}
|
|
695
|
+
// Sort variables for consistent output
|
|
696
|
+
slices.Sort(sanitizedVariables)
|
|
697
|
+
c.codeWriter.WriteLinef("import { %s } from \"./%s.gs.js\";",
|
|
698
|
+
strings.Join(sanitizedVariables, ", "), sourceFile)
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
// Write synthetic imports (for promoted methods from embedded structs)
|
|
704
|
+
// Sort by package name for consistent output
|
|
705
|
+
var syntheticPkgNames []string
|
|
706
|
+
for pkgName := range c.Analysis.SyntheticImports {
|
|
707
|
+
syntheticPkgNames = append(syntheticPkgNames, pkgName)
|
|
708
|
+
}
|
|
709
|
+
slices.Sort(syntheticPkgNames)
|
|
710
|
+
for _, pkgName := range syntheticPkgNames {
|
|
711
|
+
imp := c.Analysis.SyntheticImports[pkgName]
|
|
712
|
+
c.codeWriter.WriteImport(pkgName, imp.importPath+"/index.js")
|
|
713
|
+
}
|
|
714
|
+
|
|
679
715
|
c.codeWriter.WriteLine("") // Add a newline after imports
|
|
680
716
|
|
|
681
717
|
if err := goWriter.WriteDecls(f.Decls); err != nil {
|
|
@@ -697,6 +733,10 @@ type GoToTSCompiler struct {
|
|
|
697
733
|
|
|
698
734
|
// Context flags
|
|
699
735
|
insideAddressOf bool // true when processing operand of & operator
|
|
736
|
+
|
|
737
|
+
// renamedVars tracks variables that have been renamed to avoid type shadowing
|
|
738
|
+
// Key: types.Object of the original variable, Value: new name to use
|
|
739
|
+
renamedVars map[types.Object]string
|
|
700
740
|
}
|
|
701
741
|
|
|
702
742
|
// It initializes the compiler with a `TSCodeWriter` for output,
|
|
@@ -704,9 +744,10 @@ type GoToTSCompiler struct {
|
|
|
704
744
|
// analysis results (`Analysis`) to guide the translation process.
|
|
705
745
|
func NewGoToTSCompiler(tsw *TSCodeWriter, pkg *packages.Package, analysis *Analysis) *GoToTSCompiler {
|
|
706
746
|
return &GoToTSCompiler{
|
|
707
|
-
tsw:
|
|
708
|
-
pkg:
|
|
709
|
-
analysis:
|
|
747
|
+
tsw: tsw,
|
|
748
|
+
pkg: pkg,
|
|
749
|
+
analysis: analysis,
|
|
750
|
+
renamedVars: make(map[types.Object]string),
|
|
710
751
|
}
|
|
711
752
|
}
|
|
712
753
|
|
|
@@ -785,6 +826,18 @@ func (c *GoToTSCompiler) WriteIdent(exp *ast.Ident, accessVarRefedValue bool) {
|
|
|
785
826
|
// Use TypesInfo to find the object associated with the identifier
|
|
786
827
|
obj := c.objectOfIdent(exp)
|
|
787
828
|
|
|
829
|
+
// Check if this variable has been renamed to avoid type shadowing
|
|
830
|
+
if obj != nil {
|
|
831
|
+
if renamedName, ok := c.renamedVars[obj]; ok {
|
|
832
|
+
c.tsw.WriteLiterally(c.sanitizeIdentifier(renamedName))
|
|
833
|
+
// Determine if we need to access .value based on analysis data
|
|
834
|
+
if accessVarRefedValue && c.analysis.NeedsVarRefAccess(obj) {
|
|
835
|
+
c.tsw.WriteLiterally("!.value")
|
|
836
|
+
}
|
|
837
|
+
return
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
|
|
788
841
|
// Check if this identifier refers to a constant
|
|
789
842
|
if obj != nil {
|
|
790
843
|
if constObj, isConst := obj.(*types.Const); isConst {
|
|
@@ -341,7 +341,7 @@ func (c *GoToTSCompiler) WriteCompositeLit(exp *ast.CompositeLit) error {
|
|
|
341
341
|
case *types.Map, *types.Struct:
|
|
342
342
|
// Handle struct directly with the struct literal logic
|
|
343
343
|
if structType, ok := underlying.(*types.Struct); ok {
|
|
344
|
-
return c.writeUntypedStructLiteral(exp, structType)
|
|
344
|
+
return c.writeUntypedStructLiteral(exp, tv.Type, structType)
|
|
345
345
|
}
|
|
346
346
|
// Map case would be handled here
|
|
347
347
|
return fmt.Errorf("untyped map composite literals not yet supported")
|
|
@@ -356,7 +356,7 @@ func (c *GoToTSCompiler) WriteCompositeLit(exp *ast.CompositeLit) error {
|
|
|
356
356
|
// This is an anonymous struct literal with inferred pointer type
|
|
357
357
|
// Just create the struct object directly - no var-refing needed
|
|
358
358
|
// Anonymous literals are not variables, so they don't get var-refed
|
|
359
|
-
return c.writeUntypedStructLiteral(exp, elemType)
|
|
359
|
+
return c.writeUntypedStructLiteral(exp, ptrType.Elem(), elemType)
|
|
360
360
|
default:
|
|
361
361
|
return fmt.Errorf("unhandled pointer composite literal element type: %T", elemType)
|
|
362
362
|
}
|
|
@@ -384,7 +384,7 @@ func (c *GoToTSCompiler) writeUntypedArrayLiteral(exp *ast.CompositeLit) error {
|
|
|
384
384
|
}
|
|
385
385
|
|
|
386
386
|
// writeUntypedStructLiteral handles untyped composite literals that are structs or pointers to structs
|
|
387
|
-
func (c *GoToTSCompiler) writeUntypedStructLiteral(exp *ast.CompositeLit, structType *types.Struct) error {
|
|
387
|
+
func (c *GoToTSCompiler) writeUntypedStructLiteral(exp *ast.CompositeLit, actualType types.Type, structType *types.Struct) error {
|
|
388
388
|
// Create field mapping like the typed struct case
|
|
389
389
|
directFields := make(map[string]ast.Expr)
|
|
390
390
|
|
|
@@ -408,8 +408,23 @@ func (c *GoToTSCompiler) writeUntypedStructLiteral(exp *ast.CompositeLit, struct
|
|
|
408
408
|
}
|
|
409
409
|
}
|
|
410
410
|
|
|
411
|
-
//
|
|
412
|
-
|
|
411
|
+
// Check if this is a named type
|
|
412
|
+
isNamed := false
|
|
413
|
+
if _, ok := actualType.(*types.Named); ok {
|
|
414
|
+
isNamed = true
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// Write the object literal
|
|
418
|
+
if isNamed {
|
|
419
|
+
// For named structs, use constructor
|
|
420
|
+
c.tsw.WriteLiterally("$.markAsStructValue(new ")
|
|
421
|
+
// Write the type name
|
|
422
|
+
c.WriteGoType(actualType, GoTypeContextGeneral)
|
|
423
|
+
c.tsw.WriteLiterally("({")
|
|
424
|
+
} else {
|
|
425
|
+
// For truly anonymous structs, just write a simple object literal
|
|
426
|
+
c.tsw.WriteLiterally("{")
|
|
427
|
+
}
|
|
413
428
|
|
|
414
429
|
firstFieldWritten := false
|
|
415
430
|
// Write fields in order
|
|
@@ -434,7 +449,12 @@ func (c *GoToTSCompiler) writeUntypedStructLiteral(exp *ast.CompositeLit, struct
|
|
|
434
449
|
firstFieldWritten = true
|
|
435
450
|
}
|
|
436
451
|
|
|
437
|
-
|
|
452
|
+
// Close the object literal
|
|
453
|
+
if isNamed {
|
|
454
|
+
c.tsw.WriteLiterally("}))")
|
|
455
|
+
} else {
|
|
456
|
+
c.tsw.WriteLiterally("}")
|
|
457
|
+
}
|
|
438
458
|
return nil
|
|
439
459
|
}
|
|
440
460
|
|
|
@@ -606,9 +626,10 @@ func (c *GoToTSCompiler) categorizeStructFields(
|
|
|
606
626
|
}
|
|
607
627
|
}
|
|
608
628
|
|
|
609
|
-
// Handle the case where
|
|
629
|
+
// Handle the case where a struct has values without keys (positional initialization)
|
|
610
630
|
// This block processes non-key-value elements and associates them with struct fields.
|
|
611
|
-
|
|
631
|
+
// This applies to both named and anonymous structs.
|
|
632
|
+
if len(exp.Elts) > 0 && len(directFields) == 0 {
|
|
612
633
|
// Check if any elements in the composite literal are not key-value pairs.
|
|
613
634
|
hasNonKeyValueElts := false
|
|
614
635
|
for _, elt := range exp.Elts {
|
package/compiler/decl.go
CHANGED
|
@@ -5,7 +5,7 @@ import (
|
|
|
5
5
|
"go/ast"
|
|
6
6
|
"go/token"
|
|
7
7
|
"go/types"
|
|
8
|
-
"
|
|
8
|
+
"slices"
|
|
9
9
|
)
|
|
10
10
|
|
|
11
11
|
// WriteDecls iterates through a slice of Go top-level declarations (`ast.Decl`)
|
|
@@ -210,7 +210,7 @@ func (c *GoToTSCompiler) extractTypeDependencies(typeExpr ast.Expr, typeSpecMap
|
|
|
210
210
|
}
|
|
211
211
|
|
|
212
212
|
// Sort dependencies for deterministic output
|
|
213
|
-
|
|
213
|
+
slices.Sort(deps)
|
|
214
214
|
return deps
|
|
215
215
|
}
|
|
216
216
|
|
|
@@ -347,7 +347,7 @@ func (c *GoToTSCompiler) topologicalSort(dependencies map[string][]string) ([]st
|
|
|
347
347
|
// Sort dependencies for consistent output
|
|
348
348
|
sortedDeps := make([]string, len(deps))
|
|
349
349
|
copy(sortedDeps, deps)
|
|
350
|
-
|
|
350
|
+
slices.Sort(sortedDeps)
|
|
351
351
|
|
|
352
352
|
for _, dep := range sortedDeps {
|
|
353
353
|
if _, exists := inDegree[dep]; exists {
|
|
@@ -359,7 +359,7 @@ func (c *GoToTSCompiler) topologicalSort(dependencies map[string][]string) ([]st
|
|
|
359
359
|
|
|
360
360
|
// Sort neighbors in graph for consistency
|
|
361
361
|
for node := range graph {
|
|
362
|
-
|
|
362
|
+
slices.Sort(graph[node])
|
|
363
363
|
}
|
|
364
364
|
|
|
365
365
|
// Find nodes with no incoming edges and sort them
|
|
@@ -369,7 +369,7 @@ func (c *GoToTSCompiler) topologicalSort(dependencies map[string][]string) ([]st
|
|
|
369
369
|
queue = append(queue, node)
|
|
370
370
|
}
|
|
371
371
|
}
|
|
372
|
-
|
|
372
|
+
slices.Sort(queue) // Sort initial queue for deterministic output
|
|
373
373
|
|
|
374
374
|
var result []string
|
|
375
375
|
|
|
@@ -389,7 +389,7 @@ func (c *GoToTSCompiler) topologicalSort(dependencies map[string][]string) ([]st
|
|
|
389
389
|
}
|
|
390
390
|
|
|
391
391
|
// Sort new zero-degree nodes and add to queue
|
|
392
|
-
|
|
392
|
+
slices.Sort(newZeroNodes)
|
|
393
393
|
queue = append(queue, newZeroNodes...)
|
|
394
394
|
}
|
|
395
395
|
|
|
@@ -407,7 +407,7 @@ func (c *GoToTSCompiler) topologicalSort(dependencies map[string][]string) ([]st
|
|
|
407
407
|
remaining = append(remaining, name)
|
|
408
408
|
}
|
|
409
409
|
}
|
|
410
|
-
|
|
410
|
+
slices.Sort(remaining)
|
|
411
411
|
|
|
412
412
|
return nil, fmt.Errorf("circular dependency detected in type declarations. Remaining types: %v", remaining)
|
|
413
413
|
}
|
|
@@ -622,11 +622,20 @@ func (c *GoToTSCompiler) writeMethodSignature(decl *ast.FuncDecl) (bool, error)
|
|
|
622
622
|
} else {
|
|
623
623
|
// Multiple return values -> tuple type
|
|
624
624
|
c.tsw.WriteLiterally("[")
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
625
|
+
first := true
|
|
626
|
+
for _, field := range funcType.Results.List {
|
|
627
|
+
// Each field may represent multiple return values (e.g., "a, b int")
|
|
628
|
+
count := len(field.Names)
|
|
629
|
+
if count == 0 {
|
|
630
|
+
count = 1 // Unnamed return value
|
|
631
|
+
}
|
|
632
|
+
for j := 0; j < count; j++ {
|
|
633
|
+
if !first {
|
|
634
|
+
c.tsw.WriteLiterally(", ")
|
|
635
|
+
}
|
|
636
|
+
first = false
|
|
637
|
+
c.WriteTypeExpr(field.Type)
|
|
628
638
|
}
|
|
629
|
-
c.WriteTypeExpr(field.Type)
|
|
630
639
|
}
|
|
631
640
|
c.tsw.WriteLiterally("]")
|
|
632
641
|
}
|
|
@@ -12,7 +12,15 @@ func (c *GoToTSCompiler) isCallExprAsync(exp *ast.CallExpr) bool {
|
|
|
12
12
|
case *ast.Ident:
|
|
13
13
|
// Function call (e.g., func())
|
|
14
14
|
if obj := c.objectOfIdent(fun); obj != nil {
|
|
15
|
-
|
|
15
|
+
// Check if this is a known async function
|
|
16
|
+
if c.analysis.IsAsyncFunc(obj) {
|
|
17
|
+
return true
|
|
18
|
+
}
|
|
19
|
+
// Check if this is a variable that returns async values
|
|
20
|
+
// (e.g., indirect := sync.OnceValue(asyncFunc))
|
|
21
|
+
if c.analysis.IsAsyncReturningVar(obj) {
|
|
22
|
+
return true
|
|
23
|
+
}
|
|
16
24
|
}
|
|
17
25
|
return false
|
|
18
26
|
|
|
@@ -42,6 +50,13 @@ func (c *GoToTSCompiler) isCallExprAsync(exp *ast.CallExpr) bool {
|
|
|
42
50
|
objOk = true
|
|
43
51
|
}
|
|
44
52
|
|
|
53
|
+
case *ast.CallExpr:
|
|
54
|
+
// Method call on function result: funcCall().method()
|
|
55
|
+
// Get the type of the function call result
|
|
56
|
+
if callType := c.pkg.TypesInfo.TypeOf(x); callType != nil {
|
|
57
|
+
objOk = true
|
|
58
|
+
}
|
|
59
|
+
|
|
45
60
|
default:
|
|
46
61
|
objOk = false
|
|
47
62
|
}
|
|
@@ -144,6 +159,16 @@ func (c *GoToTSCompiler) addNonNullAssertion(expFun ast.Expr) {
|
|
|
144
159
|
c.tsw.WriteLiterally("!")
|
|
145
160
|
}
|
|
146
161
|
}
|
|
162
|
+
} else if selectorExpr, isSelectorExpr := expFun.(*ast.SelectorExpr); isSelectorExpr {
|
|
163
|
+
// Check if this is a field access that returns a function type
|
|
164
|
+
// e.g., s.step where step is a function-typed field
|
|
165
|
+
if selection := c.pkg.TypesInfo.Selections[selectorExpr]; selection != nil {
|
|
166
|
+
// This is a field or method selection
|
|
167
|
+
if selection.Kind() == types.FieldVal {
|
|
168
|
+
// It's a field - function-typed fields may be nil
|
|
169
|
+
c.tsw.WriteLiterally("!")
|
|
170
|
+
}
|
|
171
|
+
}
|
|
147
172
|
} else if _, isNamed := funType.(*types.Named); isNamed {
|
|
148
173
|
c.tsw.WriteLiterally("!")
|
|
149
174
|
}
|
|
@@ -25,6 +25,9 @@ var builtinFunctions = map[string]bool{
|
|
|
25
25
|
"recover": true,
|
|
26
26
|
"print": true,
|
|
27
27
|
"println": true,
|
|
28
|
+
"min": true,
|
|
29
|
+
"max": true,
|
|
30
|
+
"clear": true,
|
|
28
31
|
}
|
|
29
32
|
|
|
30
33
|
// writeBuiltinFunction handles built-in Go functions
|
|
@@ -34,7 +37,7 @@ func (c *GoToTSCompiler) writeBuiltinFunction(exp *ast.CallExpr, funName string)
|
|
|
34
37
|
c.tsw.WriteLiterally("$.panic")
|
|
35
38
|
return true, nil
|
|
36
39
|
case "println":
|
|
37
|
-
c.tsw.WriteLiterally("
|
|
40
|
+
c.tsw.WriteLiterally("$.println")
|
|
38
41
|
return true, nil
|
|
39
42
|
case "len":
|
|
40
43
|
if len(exp.Args) != 1 {
|
|
@@ -89,6 +92,46 @@ func (c *GoToTSCompiler) writeBuiltinFunction(exp *ast.CallExpr, funName string)
|
|
|
89
92
|
return true, nil
|
|
90
93
|
case "append":
|
|
91
94
|
return true, c.writeAppendCall(exp)
|
|
95
|
+
case "min":
|
|
96
|
+
if len(exp.Args) < 1 {
|
|
97
|
+
return true, errors.New("unhandled min call with no arguments")
|
|
98
|
+
}
|
|
99
|
+
c.tsw.WriteLiterally("Math.min(")
|
|
100
|
+
for i, arg := range exp.Args {
|
|
101
|
+
if i > 0 {
|
|
102
|
+
c.tsw.WriteLiterally(", ")
|
|
103
|
+
}
|
|
104
|
+
if err := c.WriteValueExpr(arg); err != nil {
|
|
105
|
+
return true, fmt.Errorf("failed to write argument %d in min call: %w", i, err)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
c.tsw.WriteLiterally(")")
|
|
109
|
+
return true, nil
|
|
110
|
+
case "max":
|
|
111
|
+
if len(exp.Args) < 1 {
|
|
112
|
+
return true, errors.New("unhandled max call with no arguments")
|
|
113
|
+
}
|
|
114
|
+
c.tsw.WriteLiterally("Math.max(")
|
|
115
|
+
for i, arg := range exp.Args {
|
|
116
|
+
if i > 0 {
|
|
117
|
+
c.tsw.WriteLiterally(", ")
|
|
118
|
+
}
|
|
119
|
+
if err := c.WriteValueExpr(arg); err != nil {
|
|
120
|
+
return true, fmt.Errorf("failed to write argument %d in max call: %w", i, err)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
c.tsw.WriteLiterally(")")
|
|
124
|
+
return true, nil
|
|
125
|
+
case "clear":
|
|
126
|
+
if len(exp.Args) != 1 {
|
|
127
|
+
return true, errors.Errorf("unhandled clear call with incorrect number of arguments: %d != 1", len(exp.Args))
|
|
128
|
+
}
|
|
129
|
+
c.tsw.WriteLiterally("$.clear(")
|
|
130
|
+
if err := c.WriteValueExpr(exp.Args[0]); err != nil {
|
|
131
|
+
return true, fmt.Errorf("failed to write argument in clear call: %w", err)
|
|
132
|
+
}
|
|
133
|
+
c.tsw.WriteLiterally(")")
|
|
134
|
+
return true, nil
|
|
92
135
|
case "byte":
|
|
93
136
|
if len(exp.Args) != 1 {
|
|
94
137
|
return true, errors.Errorf("unhandled byte call with incorrect number of arguments: %d != 1", len(exp.Args))
|
|
@@ -119,13 +162,16 @@ func (c *GoToTSCompiler) writeAppendCall(exp *ast.CallExpr) error {
|
|
|
119
162
|
}
|
|
120
163
|
|
|
121
164
|
// The remaining arguments are the elements to append
|
|
122
|
-
|
|
165
|
+
elemsToAppend := exp.Args[1:]
|
|
166
|
+
for i, arg := range elemsToAppend {
|
|
123
167
|
if i > 0 || len(exp.Args) > 1 {
|
|
124
168
|
c.tsw.WriteLiterally(", ")
|
|
125
169
|
}
|
|
126
170
|
|
|
127
|
-
//
|
|
128
|
-
|
|
171
|
+
// Handle ellipsis (spread) for the last argument: append(slice, elems...)
|
|
172
|
+
// The ellipsis can only appear on the last argument, so check if this is the last element
|
|
173
|
+
isLastElement := i == len(elemsToAppend)-1
|
|
174
|
+
if exp.Ellipsis != token.NoPos && isLastElement {
|
|
129
175
|
// Check if the slice is []byte and the argument is a string
|
|
130
176
|
sliceType := c.pkg.TypesInfo.TypeOf(exp.Args[0])
|
|
131
177
|
argType := c.pkg.TypesInfo.TypeOf(arg)
|
|
@@ -141,6 +187,16 @@ func (c *GoToTSCompiler) writeAppendCall(exp *ast.CallExpr) error {
|
|
|
141
187
|
continue
|
|
142
188
|
}
|
|
143
189
|
}
|
|
190
|
+
|
|
191
|
+
// For other slice types with ellipsis, use spread operator
|
|
192
|
+
// append(slice, anotherSlice...) -> $.append(slice, ...(anotherSlice || []))
|
|
193
|
+
// The || [] handles the case where anotherSlice is null (nil in Go)
|
|
194
|
+
c.tsw.WriteLiterally("...(")
|
|
195
|
+
if err := c.WriteValueExpr(arg); err != nil {
|
|
196
|
+
return fmt.Errorf("failed to write spread argument in append call: %w", err)
|
|
197
|
+
}
|
|
198
|
+
c.tsw.WriteLiterally(" || [])")
|
|
199
|
+
continue
|
|
144
200
|
}
|
|
145
201
|
|
|
146
202
|
if err := c.WriteValueExpr(arg); err != nil {
|
|
@@ -18,14 +18,33 @@ func (c *GoToTSCompiler) writeNilConversion(exp *ast.CallExpr) (handled bool, er
|
|
|
18
18
|
return false, nil
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
//
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
// Check if this is actually a type conversion, not a method/function call
|
|
22
|
+
// For type conversions, exp.Fun is a type expression (IsType() is true)
|
|
23
|
+
// For method calls like s.ptr.Swap(nil), exp.Fun is a selector expression (IsType() is false)
|
|
24
|
+
if tv, ok := c.pkg.TypesInfo.Types[exp.Fun]; !ok || !tv.IsType() {
|
|
25
|
+
// This is not a type conversion, let the normal call handling proceed
|
|
26
|
+
return false, nil
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Get the type being converted to
|
|
30
|
+
if typ := c.pkg.TypesInfo.TypeOf(exp.Fun); typ != nil {
|
|
31
|
+
// For pointer types, create a typed nil that preserves type information
|
|
32
|
+
if ptrType, ok := typ.(*types.Pointer); ok {
|
|
33
|
+
// Use a qualifier that returns the package name for local types
|
|
34
|
+
// This matches Go's reflect output format (e.g., "main.Stringer")
|
|
35
|
+
qualifier := func(pkg *types.Package) string {
|
|
36
|
+
if pkg == nil {
|
|
37
|
+
return ""
|
|
38
|
+
}
|
|
39
|
+
return pkg.Name()
|
|
40
|
+
}
|
|
41
|
+
typeName := types.TypeString(ptrType, qualifier)
|
|
42
|
+
c.tsw.WriteLiterallyf("$.typedNil(%q)", typeName)
|
|
25
43
|
return true, nil
|
|
26
44
|
}
|
|
27
45
|
}
|
|
28
46
|
|
|
47
|
+
// For non-pointer types (or if type info is unavailable), use plain null
|
|
29
48
|
c.tsw.WriteLiterally("null")
|
|
30
49
|
return true, nil
|
|
31
50
|
}
|
|
@@ -141,8 +160,21 @@ func (c *GoToTSCompiler) writeStringConversion(exp *ast.CallExpr) error {
|
|
|
141
160
|
|
|
142
161
|
// Handle direct string(int32) conversion
|
|
143
162
|
if tv, ok := c.pkg.TypesInfo.Types[arg]; ok {
|
|
144
|
-
// Case 3a: Argument is already a string - no-op
|
|
163
|
+
// Case 3a: Argument is already a string - no-op (unless it's a named type with toString)
|
|
145
164
|
if c.isStringType(tv.Type) {
|
|
165
|
+
// Check if this is a named type from the reflect package (like StructTag)
|
|
166
|
+
// which is implemented as a class in TypeScript with a toString() method
|
|
167
|
+
if namedType, isNamed := tv.Type.(*types.Named); isNamed {
|
|
168
|
+
obj := namedType.Obj()
|
|
169
|
+
if obj != nil && obj.Pkg() != nil && obj.Pkg().Path() == "reflect" && obj.Name() == "StructTag" {
|
|
170
|
+
// Call toString() for reflect.StructTag
|
|
171
|
+
if err := c.WriteValueExpr(arg); err != nil {
|
|
172
|
+
return fmt.Errorf("failed to write argument for string(reflect.StructTag) conversion: %w", err)
|
|
173
|
+
}
|
|
174
|
+
c.tsw.WriteLiterally(".toString()")
|
|
175
|
+
return nil
|
|
176
|
+
}
|
|
177
|
+
}
|
|
146
178
|
// Translate string(stringValue) to stringValue (no-op)
|
|
147
179
|
if err := c.WriteValueExpr(arg); err != nil {
|
|
148
180
|
return fmt.Errorf("failed to write argument for string(string) no-op conversion: %w", err)
|
package/compiler/expr-call.go
CHANGED
|
@@ -61,7 +61,8 @@ func (c *GoToTSCompiler) WriteCallExpr(exp *ast.CallExpr) error {
|
|
|
61
61
|
// For built-ins that don't return early, write the arguments
|
|
62
62
|
if funIdent.String() != "new" && funIdent.String() != "close" && funIdent.String() != "make" &&
|
|
63
63
|
funIdent.String() != "string" && funIdent.String() != "append" && funIdent.String() != "byte" &&
|
|
64
|
-
funIdent.String() != "int"
|
|
64
|
+
funIdent.String() != "int" && funIdent.String() != "min" && funIdent.String() != "max" &&
|
|
65
|
+
funIdent.String() != "clear" {
|
|
65
66
|
return c.writeCallArguments(exp)
|
|
66
67
|
}
|
|
67
68
|
return nil
|
|
@@ -117,14 +118,26 @@ func (c *GoToTSCompiler) WriteCallExpr(exp *ast.CallExpr) error {
|
|
|
117
118
|
}
|
|
118
119
|
c.tsw.WriteLiterally(")")
|
|
119
120
|
} else {
|
|
121
|
+
// Check if this is a function call that returns a function (e.g., simpleIterator(m)())
|
|
122
|
+
// and if the inner call is async, wrap it in parentheses
|
|
123
|
+
innerCallExpr, isCallExpr := expFun.(*ast.CallExpr)
|
|
124
|
+
needsParens := isCallExpr && c.isCallExprAsync(innerCallExpr)
|
|
125
|
+
|
|
126
|
+
if needsParens {
|
|
127
|
+
c.tsw.WriteLiterally("(")
|
|
128
|
+
}
|
|
129
|
+
|
|
120
130
|
// Not an identifier (e.g., method call on a value, function call result)
|
|
121
131
|
if err := c.WriteValueExpr(expFun); err != nil {
|
|
122
132
|
return fmt.Errorf("failed to write method expression in call: %w", err)
|
|
123
133
|
}
|
|
124
134
|
|
|
125
|
-
|
|
135
|
+
if needsParens {
|
|
136
|
+
c.tsw.WriteLiterally(")")
|
|
137
|
+
}
|
|
138
|
+
|
|
126
139
|
// Add non-null assertion since the returned function could be null
|
|
127
|
-
if
|
|
140
|
+
if isCallExpr {
|
|
128
141
|
c.tsw.WriteLiterally("!")
|
|
129
142
|
} else {
|
|
130
143
|
c.addNonNullAssertion(expFun)
|