Documentation
¶
Index ¶
- func ComputeModulePath(outputRoot, goPkg string) string
- func GoBuiltinToTypescript(typeName string) (string, bool)
- func TokenToTs(tok token.Token) (string, bool)
- func TranslateGoFilePathToTypescriptFilePath(goPkgPath, goCodeFilename string) string
- type Analysis
- func (a *Analysis) GetFunctionTypeInfo(node ast.Node) *ReflectedFunctionInfo
- func (a *Analysis) GetIdentifierMapping(ident *ast.Ident) string
- func (a *Analysis) GetReceiverMapping(funcDecl *ast.FuncDecl) string
- func (a *Analysis) GetShadowingInfo(node ast.Node) *ShadowingInfo
- func (a *Analysis) HasVariableShadowing(node ast.Node) bool
- func (a *Analysis) IsAsyncFunc(obj types.Object) bool
- func (a *Analysis) IsFuncLitAsync(funcLit *ast.FuncLit) bool
- func (a *Analysis) IsInAsyncFunction(node ast.Node) bool
- func (a *Analysis) IsInterfaceMethodAsync(interfaceType *types.Interface, methodName string) bool
- func (a *Analysis) IsLocalMethodAsync(pkgPath, receiverType, methodName string) bool
- func (a *Analysis) IsMethodAsync(pkgPath, typeName, methodName string) bool
- func (a *Analysis) IsMethodValue(node *ast.SelectorExpr) bool
- func (a *Analysis) IsNamedBasicType(t types.Type) bool
- func (a *Analysis) IsReceiverUsed(obj types.Object) bool
- func (a *Analysis) LoadPackageMetadata()
- func (a *Analysis) MarkFunctionForReflection(node ast.Node, funcType *types.Signature)
- func (a *Analysis) MustBeAsyncDueToInterface(structType *types.Named, methodName string) bool
- func (a *Analysis) NeedsDefer(node ast.Node) bool
- func (a *Analysis) NeedsReflectionMetadata(node ast.Node) bool
- func (a *Analysis) NeedsVarRef(obj types.Object) bool
- func (a *Analysis) NeedsVarRefAccess(obj types.Object) bool
- type AssignmentInfo
- type AssignmentType
- type CompilationResult
- type Compiler
- type Config
- type FileCompiler
- type FunctionInfo
- type FunctionTypeInfo
- type GoToTSCompiler
- func (c *GoToTSCompiler) WriteArrayType(t *types.Array)
- func (c *GoToTSCompiler) WriteBasicLit(exp *ast.BasicLit)
- func (c *GoToTSCompiler) WriteBasicType(t *types.Basic)
- func (c *GoToTSCompiler) WriteBinaryExpr(exp *ast.BinaryExpr) error
- func (c *GoToTSCompiler) WriteCallExpr(exp *ast.CallExpr) error
- func (c *GoToTSCompiler) WriteCallExprMake(exp *ast.CallExpr) error
- func (c *GoToTSCompiler) WriteCaseClause(exp *ast.CaseClause) error
- func (c *GoToTSCompiler) WriteChannelType(t *types.Chan)
- func (c *GoToTSCompiler) WriteCompositeLit(exp *ast.CompositeLit) error
- func (c *GoToTSCompiler) WriteDecls(decls []ast.Decl) error
- func (c *GoToTSCompiler) WriteDoc(doc *ast.CommentGroup)
- func (c *GoToTSCompiler) WriteField(field *ast.Field, isArguments bool)
- func (c *GoToTSCompiler) WriteFieldList(a *ast.FieldList, isArguments bool)
- func (c *GoToTSCompiler) WriteFuncDeclAsFunction(decl *ast.FuncDecl) error
- func (c *GoToTSCompiler) WriteFuncDeclAsMethod(decl *ast.FuncDecl) error
- func (c *GoToTSCompiler) WriteFuncLitValue(exp *ast.FuncLit) error
- func (c *GoToTSCompiler) WriteFuncType(exp *ast.FuncType, isAsync bool)
- func (c *GoToTSCompiler) WriteGoType(typ types.Type, context GoTypeContext)
- func (c *GoToTSCompiler) WriteIdent(exp *ast.Ident, accessVarRefedValue bool)
- func (c *GoToTSCompiler) WriteImportSpec(a *ast.ImportSpec)
- func (c *GoToTSCompiler) WriteIndexExpr(exp *ast.IndexExpr) error
- func (c *GoToTSCompiler) WriteIndexListExpr(exp *ast.IndexListExpr) error
- func (c *GoToTSCompiler) WriteInterfaceType(t *types.Interface, astNode *ast.InterfaceType)
- func (c *GoToTSCompiler) WriteInterfaceTypeSpec(a *ast.TypeSpec, t *ast.InterfaceType) error
- func (c *GoToTSCompiler) WriteKeyValueExpr(exp *ast.KeyValueExpr) error
- func (c *GoToTSCompiler) WriteMapType(t *types.Map)
- func (c *GoToTSCompiler) WriteNamedType(t *types.Named)
- func (c *GoToTSCompiler) WriteNamedTypeWithMethods(a *ast.TypeSpec) error
- func (c *GoToTSCompiler) WritePointerType(t *types.Pointer, context GoTypeContext)
- func (c *GoToTSCompiler) WriteSelectorExpr(exp *ast.SelectorExpr) error
- func (c *GoToTSCompiler) WriteSignatureType(t *types.Signature)
- func (c *GoToTSCompiler) WriteSliceExpr(exp *ast.SliceExpr) error
- func (c *GoToTSCompiler) WriteSliceType(t *types.Slice)
- func (c *GoToTSCompiler) WriteSpec(a ast.Spec) error
- func (c *GoToTSCompiler) WriteStarExpr(exp *ast.StarExpr) error
- func (c *GoToTSCompiler) WriteStmt(a ast.Stmt) error
- func (c *GoToTSCompiler) WriteStmtAssign(exp *ast.AssignStmt) error
- func (c *GoToTSCompiler) WriteStmtBlock(exp *ast.BlockStmt, suppressNewline bool) error
- func (c *GoToTSCompiler) WriteStmtBranch(stmt *ast.BranchStmt) error
- func (c *GoToTSCompiler) WriteStmtDecl(stmt *ast.DeclStmt) error
- func (c *GoToTSCompiler) WriteStmtDefer(exp *ast.DeferStmt) error
- func (c *GoToTSCompiler) WriteStmtExpr(exp *ast.ExprStmt) error
- func (c *GoToTSCompiler) WriteStmtFor(exp *ast.ForStmt) error
- func (c *GoToTSCompiler) WriteStmtForInit(stmt ast.Stmt) error
- func (c *GoToTSCompiler) WriteStmtForPost(stmt ast.Stmt) error
- func (c *GoToTSCompiler) WriteStmtGo(exp *ast.GoStmt) error
- func (c *GoToTSCompiler) WriteStmtIf(exp *ast.IfStmt) error
- func (c *GoToTSCompiler) WriteStmtIncDec(stmt *ast.IncDecStmt) error
- func (c *GoToTSCompiler) WriteStmtLabeled(stmt *ast.LabeledStmt) error
- func (c *GoToTSCompiler) WriteStmtRange(exp *ast.RangeStmt) error
- func (c *GoToTSCompiler) WriteStmtReturn(exp *ast.ReturnStmt) error
- func (c *GoToTSCompiler) WriteStmtSelect(exp *ast.SelectStmt) error
- func (c *GoToTSCompiler) WriteStmtSend(exp *ast.SendStmt) error
- func (c *GoToTSCompiler) WriteStmtSwitch(exp *ast.SwitchStmt) error
- func (c *GoToTSCompiler) WriteStmtTypeSwitch(stmt *ast.TypeSwitchStmt) error
- func (c *GoToTSCompiler) WriteStructType(t *types.Struct)
- func (c *GoToTSCompiler) WriteStructTypeSpec(a *ast.TypeSpec, t *ast.StructType) error
- func (c *GoToTSCompiler) WriteTypeAssertExpr(exp *ast.TypeAssertExpr) error
- func (c *GoToTSCompiler) WriteTypeConstraint(constraint ast.Expr)
- func (c *GoToTSCompiler) WriteTypeExpr(a ast.Expr)
- func (c *GoToTSCompiler) WriteTypeParameters(typeParams *ast.FieldList)
- func (c *GoToTSCompiler) WriteTypeSpec(a *ast.TypeSpec) error
- func (c *GoToTSCompiler) WriteUnaryExpr(exp *ast.UnaryExpr) error
- func (c *GoToTSCompiler) WriteValueExpr(a ast.Expr) error
- func (c *GoToTSCompiler) WriteValueSpec(a *ast.ValueSpec) error
- func (c *GoToTSCompiler) WriteVarRefedValue(expr ast.Expr) error
- func (c *GoToTSCompiler) WriteZeroValueForType(typ any)
- type GoTypeContext
- type GsMetadata
- type GsPackageMetadata
- type ImplementationInfo
- type InterfaceMethodKey
- type MethodKey
- type NodeInfo
- type PackageAnalysis
- type PackageCompiler
- type ReflectedFunctionInfo
- type ShadowingInfo
- type TSCodeWriter
- func (w *TSCodeWriter) Indent(count int)
- func (w *TSCodeWriter) WriteCommentInline(commentText string)
- func (w *TSCodeWriter) WriteCommentInlinef(format string, args ...any)
- func (w *TSCodeWriter) WriteCommentLine(commentText string)
- func (w *TSCodeWriter) WriteCommentLinef(format string, args ...any)
- func (w *TSCodeWriter) WriteImport(symbolName, importPath string)
- func (w *TSCodeWriter) WriteLine(line string)
- func (w *TSCodeWriter) WriteLinePreamble()
- func (w *TSCodeWriter) WriteLinef(line string, args ...any)
- func (w *TSCodeWriter) WriteLiterally(literal string)
- func (w *TSCodeWriter) WriteLiterallyf(literal string, args ...any)
- func (w *TSCodeWriter) WriteSectionTail()
- type VariableUsageInfo
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ComputeModulePath ¶
ComputeModulePath computes the root of the output typescript module.
func GoBuiltinToTypescript ¶ added in v0.0.15
GoBuiltinToTypescript translates a Go built-in primitive type name (string) to its TypeScript equivalent. It uses the `goToTypescriptPrimitives` map for the conversion. It returns the TypeScript type name and `true` if the Go type name is found in the map. Otherwise, it returns an empty string and `false`. This function only handles primitive types listed in the map; composite types or custom types are not processed here.
func TokenToTs ¶ added in v0.0.15
TokenToTs converts a Go `token.Token` (representing an operator or punctuation) into its corresponding TypeScript string representation using the `tokenMap`. It returns the TypeScript string and `true` if the token is found in the map. Otherwise, it returns an empty string and `false`. This function is essential for translating expressions involving operators (e.g., arithmetic, logical, assignment operators).
func TranslateGoFilePathToTypescriptFilePath ¶
TranslateGoFilePathToTypescriptFilePath converts the go package path and typescript filename to output path within the typescript output dir
Types ¶
type Analysis ¶ added in v0.0.15
type Analysis struct { // VariableUsage tracks how variables are assigned and used, particularly for pointer analysis. // The key is the variable's types.Object. VariableUsage map[types.Object]*VariableUsageInfo // Imports stores the imports for the file Imports map[string]*fileImport // Cmap stores the comment map for the file Cmap ast.CommentMap // FunctionData consolidates function-related tracking into one map FunctionData map[types.Object]*FunctionInfo // NodeData consolidates node-related tracking into one map NodeData map[ast.Node]*NodeInfo // Keep specialized maps that serve different purposes // FuncLitData tracks function literal specific data since they don't have types.Object FuncLitData map[*ast.FuncLit]*FunctionInfo // ReflectedFunctions tracks functions that need reflection type metadata ReflectedFunctions map[ast.Node]*ReflectedFunctionInfo // FunctionAssignments tracks which function literals are assigned to which variables FunctionAssignments map[types.Object]ast.Node // NamedBasicTypes tracks types that should be implemented as type aliases with standalone functions // This includes named types with basic underlying types (like uint32, string) that have methods NamedBasicTypes map[types.Type]bool // AllPackages stores all loaded packages for dependency analysis // Key: package path, Value: package data AllPackages map[string]*packages.Package // InterfaceImplementations tracks which struct types implement which interface methods // This is used to determine interface method async status based on implementations InterfaceImplementations map[InterfaceMethodKey][]ImplementationInfo // InterfaceMethodAsyncStatus caches the async status determination for interface methods // This is computed once during analysis and reused during code generation InterfaceMethodAsyncStatus map[InterfaceMethodKey]bool // MethodAsyncStatus stores the async status of all methods analyzed // This is computed once during analysis and reused during code generation MethodAsyncStatus map[MethodKey]bool }
Analysis holds information gathered during the analysis phase of the Go code compilation. This data is used to make decisions about how to generate TypeScript code. Analysis is read-only after being built and should not be modified during code generation.
func AnalyzePackageFiles ¶ added in v0.0.50
AnalyzePackageFiles analyzes all Go source files in a package and populates the Analysis struct with information that will be used during code generation to properly handle pointers, variables that need varRefing, receiver usage, etc. This replaces the old file-by-file analysis.
func NewAnalysis ¶ added in v0.0.15
NewAnalysis creates a new Analysis instance.
func (*Analysis) GetFunctionTypeInfo ¶ added in v0.0.38
func (a *Analysis) GetFunctionTypeInfo(node ast.Node) *ReflectedFunctionInfo
GetFunctionTypeInfo returns the function type information for reflection
func (*Analysis) GetIdentifierMapping ¶ added in v0.0.49
GetIdentifierMapping returns the replacement name for an identifier
func (*Analysis) GetReceiverMapping ¶ added in v0.0.49
GetReceiverMapping returns the receiver variable mapping for a function declaration
func (*Analysis) GetShadowingInfo ¶ added in v0.0.42
func (a *Analysis) GetShadowingInfo(node ast.Node) *ShadowingInfo
GetShadowingInfo returns the variable shadowing information for the given node
func (*Analysis) HasVariableShadowing ¶ added in v0.0.42
HasVariableShadowing returns whether the given node has variable shadowing issues
func (*Analysis) IsAsyncFunc ¶ added in v0.0.15
IsAsyncFunc returns whether the given object represents an async function.
func (*Analysis) IsFuncLitAsync ¶ added in v0.0.15
IsFuncLitAsync checks if a function literal is async based on our analysis.
func (*Analysis) IsInAsyncFunction ¶ added in v0.0.15
IsInAsyncFunction returns whether the given node is inside an async function.
func (*Analysis) IsInterfaceMethodAsync ¶ added in v0.0.50
IsInterfaceMethodAsync determines if an interface method should be async based on its implementations
func (*Analysis) IsLocalMethodAsync ¶ added in v0.0.52
IsLocalMethodAsync checks if a local method is async using pre-computed analysis
func (*Analysis) IsMethodAsync ¶ added in v0.0.27
IsMethodAsync checks if a method call is async based on package metadata
func (*Analysis) IsMethodValue ¶ added in v0.0.29
func (a *Analysis) IsMethodValue(node *ast.SelectorExpr) bool
IsMethodValue returns whether the given SelectorExpr node is a method value that needs binding.
func (*Analysis) IsNamedBasicType ¶ added in v0.0.50
IsNamedBasicType returns whether the given type should be implemented as a type alias with standalone functions This applies to named types with basic underlying types (like uint32, string, etc.) that have methods It excludes struct types, which should remain as classes
func (*Analysis) IsReceiverUsed ¶ added in v0.0.45
func (*Analysis) LoadPackageMetadata ¶ added in v0.0.27
func (a *Analysis) LoadPackageMetadata()
LoadPackageMetadata loads metadata from gs packages using embedded JSON files
func (*Analysis) MarkFunctionForReflection ¶ added in v0.0.38
MarkFunctionForReflection marks a function node as needing reflection support
func (*Analysis) MustBeAsyncDueToInterface ¶ added in v0.0.50
MustBeAsyncDueToInterface checks if a struct method must be async due to interface constraints
func (*Analysis) NeedsDefer ¶ added in v0.0.15
NeedsDefer returns whether the given node needs defer handling.
func (*Analysis) NeedsReflectionMetadata ¶ added in v0.0.38
NeedsReflectionMetadata returns whether the given function node needs reflection type metadata
func (*Analysis) NeedsVarRef ¶ added in v0.0.24
NeedsVarRef returns whether the given object needs to be variable referenced. This is true when the object's address is taken (e.g., &myVar) in the analyzed code. Variables that have their address taken must be wrapped in VarRef to maintain identity.
func (*Analysis) NeedsVarRefAccess ¶ added in v0.0.24
NeedsVarRefAccess returns whether accessing the given object requires '.value' access in TypeScript. This is more nuanced than NeedsVarRef and considers both direct variable references and pointers that may point to variable-referenced values.
Examples:
- Direct variable reference (NeedsVarRef = true): Example: let x = $.varRef(10) => x.value
- Pointer pointing to a variable-referenced value: Example: let p: VarRef<number> | null = x => p!.value
- Regular pointer (NeedsVarRef = false, but points to variable reference): Example: let q = x => q!.value (where x is VarRef)
type AssignmentInfo ¶ added in v0.0.15
type AssignmentInfo struct { Object types.Object // The source or destination variable object Type AssignmentType // The type of assignment involved }
AssignmentInfo stores information about a single assignment source or destination.
type AssignmentType ¶ added in v0.0.15
type AssignmentType int
AssignmentType indicates how a variable's value was assigned or used.
const ( // DirectAssignment represents a direct value copy (e.g., x = y) DirectAssignment AssignmentType = iota // AddressOfAssignment represents taking the address (e.g., p = &y) // or assigning to a dereferenced pointer (*p = y) - indicating the pointer p is used. AddressOfAssignment )
type CompilationResult ¶ added in v0.0.25
type CompilationResult struct { // CompiledPackages contains the package paths of all packages that were actually compiled to TypeScript CompiledPackages []string // CopiedPackages contains the package paths of all packages that were copied from handwritten sources CopiedPackages []string // OriginalPackages contains the package paths that were explicitly requested for compilation OriginalPackages []string }
CompilationResult contains information about what was compiled
type Compiler ¶
type Compiler struct {
// contains filtered or unexported fields
}
Compiler is the root compiler for a project. It orchestrates the loading and compilation of Go packages into TypeScript. It holds project-wide configuration and uses `golang.org/x/tools/go/packages` to load Go package information.
func NewCompiler ¶
NewCompiler builds a new Compiler instance. It takes a compiler configuration, a logger entry, and an optional `packages.Config` for loading Go packages. If `opts` is nil, default options are used, configured for JavaScript/WebAssembly (js/wasm) target and to load comprehensive package information (types, syntax, etc.). It validates the provided configuration before creating the compiler.
func (*Compiler) CompilePackages ¶
func (c *Compiler) CompilePackages(ctx context.Context, patterns ...string) (*CompilationResult, error)
CompilePackages loads Go packages based on the provided patterns and then compiles each loaded package into TypeScript. It uses the context for cancellation and applies the compiler's configured options during package loading. For each successfully loaded package, it creates a `PackageCompiler` and invokes its `Compile` method. If c.config.AllDependencies is true, it will also compile all dependencies of the requested packages, including standard library dependencies. Returns a CompilationResult with information about what was compiled.
func (*Compiler) ReadGsPackageMetadata ¶ added in v0.0.40
func (c *Compiler) ReadGsPackageMetadata(gsSourcePath string) (*GsPackageMetadata, error)
ReadGsPackageMetadata reads dependency metadata from meta.json file in a gs/ package
type Config ¶
type Config struct { // Dir is the working directory for the compiler. If empty, uses the current working directory. Dir string // OutputPath is the output path root. OutputPath string // BuildFlags are the Go build flags (tags) to use during analysis. BuildFlags []string // AllDependencies controls whether to compile all dependencies of the requested packages. // If true, all dependencies will be compiled; if false, only the requested packages are compiled. AllDependencies bool // DisableEmitBuiltin controls whether to emit builtin packages when they are referenced. // If true, builtin packages will not be emitted; if false, they will be emitted if referenced. // Default is false (emit builtin packages). DisableEmitBuiltin bool // contains filtered or unexported fields }
Config is the configuration for the compiler Dir is the working directory for the compiler. If empty, uses the current working directory.
type FileCompiler ¶
type FileCompiler struct { Analysis *Analysis PackageAnalysis *PackageAnalysis // contains filtered or unexported fields }
FileCompiler is responsible for compiling a single Go source file (`ast.File`) into a corresponding TypeScript file. It manages the output file creation, initializes the `TSCodeWriter` for TypeScript code generation, and uses a `GoToTSCompiler` to translate Go declarations and statements.
func NewFileCompiler ¶
func NewFileCompiler( compilerConf *Config, pkg *packages.Package, astFile *ast.File, fullPath string, analysis *Analysis, packageAnalysis *PackageAnalysis, ) (*FileCompiler, error)
NewFileCompiler creates a new `FileCompiler` for a specific Go file. It takes the global compiler configuration, the Go package information, the AST of the file, its full path, and the pre-computed analysis results. This setup provides all necessary context for translating the file.
func (*FileCompiler) Compile ¶
func (c *FileCompiler) Compile(ctx context.Context) error
Compile generates the TypeScript code for the Go file. It determines the output TypeScript file path, creates the necessary directories, and opens the output file. It then initializes a `TSCodeWriter` and a `GoToTSCompiler`. A standard import for the `@goscript/builtin` runtime (aliased as `$`) is added, followed by the translation of all top-level declarations in the Go file.
type FunctionInfo ¶ added in v0.0.23
FunctionInfo consolidates function-related tracking data.
type FunctionTypeInfo ¶ added in v0.0.38
type FunctionTypeInfo struct { Params []types.Type // Parameter types Results []types.Type // Return types Variadic bool // Whether the function is variadic }
FunctionTypeInfo represents Go function type information for reflection
type GoToTSCompiler ¶
type GoToTSCompiler struct {
// contains filtered or unexported fields
}
GoToTSCompiler is the core component responsible for translating Go AST nodes and type information into TypeScript code. It uses a `TSCodeWriter` to output the generated TypeScript and relies on `Analysis` data to make informed decisions about code generation (e.g., varRefing, async behavior).
func NewGoToTSCompiler ¶
func NewGoToTSCompiler(tsw *TSCodeWriter, pkg *packages.Package, analysis *Analysis) *GoToTSCompiler
It initializes the compiler with a `TSCodeWriter` for output, Go package information (`packages.Package`), and pre-computed analysis results (`Analysis`) to guide the translation process.
func (*GoToTSCompiler) WriteArrayType ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteArrayType(t *types.Array)
WriteArrayType translates a Go array type ([N]T) to its TypeScript equivalent. It generates T_ts[], where T_ts is the translated element type.
func (*GoToTSCompiler) WriteBasicLit ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteBasicLit(exp *ast.BasicLit)
WriteBasicLit translates a Go basic literal (`ast.BasicLit`) into its TypeScript equivalent.
- Character literals (e.g., `'a'`, `'\n'`) are translated to their numeric Unicode code point (e.g., `97`, `10`). Escape sequences are handled.
- Integer, float, imaginary, and string literals are written directly as their `exp.Value` string, which typically corresponds to valid TypeScript syntax (e.g., `123`, `3.14`, `"hello"`). Imaginary literals might need special handling if they are to be fully supported beyond direct string output.
- Legacy octal literals (e.g., `0777`) are converted to modern TypeScript octal syntax (e.g., `0o777`) to avoid ES module compatibility issues.
func (*GoToTSCompiler) WriteBasicType ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteBasicType(t *types.Basic)
WriteBasicType translates a Go basic type (primitives like int, string, bool) to its TypeScript equivalent. It handles untyped constants by mapping them to appropriate TypeScript types (boolean, number, string, null) and uses GoBuiltinToTypescript for typed primitives.
func (*GoToTSCompiler) WriteBinaryExpr ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteBinaryExpr(exp *ast.BinaryExpr) error
WriteBinaryExpr translates a Go binary expression (`ast.BinaryExpr`) into its TypeScript equivalent. It handles several cases:
- Channel send (`ch <- val`): Becomes `await ch.send(val)`.
- Nil comparison for pointers (`ptr == nil` or `ptr != nil`): Compares the pointer (which may be a varRef object or `null`) directly to `null` using the translated operator (`==` or `!=`).
- Pointer comparison (non-nil, `ptr1 == ptr2` or `ptr1 != ptr2`): Compares the varRef objects directly using strict equality (`===` or `!==`).
- Bitwise operations (`&`, `|`, `^`, `<<`, `>>`, `&^`): The expression is wrapped in parentheses `()` to ensure correct precedence in TypeScript, and operators are mapped (e.g., `&^` might need special handling or is mapped to a runtime helper).
- Other binary operations (arithmetic, logical, comparison): Operands are translated using `WriteValueExpr`, and the operator is mapped to its TypeScript equivalent using `TokenToTs`.
Unhandled operators result in a comment and a placeholder.
func (*GoToTSCompiler) WriteCallExpr ¶
func (c *GoToTSCompiler) WriteCallExpr(exp *ast.CallExpr) error
WriteCallExpr translates a Go function call expression (`ast.CallExpr`) into its TypeScript equivalent. It handles several Go built-in functions specially: - `println(...)` becomes `console.log(...)`. - `panic(...)` becomes `$.panic(...)`. - `len(arg)` becomes `$.len(arg)`. - `cap(arg)` becomes `$.cap(arg)`. - `delete(m, k)` becomes `$.deleteMapEntry(m, k)`. - `make(chan T, size)` becomes `$.makeChannel<T_ts>(size, zeroValueForT)`. - `make(map[K]V)` becomes `$.makeMap<K_ts, V_ts>()`. - `make([]T, len, cap)` becomes `$.makeSlice<T_ts>(len, cap)`. - `make([]byte, len, cap)` becomes `new Uint8Array(len)`. - `string(runeVal)` becomes `$.runeOrStringToString(runeVal)`. - `string([]runeVal)` becomes `$.runesToString(sliceVal)`. - `string([]byteVal)` becomes `$.bytesToString(sliceVal)`. - `[]rune(stringVal)` becomes `$.stringToRunes(stringVal)". - `[]byte(stringVal)` becomes `$.stringToBytes(stringVal)`. - `close(ch)` becomes `ch.close()`. - `append(slice, elems...)` becomes `$.append(slice, elems...)`. - `byte(val)` becomes `$.byte(val)`. For other function calls:
- If the `Analysis` data indicates the function is asynchronous (e.g., due to channel operations or `go`/`defer` usage within it), the call is prefixed with `await`.
- Otherwise, it's translated as a standard TypeScript function call: `funcName(arg1, arg2)`.
Arguments are recursively translated using `WriteValueExpr`.
func (*GoToTSCompiler) WriteCallExprMake ¶ added in v0.0.46
func (c *GoToTSCompiler) WriteCallExprMake(exp *ast.CallExpr) error
WriteCallExprMake handles make() function calls and translates them to TypeScript. It handles channel, map, and slice creation with different type patterns including: - Channel creation with different directions - Map creation for various type patterns - Slice creation with special handling for []byte, generic types, named types, instantiated generics, and selector expressions
func (*GoToTSCompiler) WriteCaseClause ¶
func (c *GoToTSCompiler) WriteCaseClause(exp *ast.CaseClause) error
WriteCaseClause translates a Go `case` clause (`ast.CaseClause`) from within a `switch` statement into its TypeScript `case` or `default` equivalent.
- If `exp.List` is nil, it's a `default` case, written as `default:`.
- If `exp.List` is not nil, it's a `case` with one or more match expressions. It's written as `case expr1_ts, expr2_ts, ... :`. (Note: Go's `case` doesn't allow multiple expressions this way, but TypeScript does. This code implies Go's fallthrough is not directly modeled here but rather by explicit `break`s, and each Go `case` becomes one or more TS `case` labels if needed, though current implementation writes them comma-separated which is valid TS syntax).
- The body of the case (`exp.Body`) is translated statement by statement using `WriteStmt`.
- A `break;` statement is automatically added at the end of the TypeScript case body, because Go `switch` cases have implicit breaks, whereas TypeScript cases fall through by default.
func (*GoToTSCompiler) WriteChannelType ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteChannelType(t *types.Chan)
WriteChannelType translates a Go channel type (chan T) to its TypeScript equivalent. It generates $.Channel<T_ts> | null, where T_ts is the translated element type. Channels are nilable in Go, so they are represented as nullable types in TypeScript.
func (*GoToTSCompiler) WriteCompositeLit ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteCompositeLit(exp *ast.CompositeLit) error
WriteCompositeLit translates a Go composite literal (ast.CompositeLit) into its TypeScript equivalent.
It handles several types of composite literals:
- Map literals (e.g., `map[K]V{k1: v1}`): Translated to `new Map([[k1_ts, v1_ts]])`. Values are processed by `WriteVarRefedValue`.
- Array/Slice literals (e.g., `[]T{e1, e2}`, `[N]T{idx: val}`):
- For `[]byte{...}`, translated to `new Uint8Array([...])`.
- For other `[]T` or `[N]T`, translated using the `$.arrayToSlice<T_ts>([...])` runtime helper. It handles both keyed and unkeyed elements, infers length if necessary, and uses zero values for uninitialized array elements. Multi-dimensional arrays/slices pass a depth parameter to `$.arrayToSlice`. Element values are processed by `WriteVarRefedValue`.
- Struct literals:
- Named structs (e.g., `MyStruct{F: v}` or `&MyStruct{F: v}`): Translated to `new MyStruct_ts({ F: v_ts, ... })`. The constructor typically uses an `_init` method.
- Anonymous structs (e.g., `struct{F int}{F: v}`): Translated to TypeScript object literals `{ F: v_ts, ... }`. It processes keyed elements (`FieldName: Value`) and unkeyed elements (for anonymous structs or arrays). Field values are processed by `WriteVarRefedValue`. Embedded struct fields are initialized, and explicit initializers for embedded structs (e.g. `Outer{InnerField: InnerType{...}}`) are handled. The function uses `c.analysis` to determine correct value access (e.g., `.value` for var-refed fields).
func (*GoToTSCompiler) WriteDecls ¶
func (c *GoToTSCompiler) WriteDecls(decls []ast.Decl) error
WriteDecls iterates through a slice of Go top-level declarations (`ast.Decl`) and translates each one into its TypeScript equivalent. It distinguishes between: - Function declarations (`ast.FuncDecl`):
- If it's a regular function (no receiver), it delegates to `WriteFuncDeclAsFunction`.
- Methods (with receivers) are handled within `WriteTypeSpec` when their associated struct/type is defined, so they are skipped here.
- General declarations (`ast.GenDecl`), which can contain imports, constants, variables, or type definitions: It iterates through `d.Specs` and calls `WriteSpec` for each specification.
Type declarations are sorted by dependencies to ensure referenced types are defined before types that reference them, avoiding initialization order issues. A newline is added after each processed declaration or spec group for readability. Unknown declaration types result in a printed diagnostic message.
func (*GoToTSCompiler) WriteDoc ¶
func (c *GoToTSCompiler) WriteDoc(doc *ast.CommentGroup)
WriteDoc translates a Go comment group (`ast.CommentGroup`) into TypeScript comments, preserving the original style (line `//` or block `/* ... */`). - If `doc` is nil, it does nothing. - It iterates through each `ast.Comment` in the group. - If a comment starts with `//`, it's written as a TypeScript line comment. - If a comment starts with `/*`, it's written as a TypeScript block comment:
- Single-line block comments (`/* comment */`) are kept on one line.
- Multi-line block comments are formatted with `/*` on its own line, each content line prefixed with ` * `, and ` */` on its own line.
This function helps maintain documentation and explanatory comments from the Go source in the generated TypeScript code.
func (*GoToTSCompiler) WriteField ¶
func (c *GoToTSCompiler) WriteField(field *ast.Field, isArguments bool)
WriteField translates a single Go field (`ast.Field`) from a field list (e.g., in a struct type or function signature) into its TypeScript representation. - If `isArguments` is false (struct field):
- Documentation comments (`field.Doc`, `field.Comment`) are preserved.
- If the field is anonymous (embedded), it's skipped as promotions are handled elsewhere (e.g., during struct class generation).
- For named fields, it writes `public fieldName: FieldType_ts`. The field name retains its Go casing. The type is translated using `WriteGoType`.
- Go struct tags (`field.Tag`) are written as a trailing comment.
- If `isArguments` is true (function parameter):
- It writes the parameter name (retaining Go casing). The type is handled by the caller (`WriteFieldList`).
This function is used by `WriteFieldList` to process individual items within parameter lists and struct field definitions.
func (*GoToTSCompiler) WriteFieldList ¶
func (c *GoToTSCompiler) WriteFieldList(a *ast.FieldList, isArguments bool)
WriteFieldList translates a Go field list (`ast.FieldList`), which can represent function parameters, function results, or struct fields, into its TypeScript equivalent.
- If `isArguments` is true (for function parameters/results): It iterates through `a.List`, writing each field as `name: type`. Parameter names and types are written using `WriteField` and `WriteGoType` respectively. Multiple parameters are comma-separated.
- If `isArguments` is false (for struct fields): It writes an opening brace `{`, indents, then writes each field definition using `WriteField`, followed by a closing brace `}`. If the field list is empty or nil, it simply writes `{}`.
This function is a key part of generating TypeScript type signatures for functions and interfaces, as well as struct type definitions.
func (*GoToTSCompiler) WriteFuncDeclAsFunction ¶
func (c *GoToTSCompiler) WriteFuncDeclAsFunction(decl *ast.FuncDecl) error
WriteFuncDeclAsFunction translates a Go function declaration (`ast.FuncDecl`) that does not have a receiver (i.e., it's a regular function, not a method) into a TypeScript function.
- Go documentation comments (`decl.Doc`) are preserved.
- If the Go function is exported (name starts with an uppercase letter) or is the `main` function, the `export` keyword is added to the TypeScript output.
- If the `Analysis` data indicates the function is asynchronous, the `async` keyword is prepended.
- The function signature (parameters and return type) is translated using `WriteFuncType`, passing the `isAsync` status.
- The function body (`decl.Body`) is translated using `WriteStmt`.
This function specifically handles top-level functions; methods are generated by `WriteFuncDeclAsMethod` within the context of their type definition.
func (*GoToTSCompiler) WriteFuncDeclAsMethod ¶
func (c *GoToTSCompiler) WriteFuncDeclAsMethod(decl *ast.FuncDecl) error
WriteFuncDeclAsMethod translates a Go function declaration (`ast.FuncDecl`) that has a receiver (i.e., it's a method) into a TypeScript class method.
- It preserves Go documentation comments (`decl.Doc`).
- The method is declared as `public`.
- If the `Analysis` data indicates the method is asynchronous, the `async` keyword is prepended.
- The method name retains its original Go casing.
- Parameters and return types are translated using `WriteFieldList` and `WriteTypeExpr`, respectively. Async methods have their return types wrapped in `Promise<>`.
- The method body is translated. If the Go receiver has a name (e.g., `(s *MyStruct)`), a `const receiverName = this;` binding is generated at the start of the TypeScript method body to make `this` available via the Go receiver's name. If the method body requires deferred cleanup (`NeedsDefer`), the appropriate `using __defer = new $.DisposableStack()` (or `AsyncDisposableStack`) is also generated.
This function assumes it is called only for `FuncDecl` nodes that are methods.
func (*GoToTSCompiler) WriteFuncLitValue ¶
func (c *GoToTSCompiler) WriteFuncLitValue(exp *ast.FuncLit) error
WriteFuncLitValue translates a Go function literal (`ast.FuncLit`) into a TypeScript arrow function. The translation results in: `[async] (param1: type1, ...) : returnType => { ...body... }`.
- The `async` keyword is prepended if `c.analysis.IsFuncLitAsync(exp)` indicates the function literal contains asynchronous operations.
- Parameters are translated using `WriteFieldList`.
- The return type is determined similarly to `WriteFuncType`:
- `void` for no results.
- `resultType` for a single unnamed result.
- `[typeA, typeB]` for multiple or named results.
- Wrapped in `Promise<>` if `async`.
- The function body (`exp.Body`) is translated using `WriteStmt`.
func (*GoToTSCompiler) WriteFuncType ¶
func (c *GoToTSCompiler) WriteFuncType(exp *ast.FuncType, isAsync bool)
WriteFuncType translates a Go function type (`ast.FuncType`) into a TypeScript function signature. The signature is of the form `(param1: type1, param2: type2) => returnType`. - Parameters are written using `WriteFieldList`. - Return types:
- If there are no results, the return type is `void`.
- If there's a single, unnamed result, it's `resultType`.
- If there are multiple or named results, it's a tuple type `[typeA, typeB]`.
- If `isAsync` is true (indicating the function is known to perform async operations like channel interactions or contains `go` or `defer` with async calls), the return type is wrapped in `Promise<>` (e.g., `Promise<void>`, `Promise<number>`).
func (*GoToTSCompiler) WriteGoType ¶
func (c *GoToTSCompiler) WriteGoType(typ types.Type, context GoTypeContext)
WriteGoType is the main dispatcher for translating Go types to their TypeScript equivalents. It examines the type and delegates to more specialized type writer functions based on the specific Go type encountered.
The context parameter controls how certain types (especially pointers) are handled:
- GoTypeContextGeneral: Standard type translation
- GoTypeContextFunctionReturn: Special handling for function return types where pointer-to-struct types become `ClassName | null` instead of `$.VarRef<ClassName> | null`
- GoTypeContextVariadicParam: Special handling for variadic parameter elements
It handles nil types as 'any' with a comment, and dispatches to appropriate type-specific writers for all other recognized Go types.
func (*GoToTSCompiler) WriteIdent ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteIdent(exp *ast.Ident, accessVarRefedValue bool)
WriteIdent translates a Go identifier (`ast.Ident`) used as a value (e.g., variable, function name) into its TypeScript equivalent.
- If the identifier is `nil`, it writes `null`.
- If the identifier refers to a constant, it writes the constant's evaluated value.
- Otherwise, it writes the identifier's name.
- If `accessVarRefedValue` is true and the analysis (`c.analysis.NeedsVarRefAccess`) indicates the variable is variable referenced, `.value` is appended to access the contained value.
This function relies on `go/types` (`TypesInfo.Uses` or `Defs`) to resolve the identifier and the `Analysis` data to determine varRefing needs.
func (*GoToTSCompiler) WriteImportSpec ¶
func (c *GoToTSCompiler) WriteImportSpec(a *ast.ImportSpec)
WriteImportSpec translates a Go import specification (`ast.ImportSpec`) into a TypeScript import statement.
It extracts the Go import path (e.g., `"path/to/pkg"`) and determines the import alias/name for TypeScript. If the Go import has an explicit name (e.g., `alias "path/to/pkg"`), that alias is used. Otherwise, the package name is derived from the actual Go package name, not the import path.
The Go path is then translated to a TypeScript module path using `translateGoPathToTypescriptPath`.
Finally, it writes a TypeScript import statement like `import * as alias from "typescript/path/to/pkg";` and records the import details in `c.analysis.Imports` for later use (e.g., resolving qualified identifiers).
func (*GoToTSCompiler) WriteIndexExpr ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteIndexExpr(exp *ast.IndexExpr) error
WriteIndexExpr translates a Go index expression (a[b]) to its TypeScript equivalent.
func (*GoToTSCompiler) WriteIndexListExpr ¶ added in v0.0.23
func (c *GoToTSCompiler) WriteIndexListExpr(exp *ast.IndexListExpr) error
WriteIndexListExpr translates a Go generic function instantiation (f[T1, T2]) to its TypeScript equivalent (f<T1, T2>).
func (*GoToTSCompiler) WriteInterfaceType ¶
func (c *GoToTSCompiler) WriteInterfaceType(t *types.Interface, astNode *ast.InterfaceType)
WriteInterfaceType translates a Go interface type to its TypeScript equivalent. It specially handles the error interface as $.GoError, and delegates to writeInterfaceStructure for other interface types, prepending "null | ". If astNode is provided (e.g., from a type spec), comments for methods will be included.
func (*GoToTSCompiler) WriteInterfaceTypeSpec ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteInterfaceTypeSpec(a *ast.TypeSpec, t *ast.InterfaceType) error
WriteInterfaceTypeSpec writes the TypeScript type for a Go interface type.
func (*GoToTSCompiler) WriteKeyValueExpr ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteKeyValueExpr(exp *ast.KeyValueExpr) error
WriteKeyValueExpr translates a Go key-value pair expression (`ast.KeyValueExpr`), typically found within composite literals (for structs, maps, or arrays with indexed elements), into its TypeScript object property equivalent: `key: value`. Both the key and the value expressions are recursively translated using `WriteValueExpr`. The original Go casing for keys is preserved. For example, `MyField: 123` in Go becomes `MyField: 123` in TypeScript.
func (*GoToTSCompiler) WriteMapType ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteMapType(t *types.Map)
WriteMapType translates a Go map type (map[K]V) to its TypeScript equivalent. It generates Map<K_ts, V_ts> | null, where K_ts and V_ts are the translated key and element types respectively. Maps are nilable in Go, so they are represented as nullable types in TypeScript.
func (*GoToTSCompiler) WriteNamedType ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteNamedType(t *types.Named)
WriteNamedType translates a Go named type to its TypeScript equivalent. It specially handles the error interface as $.GoError, and uses the original type name for other named types. For imported types, it writes the qualified name using the import alias found from the analysis imports. For generic types, it includes type arguments.
func (*GoToTSCompiler) WriteNamedTypeWithMethods ¶ added in v0.0.29
func (c *GoToTSCompiler) WriteNamedTypeWithMethods(a *ast.TypeSpec) error
WriteNamedTypeWithMethods generates TypeScript code for Go named types that have methods. Instead of generating a class, it now generates: 1. A type alias for the underlying type 2. Function declarations for each method (TypeName_MethodName) 3. Function implementations for each method
func (*GoToTSCompiler) WritePointerType ¶ added in v0.0.15
func (c *GoToTSCompiler) WritePointerType(t *types.Pointer, context GoTypeContext)
WritePointerType translates a Go pointer type (*T) to its TypeScript equivalent.
func (*GoToTSCompiler) WriteSelectorExpr ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteSelectorExpr(exp *ast.SelectorExpr) error
WriteSelectorExpr translates a Go selector expression (`ast.SelectorExpr`) used as a value (e.g., `obj.Field`, `pkg.Variable`, `structVar.Method()`) into its TypeScript equivalent. It distinguishes between package selectors (e.g., `time.Now`) and field/method access on an object or struct.
- For package selectors, it writes `PackageName.IdentifierName`. The `IdentifierName` is written using `WriteIdent` which handles potential `.value` access if the package-level variable is varrefed.
- For field or method access on an object (`exp.X`), it first writes the base expression (`exp.X`) using `WriteValueExpr` (which handles its own varRefing). Then, it writes a dot (`.`) followed by the selected identifier (`exp.Sel`) using `WriteIdent`, which appends `.value` if the field itself is varrefed (e.g., accessing a field of primitive type through a pointer to a struct where the field's address might have been taken).
This function aims to correctly navigate Go's automatic dereferencing and TypeScript's explicit varRefing model.
func (*GoToTSCompiler) WriteSignatureType ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteSignatureType(t *types.Signature)
WriteSignatureType translates a Go function signature to its TypeScript equivalent. It generates (param1: type1, param2: type2, ...): returnType for function types.
func (*GoToTSCompiler) WriteSliceExpr ¶ added in v0.0.23
func (c *GoToTSCompiler) WriteSliceExpr(exp *ast.SliceExpr) error
WriteSliceExpr translates a Go slice expression (e.g., `s[low:high:max]`) to its TypeScript equivalent. If `s` is a string and it's not a 3-index slice, it uses `s.substring(low, high)`. If `s` is `[]byte` (Uint8Array) and it's not a 3-index slice, it uses $.goSlice. Otherwise, it falls back to the `$.goSlice(s, low, high, max)` runtime helper.
func (*GoToTSCompiler) WriteSliceType ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteSliceType(t *types.Slice)
WriteSliceType translates a Go slice type ([]T) to its TypeScript equivalent. It generates $.Slice<T_ts>, where T_ts is the translated element type. For []byte, it generates Uint8Array.
func (*GoToTSCompiler) WriteSpec ¶
func (c *GoToTSCompiler) WriteSpec(a ast.Spec) error
WriteSpec is a dispatcher function that translates a Go specification node (`ast.Spec`) into its TypeScript equivalent. It handles different types of specifications found within `GenDecl` (general declarations): - `ast.ImportSpec` (import declarations): Delegates to `WriteImportSpec`. - `ast.ValueSpec` (variable or constant declarations): Delegates to `WriteValueSpec`. - `ast.TypeSpec` (type definitions like structs, interfaces): Delegates to `WriteTypeSpec`. If an unknown specification type is encountered, it returns an error.
func (*GoToTSCompiler) WriteStarExpr ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteStarExpr(exp *ast.StarExpr) error
WriteStarExpr translates a Go pointer dereference expression (`ast.StarExpr`, e.g., `*p`) into its TypeScript equivalent. This involves careful handling of Go's pointers and TypeScript's varRefing mechanism for emulating pointer semantics.
The translation depends on whether the pointer variable `p` itself is varrefed and what type of value it points to:
- If `p` is not varrefed and points to a primitive or another pointer: `*p` -> `p!.value`. (`p` holds a varRef, so dereference accesses its `value` field).
- If `p` is not varrefed and points to a struct: `*p` -> `p!`. (`p` holds the struct instance directly; structs are reference types in TS).
- If `p` is variable referenced (i.e., `p` is `$.VarRef<PointerType>`) and points to a primitive/pointer: `p.value!.value` (access the variable reference, then dereference the pointer)
- If `p` is varrefed and points to a struct: `p.value!`. (First `.value` unvarRefes `p` to get the struct instance).
`WriteValueExpr(operand)` handles the initial unvarRefing of `p` if `p` itself is a varrefed variable. A non-null assertion `!` is always added as pointers can be nil. The function determines if `.value` access is needed by checking what the Go pointer operand points to.
For multi-level dereferences like `***p`, this function is called recursively, with each level adding the appropriate `!.value` suffix.
Examples:
- Simple pointer to primitive: `p!.value` (where p is *int)
- Variable referenced pointer to primitive: `p.value!.value` (where p is VarRef<*int>) Example: let p = $.varRef(x) (where x is another variable reference) => p.value!.value
- Pointer to struct: `p!` (where p is *MyStruct) Example: let p = $.varRef(new MyStruct()) => p.value!
- Variable referenced pointer to struct: `p.value!` (where p is VarRef<*MyStruct>)
- Triple pointer: `p3!.value!.value!.value` (where p3 is VarRef<VarRef<VarRef<number> | null> | null> | null)
func (*GoToTSCompiler) WriteStmt ¶
func (c *GoToTSCompiler) WriteStmt(a ast.Stmt) error
WriteStmt is a central dispatcher function that translates a Go statement (`ast.Stmt`) into its TypeScript equivalent by calling the appropriate specialized `WriteStmt*` or `write*` method. It handles a wide variety of Go statements:
- Block statements (`ast.BlockStmt`): `WriteStmtBlock`.
- Assignment statements (`ast.AssignStmt`): `WriteStmtAssign`.
- Return statements (`ast.ReturnStmt`): `WriteStmtReturn`.
- Defer statements (`ast.DeferStmt`): `WriteStmtDefer`.
- If statements (`ast.IfStmt`): `WriteStmtIf`.
- Expression statements (`ast.ExprStmt`): `WriteStmtExpr`.
- Declaration statements (`ast.DeclStmt`): `WriteStmtDecl`.
- For statements (`ast.ForStmt`): `WriteStmtFor`.
- Range statements (`ast.RangeStmt`): `WriteStmtRange`.
- Switch statements (`ast.SwitchStmt`): `WriteStmtSwitch`.
- Increment/decrement statements (`ast.IncDecStmt`): `WriteStmtIncDec`.
- Send statements (`ast.SendStmt`): `WriteStmtSend`.
- Go statements (`ast.GoStmt`): `WriteStmtGo`.
- Select statements (`ast.SelectStmt`): `WriteStmtSelect`.
- Branch statements (`ast.BranchStmt`): `WriteStmtBranch`.
- Type switch statements (`ast.TypeSwitchStmt`): `WriteStmtTypeSwitch`.
- Labeled statements (`ast.LabeledStmt`): `WriteStmtLabeled`.
If an unknown statement type is encountered, it returns an error.
func (*GoToTSCompiler) WriteStmtAssign ¶
func (c *GoToTSCompiler) WriteStmtAssign(exp *ast.AssignStmt) error
WriteStmtAssign translates a Go assignment statement (`ast.AssignStmt`) into its TypeScript equivalent. It handles various forms of Go assignments:
1. **Multi-variable assignment from a single function call** (e.g., `a, b := fn()`):
- Uses `writeMultiVarAssignFromCall` to generate `let [a, b] = fn_ts();`.
2. **Type assertion with comma-ok** (e.g., `val, ok := expr.(Type)`):
- Uses `writeTypeAssertion` to generate `let { value: val, ok: ok } = $.typeAssert<Type_ts>(expr_ts, 'TypeName');`.
3. **Map lookup with comma-ok** (e.g., `val, ok := myMap[key]`):
- Uses `writeMapLookupWithExists` to generate separate assignments for `val` (using `myMap_ts.get(key_ts) ?? zeroValue`) and `ok` (using `myMap_ts.has(key_ts)`).
4. **Channel receive with comma-ok** (e.g., `val, ok := <-ch`):
- Uses `writeChannelReceiveWithOk` to generate `let { value: val, ok: ok } = await ch_ts.receiveWithOk();`.
5. **Discarded channel receive** (e.g., `<-ch` on RHS, no LHS vars):
- Translates to `await ch_ts.receive();`.
6. **Single assignment** (e.g., `x = y`, `x := y`, `*p = y`, `x[i] = y`):
- Uses `writeAssignmentCore` which handles:
- Blank identifier `_` on LHS (evaluates RHS for side effects).
- Assignment to dereferenced pointer `*p = val` -> `p_ts!.value = val_ts`.
- Short declaration `x := y`: `let x = y_ts;`. If `x` is variable referenced, `let x: $.VarRef<T> = $.varRef(y_ts);`.
- Regular assignment `x = y`, including compound assignments like `x += y`.
- Assignment to map index `m[k] = v` using `$.mapSet`.
- Struct value assignment `s1 = s2` becomes `s1 = s2.clone()` if `s2` is a struct.
7. **Multi-variable assignment with multiple RHS values** (e.g., `a, b = x, y`):
- Uses `writeAssignmentCore` to generate `[a,b] = [x_ts, y_ts];` (or `let [a,b] = ...` for `:=`).
The function ensures that the number of LHS and RHS expressions matches for most cases, erroring if they don't, except for specifically handled patterns like multi-assign from single call or discarded channel receive. It correctly applies `let` for `:=` (define) tokens and handles varRefing and cloning semantics based on type information and analysis.
func (*GoToTSCompiler) WriteStmtBlock ¶
func (c *GoToTSCompiler) WriteStmtBlock(exp *ast.BlockStmt, suppressNewline bool) error
WriteStmtBlock translates a Go block statement (`ast.BlockStmt`), typically `{ ...stmts... }`, into its TypeScript equivalent, carefully preserving comments and blank lines to maintain code readability and structure.
- It writes an opening brace `{` and indents.
- If the analysis (`c.analysis.NeedsDefer`) indicates that the block (or a function it's part of) contains `defer` statements, it injects a `using __defer = new $.DisposableStack();` (or `AsyncDisposableStack` if the context is async or contains async defers) at the beginning of the block. This `__defer` stack is used by `WriteStmtDefer` to register cleanup actions.
- It iterates through the statements (`exp.List`) in the block:
- Leading comments associated with each statement are written first, with blank lines preserved based on original source line numbers.
- The statement itself is then translated using `WriteStmt`.
- Inline comments (comments on the same line after a statement) are expected to be handled by the individual statement writers (e.g., `WriteStmtExpr`).
- Trailing comments within the block (after the last statement but before the closing brace) are written.
- Blank lines before the closing brace are preserved.
- Finally, it unindents and writes the closing brace `}`.
If `suppressNewline` is true, the final newline after the closing brace is omitted (used, for example, when an `if` block is followed by an `else`).
func (*GoToTSCompiler) WriteStmtBranch ¶ added in v0.0.22
func (c *GoToTSCompiler) WriteStmtBranch(stmt *ast.BranchStmt) error
WriteStmtBranch handles branch statements (`ast.BranchStmt`), such as `break` and `continue`.
func (*GoToTSCompiler) WriteStmtDecl ¶ added in v0.0.22
func (c *GoToTSCompiler) WriteStmtDecl(stmt *ast.DeclStmt) error
WriteStmtDecl handles declaration statements (`ast.DeclStmt`), such as short variable declarations or type declarations within a statement list. It processes `ValueSpec`s and `TypeSpec`s within the declaration.
func (*GoToTSCompiler) WriteStmtDefer ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteStmtDefer(exp *ast.DeferStmt) error
WriteStmtDefer translates a Go `defer` statement into TypeScript code that utilizes a disposable stack (`$.DisposableStack` or `$.AsyncDisposableStack`). The Go `defer` semantics (LIFO execution at function exit) are emulated by registering a cleanup function with this stack.
- `defer funcCall()` becomes `__defer.defer(() => { funcCall_ts(); });`.
- `defer func(){ ...body... }()` (an immediately-invoked function literal, IIFL) has its body inlined: `__defer.defer(() => { ...body_ts... });`.
- If the deferred call is to an async function or an async function literal (determined by `c.analysis.IsInAsyncFunctionMap`), the registered callback is marked `async`: `__defer.defer(async () => { ... });`.
The `__defer` variable is assumed to be declared at the beginning of the function scope (see `WriteStmtBlock` or `WriteFuncDeclAsMethod`) using `await using __defer = new $.AsyncDisposableStack();` for async functions/contexts or `using __defer = new $.DisposableStack();` for sync contexts.
func (*GoToTSCompiler) WriteStmtExpr ¶
func (c *GoToTSCompiler) WriteStmtExpr(exp *ast.ExprStmt) error
WriteStmtExpr translates a Go expression statement (`ast.ExprStmt`) into its TypeScript equivalent. An expression statement in Go is an expression evaluated for its side effects (e.g., a function call).
- A special case is a simple channel receive used as a statement (`<-ch`). This is translated to `await ch_ts.receive();` (the value is discarded).
- For other expression statements, the underlying expression `exp.X` is translated using `WriteValueExpr`.
- It attempts to preserve inline comments associated with the expression statement or its underlying expression `exp.X`.
The translated statement is terminated with a newline.
func (*GoToTSCompiler) WriteStmtFor ¶
func (c *GoToTSCompiler) WriteStmtFor(exp *ast.ForStmt) error
WriteStmtFor translates a Go `for` statement (`ast.ForStmt`) into a TypeScript `for` loop. The structure is `for (init_ts; cond_ts; post_ts) { body_ts }`.
- The initialization part (`exp.Init`) is translated using `WriteStmtForInit`.
- The condition part (`exp.Cond`) is translated using `WriteValueExpr`. If nil, the condition part in TypeScript is empty (resulting in an infinite loop unless broken out of).
- The post-iteration part (`exp.Post`) is translated using `WriteStmtForPost`.
- The loop body (`exp.Body`) is translated as a block statement using `WriteStmtBlock`.
This function covers standard Go `for` loops (three-part loops, condition-only loops, and infinite loops). `for...range` loops are handled by `WriteStmtRange`.
func (*GoToTSCompiler) WriteStmtForInit ¶ added in v0.0.22
func (c *GoToTSCompiler) WriteStmtForInit(stmt ast.Stmt) error
WriteStmtForInit translates the initialization part of a Go `for` loop header (e.g., `i := 0` or `i = 0` in `for i := 0; ...`) into its TypeScript equivalent. - If `stmt` is an `ast.AssignStmt`:
- For short variable declarations (`:=`) with multiple variables (e.g., `i, j := 0, 10`), it generates `let i = 0, j = 10`. Each LHS variable is paired with its corresponding RHS value; if RHS values are insufficient, remaining LHS variables are initialized with their zero value using `WriteZeroValue`.
- For other assignments (single variable `:=`, or regular `=`), it uses `writeAssignmentCore`. If it's `:=`, `let` is prepended.
- If `stmt` is an `ast.ExprStmt` (less common in `for` inits), it translates the expression using `WriteValueExpr`.
Unhandled statement types in the init part result in a comment.
func (*GoToTSCompiler) WriteStmtForPost ¶ added in v0.0.22
func (c *GoToTSCompiler) WriteStmtForPost(stmt ast.Stmt) error
WriteStmtForPost translates the post-iteration part of a Go `for` loop header (e.g., `i++` or `i, j = i+1, j-1` in `for ...; i++`) into its TypeScript equivalent. - If `stmt` is an `ast.IncDecStmt` (e.g., `i++`), it writes `i_ts++`. - If `stmt` is an `ast.AssignStmt`:
- For multiple variable assignments (e.g., `i, j = i+1, j-1`), it generates TypeScript array destructuring: `[i_ts, j_ts] = [i_ts+1, j_ts-1]`.
- For single variable assignments, it uses `writeAssignmentCore`.
- If `stmt` is an `ast.ExprStmt` (less common), it translates the expression using `WriteValueExpr`.
Unhandled statement types in the post part result in a comment.
func (*GoToTSCompiler) WriteStmtGo ¶ added in v0.0.22
func (c *GoToTSCompiler) WriteStmtGo(exp *ast.GoStmt) error
WriteStmtGo translates a Go statement (`ast.GoStmt`) into its TypeScript equivalent. It handles `go func(){...}()`, `go namedFunc(args)`, and `go x.Method(args)`.
func (*GoToTSCompiler) WriteStmtIf ¶
func (c *GoToTSCompiler) WriteStmtIf(exp *ast.IfStmt) error
WriteStmtIf translates a Go `if` statement (`ast.IfStmt`) into its TypeScript equivalent.
- If the Go `if` has an initialization statement (`exp.Init`), it's wrapped in a TypeScript block `{...}` before the `if` keyword, and the initializer is translated within this block. This emulates Go's `if` statement scope.
- The condition (`exp.Cond`) is translated using `WriteValueExpr` and placed within parentheses `(...)`.
- The `if` body (`exp.Body`) is translated as a block statement using `WriteStmtBlock`. If `exp.Body` is nil, an empty block `{}` is written.
- The `else` branch (`exp.Else`) is handled:
- If `exp.Else` is a block statement (`ast.BlockStmt`), it's written as `else { ...body_ts... }`.
- If `exp.Else` is another `if` statement (`ast.IfStmt`), it's written as `else if (...) ...`, recursively calling `WriteStmtIf`.
The function aims to produce idiomatic TypeScript `if/else if/else` structures.
func (*GoToTSCompiler) WriteStmtIncDec ¶ added in v0.0.22
func (c *GoToTSCompiler) WriteStmtIncDec(stmt *ast.IncDecStmt) error
WriteStmtIncDec handles increment and decrement statements (`ast.IncDecStmt`). It writes the expression followed by `++` or `--`.
func (*GoToTSCompiler) WriteStmtLabeled ¶ added in v0.0.24
func (c *GoToTSCompiler) WriteStmtLabeled(stmt *ast.LabeledStmt) error
WriteStmtLabeled handles labeled statements (ast.LabeledStmt), such as "label: statement". In TypeScript, labels cannot be used with variable declarations, so we need to handle this case specially.
func (*GoToTSCompiler) WriteStmtRange ¶
func (c *GoToTSCompiler) WriteStmtRange(exp *ast.RangeStmt) error
WriteStmtRange translates a Go `for...range` statement (`ast.RangeStmt`) into an equivalent TypeScript loop. The translation depends on the type of the expression being ranged over (`exp.X`), determined using `go/types` info.
**Maps (`*types.Map`):** `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... }`. If only `k` or `v` (or neither) is used, the corresponding TypeScript const declaration is adjusted.
**Strings (`*types.Basic` with `IsString` info):** `for i, r := range myString` becomes: `const _runes = $.stringToRunes(myString_ts);` `for (let i_ts = 0; i_ts < _runes.length; i_ts++) { const r_ts = _runes[i_ts]; ...body... }`. The index variable `i_ts` uses the Go key variable name if provided (and not `_`). The rune variable `r_ts` uses the Go value variable name.
**Integers (`*types.Basic` with `IsInteger` info, Go 1.22+):** `for i := range N` becomes `for (let i_ts = 0; i_ts < N_ts; i_ts++) { ...body... }`. `for i, v := range N` becomes `for (let i_ts = 0; i_ts < N_ts; i_ts++) { const v_ts = i_ts; ...body... }`.
- **Arrays (`*types.Array`) and Slices (`*types.Slice`):**
- If both key (index) and value are used (`for i, val := range arr`): `for (let i_ts = 0; i_ts < arr_ts.length; i_ts++) { const val_ts = arr_ts[i_ts]; ...body... }`.
- If only the key (index) is used (`for i := range arr`): `for (let i_ts = 0; i_ts < arr_ts.length; i_ts++) { ...body... }`.
- If only the value is used (`for _, val := range arr`): `for (const v_ts of arr_ts) { const val_ts = v_ts; ...body... }`.
- If neither is used (e.g., `for range arr`), a simple index loop `for (let _i = 0; ...)` is generated. The index variable `i_ts` uses the Go key variable name if provided.
Loop variables (`exp.Key`, `exp.Value`) are declared as `const` inside the loop body if they are not blank identifiers (`_`). The loop body (`exp.Body`) is translated using `WriteStmtBlock` (or `WriteStmt` for array/slice with key and value). If the ranged type is not supported, a comment is written, and an error is returned.
func (*GoToTSCompiler) WriteStmtReturn ¶
func (c *GoToTSCompiler) WriteStmtReturn(exp *ast.ReturnStmt) error
WriteStmtReturn translates a Go `return` statement (`ast.ReturnStmt`) into its TypeScript equivalent.
- It writes the `return` keyword.
- If there are multiple return values (`len(exp.Results) > 1`), the translated results are wrapped in a TypeScript array literal `[...]`.
- Each result expression in `exp.Results` is translated using `WriteValueExpr`.
- If there are no results, it simply writes `return`.
The statement is terminated with a newline.
func (*GoToTSCompiler) WriteStmtSelect ¶
func (c *GoToTSCompiler) WriteStmtSelect(exp *ast.SelectStmt) error
WriteStmtSelect translates a Go `select` statement into an asynchronous TypeScript operation using the `$.selectStatement` runtime helper. Go's `select` provides non-deterministic choice over channel operations. This is emulated by constructing an array of `SelectCase` objects, one for each `case` in the Go `select`, and passing it to `$.selectStatement`.
Each `SelectCase` object includes:
- `id`: A unique identifier for the case.
- `isSend`: `true` for send operations (`case ch <- val:`), `false` for receives.
- `channel`: The TypeScript channel object.
- `value` (for sends): The value being sent.
- `onSelected: async (result) => { ... }`: A callback executed when this case is chosen. `result` contains `{ value, ok }` for receives.
- Inside `onSelected`, assignments for receive operations (e.g., `v := <-ch`, `v, ok := <-ch`) are handled by declaring/assigning variables from `result.value` and `result.ok`.
- The original Go case body is then translated within this callback.
A `default` case in Go `select` is translated to a `SelectCase` with `id: -1` and its body in the `onSelected` handler. The `$.selectStatement` helper is informed if a default case exists. The entire `$.selectStatement(...)` call is `await`ed because channel operations are asynchronous in the TypeScript model.
func (*GoToTSCompiler) WriteStmtSend ¶
func (c *GoToTSCompiler) WriteStmtSend(exp *ast.SendStmt) error
WriteStmtSend translates a Go channel send statement (`ast.SendStmt`), which has the form `ch <- value`, into its asynchronous TypeScript equivalent. The translation is `await ch_ts.send(value_ts)`. Both the channel expression (`exp.Chan`) and the value expression (`exp.Value`) are translated using `WriteValueExpr`. The `await` keyword is used because channel send operations are asynchronous in the TypeScript model. The statement is terminated with a newline.
func (*GoToTSCompiler) WriteStmtSwitch ¶
func (c *GoToTSCompiler) WriteStmtSwitch(exp *ast.SwitchStmt) error
WriteStmtSwitch translates a Go `switch` statement into its TypeScript equivalent.
- If the Go switch has an initialization statement (`exp.Init`), it's wrapped in a TypeScript block `{...}` before the `switch` keyword, and the initializer is translated within this block. This emulates Go's switch scope.
- The switch condition (`exp.Tag`):
- If `exp.Tag` is present, it's translated using `WriteValueExpr`.
- If `exp.Tag` is nil (a "tagless" switch, like `switch { case cond1: ... }`), it's translated as `switch (true)` in TypeScript.
- Each case clause (`ast.CaseClause`) in `exp.Body.List` is translated using `WriteCaseClause`.
The overall structure is `[optional_init_block] switch (condition_ts) { ...cases_ts... }`.
func (*GoToTSCompiler) WriteStmtTypeSwitch ¶ added in v0.0.23
func (c *GoToTSCompiler) WriteStmtTypeSwitch(stmt *ast.TypeSwitchStmt) error
WriteStmtTypeSwitch translates a Go `type switch` statement (`ast.TypeSwitchStmt`) into its TypeScript equivalent using the `$.typeSwitch` helper.
func (*GoToTSCompiler) WriteStructType ¶
func (c *GoToTSCompiler) WriteStructType(t *types.Struct)
WriteStructType translates a Go struct type definition (`ast.StructType`) into a TypeScript anonymous object type (e.g., `{ Field1: Type1; Field2: Type2 }`). If the struct has no fields, it writes `{}`. Otherwise, it delegates to `WriteFieldList` to generate the list of field definitions. Note: This is for anonymous struct type literals. Named struct types are usually handled as classes via `WriteTypeSpec`.
func (*GoToTSCompiler) WriteStructTypeSpec ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteStructTypeSpec(a *ast.TypeSpec, t *ast.StructType) error
WriteStructTypeSpec generates the TypeScript class definition for a Go struct type. It handles the generation of:
- The class declaration.
- Getters and setters for all fields (both direct and embedded).
- The internal `_fields` property, which stores field values in `$.VarRef` containers to maintain Go's value semantics.
- A constructor that initializes the `_fields` and allows partial initialization.
- A `clone` method for creating a deep copy of the struct instance.
- Methods defined directly on the struct.
- Wrapper methods for promoted fields and methods from embedded structs, ensuring correct access and behavior.
func (*GoToTSCompiler) WriteTypeAssertExpr ¶
func (c *GoToTSCompiler) WriteTypeAssertExpr(exp *ast.TypeAssertExpr) error
WriteTypeAssertExpr translates a Go type assertion expression (e.g., `x.(T)`) into a TypeScript call to `$.typeAssert<T_ts>(x_ts, 'TypeName').value`. The `$.typeAssert` runtime function handles the actual type check and panic if the assertion fails. The `.value` access is used because in an expression context, we expect the asserted value directly. The `TypeName` string is used by the runtime for error messages.
func (*GoToTSCompiler) WriteTypeConstraint ¶ added in v0.0.23
func (c *GoToTSCompiler) WriteTypeConstraint(constraint ast.Expr)
WriteTypeConstraint translates Go type constraints to TypeScript constraint expressions. It handles different constraint types including: - Union types: []byte | string -> string | Uint8Array - Interface types: interface{Method()} -> {Method(): void} - Basic types: any -> any, comparable -> $.Comparable
func (*GoToTSCompiler) WriteTypeExpr ¶
func (c *GoToTSCompiler) WriteTypeExpr(a ast.Expr)
WriteTypeExpr translates a Go abstract syntax tree (AST) expression (`ast.Expr`) that represents a type into its TypeScript type equivalent using type information.
It handles various Go type expressions: - Basic types (e.g., int, string, bool) -> TypeScript primitives (number, string, boolean) - Named types -> TypeScript class/interface names - Pointer types (`*T`) -> `$.VarRef<T_ts> | null` - Slice types (`[]T`) -> `$.Slice<T_ts>` - Array types (`[N]T`) -> `T_ts[]` - Map types (`map[K]V`) -> `Map<K_ts, V_ts>` - Channel types (`chan T`) -> `$.Channel<T_ts>` - Struct types -> TypeScript object types or class names - Interface types -> TypeScript interface types or "any" - Function types -> TypeScript function signatures
func (*GoToTSCompiler) WriteTypeParameters ¶ added in v0.0.23
func (c *GoToTSCompiler) WriteTypeParameters(typeParams *ast.FieldList)
WriteTypeParameters translates Go type parameters to TypeScript generic parameters. It handles the TypeParams field of ast.FuncDecl and ast.TypeSpec to generate TypeScript generic parameter lists like <T extends SomeConstraint, U extends OtherConstraint>.
func (*GoToTSCompiler) WriteTypeSpec ¶
func (c *GoToTSCompiler) WriteTypeSpec(a *ast.TypeSpec) error
WriteTypeSpec writes the type specification to the output.
func (*GoToTSCompiler) WriteUnaryExpr ¶ added in v0.0.15
func (c *GoToTSCompiler) WriteUnaryExpr(exp *ast.UnaryExpr) error
WriteUnaryExpr translates a Go unary expression (`ast.UnaryExpr`) into its TypeScript equivalent. It handles several unary operations: - Channel receive (`<-ch`): Becomes `await ch.receive()`. - Address-of (`&var`):
- If `var` is a varrefed variable (its address was taken), `&var` evaluates to the varRef itself (i.e., `varName` in TypeScript, which holds the varRef).
- Otherwise (e.g., `&unvarrefedVar`, `&MyStruct{}`, `&FuncCall()`), it evaluates the operand `var`. The resulting TypeScript value (e.g., a new object instance) acts as the "pointer". VarRefing decisions for such pointers are handled at the assignment site.
- Other unary operators (`+`, `-`, `!`, `^`): Mapped to their TypeScript equivalents (e.g., `+`, `-`, `!`, `~` for bitwise NOT). Parentheses are added around the operand if it's a binary or unary expression to maintain precedence.
Unhandled operators result in a comment and an attempt to write the operator token directly. Postfix operators (`++`, `--`) are expected to be handled by their statement contexts (e.g., `IncDecStmt`).
func (*GoToTSCompiler) WriteValueExpr ¶
func (c *GoToTSCompiler) WriteValueExpr(a ast.Expr) error
WriteValueExpr translates a Go abstract syntax tree (AST) expression (`ast.Expr`) that represents a value into its TypeScript value equivalent. This is a central dispatch function for various expression types: - Identifiers (`ast.Ident`): Delegates to `WriteIdent`, potentially adding `.value` for varrefed variables. - Selector expressions (`ast.SelectorExpr`, e.g., `obj.Field` or `pkg.Var`): Delegates to `WriteSelectorExpr`. - Pointer dereferences (`ast.StarExpr`, e.g., `*ptr`): Delegates to `WriteStarExpr`. - Function calls (`ast.CallExpr`): Delegates to `WriteCallExpr`. - Unary operations (`ast.UnaryExpr`, e.g., `!cond`, `&val`): Delegates to `WriteUnaryExpr`. - Binary operations (`ast.BinaryExpr`, e.g., `a + b`): Delegates to `WriteBinaryExpr`. - Basic literals (`ast.BasicLit`, e.g., `123`, `"hello"`): Delegates to `WriteBasicLit`. - Composite literals (`ast.CompositeLit`, e.g., `MyStruct{}`): Delegates to `WriteCompositeLit`. - Key-value expressions (`ast.KeyValueExpr`): Delegates to `WriteKeyValueExpr`. - Type assertions in expression context (`ast.TypeAssertExpr`, e.g., `val.(Type)`): Delegates to `WriteTypeAssertExpr`. - Index expressions (`ast.IndexExpr`):
- For maps: `myMap[key]` becomes `myMap.get(key) ?? zeroValue`.
- For arrays/slices: `myArray[idx]` becomes `myArray![idx]`.
- Slice expressions (`ast.SliceExpr`, e.g., `s[low:high:max]`): Translates to `$.slice(s, low, high, max)`. - Parenthesized expressions (`ast.ParenExpr`): Translates `(X)` to `(X)`. - Function literals (`ast.FuncLit`): Delegates to `WriteFuncLitValue`. Unhandled value expressions result in a comment.
func (*GoToTSCompiler) WriteValueSpec ¶
func (c *GoToTSCompiler) WriteValueSpec(a *ast.ValueSpec) error
WriteValueSpec translates a Go value specification (`ast.ValueSpec`), which represents `var` or `const` declarations, into TypeScript `let` declarations.
For single variable declarations (`var x T = val` or `var x = val` or `var x T`):
- It determines if the variable `x` needs to be varrefed (e.g., if its address is taken) using `c.analysis.NeedsVarRef(obj)`.
- If variable referenced: `let x: $.VarRef<T_ts> = $.varRef(initializer_ts_or_zero_ts);` The type annotation is `$.VarRef<T_ts>`, and the initializer is wrapped in `$.varRef()`.
- If not variable referenced: `let x: T_ts = initializer_ts_or_zero_ts;` The type annotation is `T_ts`. If the initializer is `&unvarrefedVar`, it becomes `$.varRef(unvarrefedVar_ts)`.
- If no initializer is provided, the TypeScript zero value (from `WriteZeroValueForType`) is used.
- Type `T` (or `T_ts`) is obtained from `obj.Type()` and translated via `WriteGoType`.
For multiple variable declarations (`var a, b = val1, val2` or `a, b := val1, val2`):
- It uses TypeScript array destructuring: `let [a, b] = [val1_ts, val2_ts];`.
- If initialized from a single multi-return function call (`a, b := func()`), it becomes `let [a, b] = func_ts();`.
- If no initializers are provided, it defaults to `let [a,b] = []` (with a TODO to assign correct individual zero values).
Documentation comments associated with the `ValueSpec` are preserved.
func (*GoToTSCompiler) WriteVarRefedValue ¶ added in v0.0.24
func (c *GoToTSCompiler) WriteVarRefedValue(expr ast.Expr) error
WriteVarRefedValue translates a Go expression (`ast.Expr`) into its TypeScript equivalent, specifically for use as a value within a composite literal (e.g., struct fields, map keys/values, or array/slice elements). Its primary goal is to ensure that the actual un-refed value of the expression is used.
How it works:
- Identifiers (`*ast.Ident`): Delegates to `c.WriteIdent(ident, true)`, forcing the `accessValue` flag to `true`. This ensures that if `ident` refers to a GoScript var-refed variable, the generated TypeScript accesses its underlying `.value` (e.g., `myVar.value`).
- Selector Expressions (`*ast.SelectorExpr`, e.g., `obj.Field`): Delegates to `c.WriteSelectorExpr(e)`. This function handles the necessary logic for accessing fields or methods, including any required un-var-refing if the field itself or the object it's accessed on is var-refed (e.g., `obj.value.field` or `obj.field.value`).
- Star Expressions (`*ast.StarExpr`, e.g., `*ptr`): Delegates to `c.WriteStarExpr(e)`. This function handles pointer dereferencing, which in GoScript's var-refing model often translates to accessing the `.value` field of the pointer (e.g., `ptr.value`).
- Basic Literals (`*ast.BasicLit`, e.g., `123`, `"hello"`): Delegates to `c.WriteBasicLit(e)` for direct translation.
- Other expression types: Falls back to `c.WriteValueExpr(expr)` for general expression handling. This is important for complex expressions like function calls or binary operations that might appear as values within a composite literal.
Necessity and Distinction from `WriteValueExpr`: While `WriteValueExpr` is a general-purpose function for translating Go expressions and also un-var-refes identifiers (by calling `WriteIdent` with `accessValue: true`), `WriteVarRefedValue` serves a specific and crucial role when called from `WriteCompositeLit`:
- Clarity of Intent: It explicitly signals that for the constituents of a composite literal, the *un-var-refed value* is mandatory.
- Contract for `WriteCompositeLit`: It ensures that `WriteCompositeLit` receives the correct values for initialization, insulating it from potential changes in the default behavior of `WriteValueExpr` regarding un-var-refing.
- Prevents Recursion: `WriteValueExpr` handles `*ast.CompositeLit` nodes by calling `WriteCompositeLit`. If `WriteCompositeLit` were to directly call `WriteValueExpr` for its elements, it could lead to unintended recursion or behavior if an element itself was another composite literal. `WriteVarRefedValue` acts as a specific intermediary for the *elements*.
In summary, `WriteVarRefedValue` is a specialized dispatcher used by `WriteCompositeLit` to guarantee that all parts of a Go composite literal are initialized with their proper, unrefed TypeScript values.
func (*GoToTSCompiler) WriteZeroValueForType ¶
func (c *GoToTSCompiler) WriteZeroValueForType(typ any)
WriteZeroValueForType writes the TypeScript representation of the zero value for a given Go type. It handles `types.Array` by recursively writing zero values for each element to form a TypeScript array literal (e.g., `[0, 0, 0]`). For `types.Basic` (like `bool`, `string`, numeric types), it writes the corresponding TypeScript zero value (`false`, `""`, `0`). For `[]byte`, it writes `new Uint8Array(0)`. Other types default to `null`. This function is primarily used for initializing arrays and variables where an explicit initializer is absent.
type GoTypeContext ¶ added in v0.0.23
type GoTypeContext int
GoTypeContext specifies the context in which a Go type is being translated to TypeScript. This affects how certain types are handled, particularly interfaces and pointers.
const ( // GoTypeContextGeneral is used for general type translation GoTypeContextGeneral GoTypeContext = iota // GoTypeContextFunctionReturn is used when translating types for function return values. // This affects how pointer types are handled (no VarRef wrapper for structs). GoTypeContextFunctionReturn // GoTypeContextVariadicParam is used when translating types for variadic parameter elements. // This affects how interface{} types are handled (no null prefix). GoTypeContextVariadicParam )
type GsMetadata ¶ added in v0.0.49
type GsMetadata struct { Dependencies []string `json:"dependencies,omitempty"` AsyncMethods map[string]bool `json:"asyncMethods,omitempty"` }
GsMetadata represents the structure of a meta.json file in gs/ packages
type GsPackageMetadata ¶ added in v0.0.40
type GsPackageMetadata struct { // Dependencies lists the import paths that this gs/ package requires Dependencies []string `json:"dependencies,omitempty"` AsyncMethods map[string]bool `json:"asyncMethods,omitempty"` }
GsPackageMetadata holds metadata about a gs/ package
type ImplementationInfo ¶ added in v0.0.50
type ImplementationInfo struct { StructType *types.Named // The struct type that implements the interface Method *types.Func // The method object IsAsyncByFlow bool // Whether this implementation is async based on control flow analysis }
ImplementationInfo tracks information about a struct that implements an interface method
type InterfaceMethodKey ¶ added in v0.0.50
type InterfaceMethodKey struct { InterfaceType string // The string representation of the interface type MethodName string // The method name }
InterfaceMethodKey uniquely identifies an interface method
type MethodKey ¶ added in v0.0.52
type MethodKey struct { PackagePath string // Package path ReceiverType string // Receiver type name (empty for package-level functions) MethodName string // Method or function name }
MethodKey uniquely identifies a method for async analysis
type NodeInfo ¶ added in v0.0.23
type NodeInfo struct { NeedsDefer bool InAsyncContext bool IsBareReturn bool EnclosingFuncDecl *ast.FuncDecl EnclosingFuncLit *ast.FuncLit IsInsideFunction bool // true if this declaration is inside a function body IsMethodValue bool // true if this SelectorExpr is a method value that needs binding ShadowingInfo *ShadowingInfo // variable shadowing information for if statements IdentifierMapping string // replacement name for this identifier (e.g., receiver -> "receiver") }
NodeInfo consolidates node-related tracking data.
type PackageAnalysis ¶ added in v0.0.27
type PackageAnalysis struct { // FunctionDefs maps file names to the functions defined in that file // Key: filename (without .go extension), Value: list of function names FunctionDefs map[string][]string // FunctionCalls maps file names to the functions they call from other files // Key: filename (without .go extension), Value: map[sourceFile][]functionNames FunctionCalls map[string]map[string][]string // TypeDefs maps file names to the types defined in that file // Key: filename (without .go extension), Value: list of type names TypeDefs map[string][]string // TypeCalls maps file names to the types they reference from other files // Key: filename (without .go extension), Value: map[sourceFile][]typeNames TypeCalls map[string]map[string][]string }
PackageAnalysis holds cross-file analysis data for a package
func AnalyzePackageImports ¶ added in v0.0.50
func AnalyzePackageImports(pkg *packages.Package) *PackageAnalysis
AnalyzePackageImports performs package-level analysis to collect function definitions and calls across all files in the package for auto-import generation
func NewPackageAnalysis ¶ added in v0.0.27
func NewPackageAnalysis() *PackageAnalysis
NewPackageAnalysis creates a new PackageAnalysis instance
type PackageCompiler ¶
type PackageCompiler struct {
// contains filtered or unexported fields
}
PackageCompiler is responsible for compiling an entire Go package into its TypeScript equivalent. It manages the compilation of individual files within the package and determines the output path for the compiled package.
func NewPackageCompiler ¶
func NewPackageCompiler( le *logrus.Entry, compilerConf *Config, pkg *packages.Package, allPackages map[string]*packages.Package, ) (*PackageCompiler, error)
NewPackageCompiler creates a new `PackageCompiler` for a given Go package. It initializes the compiler with the necessary configuration, logger, and the `packages.Package` data obtained from `golang.org/x/tools/go/packages`. It also computes the base output path for the compiled TypeScript files of the package.
func (*PackageCompiler) Compile ¶
func (c *PackageCompiler) Compile(ctx context.Context) error
Compile orchestrates the compilation of all Go files within the package.
It iterates through each syntax file (`ast.File`) of the package, determines its relative path for logging, and then invokes `CompileFile` to handle the compilation of that specific file.
After compiling all files, it generates an index.ts file that re-exports all exported symbols, allowing the package to be imported correctly.
The working directory (`wd`) is used to make file paths in logs more readable.
func (*PackageCompiler) CompileFile ¶
func (p *PackageCompiler) CompileFile(ctx context.Context, name string, syntax *ast.File, analysis *Analysis, packageAnalysis *PackageAnalysis) error
CompileFile handles the compilation of a single Go source file to TypeScript. It uses the pre-computed package-level analysis for accurate TypeScript generation (e.g., about varRefing, async functions, defer statements, receiver usage across files). Then, it creates a `FileCompiler` instance for the file and invokes its `Compile` method to generate the TypeScript code.
type ReflectedFunctionInfo ¶ added in v0.0.38
type ReflectedFunctionInfo struct { FuncType *types.Signature // The function's type signature NeedsReflect bool // Whether this function is used with reflection }
ReflectedFunctionInfo tracks functions that need reflection support
type ShadowingInfo ¶ added in v0.0.42
type ShadowingInfo struct { // ShadowedVariables maps shadowed variable names to their outer scope objects ShadowedVariables map[string]types.Object // TempVariables maps shadowed variable names to temporary variable names TempVariables map[string]string }
ShadowingInfo tracks variable shadowing in if statement initializations
type TSCodeWriter ¶
type TSCodeWriter struct {
// contains filtered or unexported fields
}
TSCodeWriter writes TypeScript code.
func NewTSCodeWriter ¶
func NewTSCodeWriter(w io.Writer) *TSCodeWriter
NewTSCodeWriter builds a new TypeScript code writer.
func (*TSCodeWriter) Indent ¶
func (w *TSCodeWriter) Indent(count int)
Indent changes the indentation level by a delta.
func (*TSCodeWriter) WriteCommentInline ¶
func (w *TSCodeWriter) WriteCommentInline(commentText string)
WriteCommentInline write a comment within /* */.
func (*TSCodeWriter) WriteCommentInlinef ¶ added in v0.0.17
func (w *TSCodeWriter) WriteCommentInlinef(format string, args ...any)
WriteCommentInlinef writes a formatted comment within /* */.
func (*TSCodeWriter) WriteCommentLine ¶
func (w *TSCodeWriter) WriteCommentLine(commentText string)
WriteCommentLine writes a comment as a // line.
func (*TSCodeWriter) WriteCommentLinef ¶ added in v0.0.17
func (w *TSCodeWriter) WriteCommentLinef(format string, args ...any)
WriteCommentLinef writes a formatted comment as a // line.
func (*TSCodeWriter) WriteImport ¶
func (w *TSCodeWriter) WriteImport(symbolName, importPath string)
WriteImport writes a TypeScript import.
func (*TSCodeWriter) WriteLine ¶
func (w *TSCodeWriter) WriteLine(line string)
WriteLine writes a line of code to the output.
func (*TSCodeWriter) WriteLinePreamble ¶
func (w *TSCodeWriter) WriteLinePreamble()
WriteLinePreamble writes the indentation.
func (*TSCodeWriter) WriteLinef ¶
func (w *TSCodeWriter) WriteLinef(line string, args ...any)
WriteLinef writes a formatted line of code to the output.
func (*TSCodeWriter) WriteLiterally ¶
func (w *TSCodeWriter) WriteLiterally(literal string)
WriteLiterally writes something to the output without processing
func (*TSCodeWriter) WriteLiterallyf ¶ added in v0.0.15
func (w *TSCodeWriter) WriteLiterallyf(literal string, args ...any)
WriteLiterallyf writes something to the output with formatting.
func (*TSCodeWriter) WriteSectionTail ¶
func (w *TSCodeWriter) WriteSectionTail()
WriteSectionTail writes the end of a section.
type VariableUsageInfo ¶ added in v0.0.15
type VariableUsageInfo struct { // Sources lists variables whose values (or addresses) are assigned TO this variable. // Example: For `x = y`, y is a source for x. For `x = &y`, y is a source for x. Sources []AssignmentInfo // Destinations lists variables that are assigned the value (or address) FROM this variable. // Example: For `y = x`, y is a destination for x. For `p = &x`, p is a destination for x. Destinations []AssignmentInfo }
VariableUsageInfo tracks how a variable is used throughout the code.
Source Files
¶
- analysis.go
- assignment.go
- code-writer.go
- compiler.go
- composite-lit.go
- config.go
- decl.go
- expr-call-async.go
- expr-call-builtins.go
- expr-call-helpers.go
- expr-call-make.go
- expr-call-type-conversion.go
- expr-call.go
- expr-selector.go
- expr-star.go
- expr-type.go
- expr-value.go
- expr.go
- field.go
- lit.go
- output.go
- primitive.go
- protobuf.go
- sanitize.go
- spec-struct.go
- spec-value.go
- spec.go
- stmt-assign.go
- stmt-for.go
- stmt-range.go
- stmt-select.go
- stmt-type-switch.go
- stmt.go
- type-assert.go
- type-info.go
- type.go