gotranspiler

package
v0.9.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package gotranspiler implements TypeScript to Go source code transpilation.

It uses the existing tsgo parser and type checker to parse TypeScript source files, resolve all types, and generate equivalent Go source code.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EmitExprToString added in v0.7.0

func EmitExprToString(expr GoExpr) string

EmitExprToString renders an IR expression to a Go source string.

func EmitStmtToString added in v0.7.0

func EmitStmtToString(stmt GoStmt) string

EmitStmtToString renders an IR statement to a Go source string.

func GenerateBridgeCode

func GenerateBridgeCode(moduleName, pkgAlias string, funcs []ExportedFunc) string

GenerateBridgeCode generates Go source code that registers transpiled functions as a native JS module via NativeModuleFromFuncs. Generic functions are skipped with a warning message.

func GenerateDTS

func GenerateDTS(packages []string) (string, error)

GenerateDTS generates TypeScript .d.ts content for the given Go packages. Package names can optionally have a "go:" prefix (e.g., "go:fmt" or "fmt").

func GenerateNativeImport

func GenerateNativeImport(pkgImport, pkgAlias string) string

GenerateNativeImport generates the import statement for a native package.

func GenericWarnings

func GenericWarnings(funcs []ExportedFunc) []string

GenericWarnings returns warning messages for generic functions that can't be exposed as native module exports.

func TranspileProjectToDir

func TranspileProjectToDir(files []string, entryFile string, outDir string, moduleName string) error

TranspileProjectToDir transpiles multiple TS files and writes the Go project to outDir.

func TranspileProjectToDirWithNpm

func TranspileProjectToDirWithNpm(files []string, entryFile string, outDir string, moduleName string) error

TranspileProjectToDirWithNpm transpiles with npm package resolution.

func TranspileToDir

func TranspileToDir(filename string, outDir string, pkgName string) error

TranspileToDir transpiles a TypeScript file and writes the output to a directory.

Types

type DispatchTarget added in v0.5.0

type DispatchTarget int

DispatchTarget determines how a method call should be emitted in Go. The target is determined by the Go type category of the object, not by method name matching.

const (
	DispatchArrayHelper    DispatchTarget = iota // jsarray.* helpers (for []T types)
	DispatchStringStdlib                         // strings.* stdlib or inline (for string types)
	DispatchPromiseMethod                        // promise.Promise.Then/Await (for *promise.Promise[T])
	DispatchMapOperation                         // Go map operations (for map[K]V types)
	DispatchConcreteMethod                       // obj.Method() direct call (for *Struct types)
	DispatchJSRTRuntime                          // jsrt.Obj().Get().Call() (for any/unknown types)
)

type ExportedFunc

type ExportedFunc struct {
	GoName  string // PascalCase Go name (e.g., "Fibonacci")
	JSName  string // camelCase JS name (e.g., "fibonacci")
	Generic bool   // True if the function has type parameters
}

ExportedFunc represents an exported Go function discovered in transpiled code.

func DiscoverExportedFuncs

func DiscoverExportedFuncs(goSource string) ([]ExportedFunc, error)

DiscoverExportedFuncs parses Go source code and returns all exported top-level functions (including generics, which are flagged for warning).

type GoDecl added in v0.7.0

type GoDecl interface {
	// contains filtered or unexported methods
}

GoDecl represents a top-level Go declaration.

type GoExpr added in v0.7.0

type GoExpr interface {
	ExprType() GoTypeInfo
	// contains filtered or unexported methods
}

GoExpr represents a Go expression with a resolved type.

type GoFile added in v0.7.0

type GoFile struct {
	Package string
	Decls   []GoDecl
	Stmts   []GoStmt // package-level init statements (rare, for var declarations)
}

GoFile is the root IR node for a single Go source file.

type GoStmt added in v0.7.0

type GoStmt interface {
	// contains filtered or unexported methods
}

GoStmt represents a Go statement.

type GoTypeCategory

type GoTypeCategory int

GoTypeCategory classifies a Go type for emission strategy dispatch.

const (
	GoTypePrimitive GoTypeCategory = iota // string, float64, bool, int
	GoTypePointer                         // *ClassName, *web.Response
	GoTypeInterface                       // discriminated union interfaces (Shape)
	GoTypeSlice                           // []T
	GoTypeMap                             // map[K]V
	GoTypeFunc                            // func(params) returnType
	GoTypePromise                         // *promise.Promise[T]
	GoTypeJSObject                        // *jsrt.JSObject (fallback when unmappable)
)

type GoTypeInfo

type GoTypeInfo struct {
	Category GoTypeCategory
	GoStr    string // Full Go type string: "[]float64", "*web.Response", etc.
	ElemType string // For Slice: element type; for Map: value type; for Promise: inner type
	KeyType  string // For Map: key type
	Name     string // For Pointer/Interface: the type name without *
}

GoTypeInfo holds the categorized Go type for an expression.

func (GoTypeInfo) IsAny

func (g GoTypeInfo) IsAny() bool

func (GoTypeInfo) IsBool

func (g GoTypeInfo) IsBool() bool

func (GoTypeInfo) IsFloat64

func (g GoTypeInfo) IsFloat64() bool

func (GoTypeInfo) IsInt

func (g GoTypeInfo) IsInt() bool

func (GoTypeInfo) IsMap

func (g GoTypeInfo) IsMap() bool

func (GoTypeInfo) IsNumeric

func (g GoTypeInfo) IsNumeric() bool

func (GoTypeInfo) IsPointer

func (g GoTypeInfo) IsPointer() bool

func (GoTypeInfo) IsPromise

func (g GoTypeInfo) IsPromise() bool

func (GoTypeInfo) IsSlice

func (g GoTypeInfo) IsSlice() bool

func (GoTypeInfo) IsString

func (g GoTypeInfo) IsString() bool

type IRAddrOf added in v0.7.0

type IRAddrOf struct {
	Expr GoExpr
	// contains filtered or unexported fields
}

IRAddrOf is the address-of operator: &expr

func (IRAddrOf) ExprType added in v0.7.0

func (e IRAddrOf) ExprType() GoTypeInfo

type IRArrayMethodCall added in v0.7.0

type IRArrayMethodCall struct {
	HelperFunc string   // "Map", "Filter", "Reduce", "Find", "ForEach", etc.
	Array      GoExpr   // the array expression
	Callback   GoExpr   // the callback function (IRFuncLit)
	ExtraArgs  []GoExpr // extra args (e.g., initial value for Reduce)
	ElemType   string   // Go element type of the array
	// contains filtered or unexported fields
}

IRArrayMethodCall is a specialized call to jsarray.* helpers. Separated from IRMethodCall because array methods have complex callback typing.

func (IRArrayMethodCall) ExprType added in v0.7.0

func (e IRArrayMethodCall) ExprType() GoTypeInfo

type IRAssign added in v0.7.0

type IRAssign struct {
	Targets []GoExpr
	Op      string // "=", "+=", "-=", etc.
	Values  []GoExpr
	// contains filtered or unexported fields
}

IRAssign is an assignment statement.

type IRAwait added in v0.7.0

type IRAwait struct {
	Expr GoExpr // the promise expression
	// contains filtered or unexported fields
}

IRAwait represents awaiting a promise: promise.Await()

func (IRAwait) ExprType added in v0.7.0

func (e IRAwait) ExprType() GoTypeInfo

type IRBinaryOp added in v0.7.0

type IRBinaryOp struct {
	Op    string // Go operator: "+", "-", "==", "!=", "&&", "||", etc.
	Left  GoExpr
	Right GoExpr
	// contains filtered or unexported fields
}

IRBinaryOp is a binary operation.

func (IRBinaryOp) ExprType added in v0.7.0

func (e IRBinaryOp) ExprType() GoTypeInfo

type IRBlock added in v0.7.0

type IRBlock struct {
	Stmts []GoStmt
	Bare  bool // if true, emit statements without surrounding braces
	// contains filtered or unexported fields
}

IRBlock is a scoped block of statements.

type IRBreak added in v0.7.0

type IRBreak struct {
	Label string // empty for unlabeled break
	// contains filtered or unexported fields
}

IRBreak is a break statement with optional label.

type IRBuilder added in v0.7.0

type IRBuilder struct {
	// contains filtered or unexported fields
}

IRBuilder constructs GOTIR nodes from the TypeScript AST. It is self-contained: no dependency on the old Transpiler emit functions. All type-driven decisions are made here; the emitter just formats Go source.

func NewIRBuilderFromChecker added in v0.7.0

func NewIRBuilderFromChecker(ck *checker.Checker, tm *typeMapper) *IRBuilder

NewIRBuilderFromChecker creates a standalone builder.

func (*IRBuilder) BuildExpr added in v0.7.0

func (b *IRBuilder) BuildExpr(node *ast.Node) GoExpr

BuildExpr converts a TypeScript AST expression to a GOTIR expression node.

func (*IRBuilder) BuildSourceFile added in v0.7.0

func (b *IRBuilder) BuildSourceFile(sf *ast.SourceFile, pkgName string, isEntry bool) *GoFile

BuildSourceFile converts a TypeScript source file to a GoFile IR.

func (*IRBuilder) BuildStmt added in v0.7.0

func (b *IRBuilder) BuildStmt(node *ast.Node) GoStmt

BuildStmt converts a TypeScript AST statement to a GOTIR statement node.

type IRCall added in v0.7.0

type IRCall struct {
	Func GoExpr // the function expression
	Args []GoExpr
	// contains filtered or unexported fields
}

IRCall is a regular function call (not a method call).

func (IRCall) ExprType added in v0.7.0

func (e IRCall) ExprType() GoTypeInfo

type IRCase added in v0.7.0

type IRCase struct {
	Exprs []GoExpr // empty = default case
	Body  []GoStmt
}

IRCase is a single case in a switch.

type IRCompositeLit added in v0.7.0

type IRCompositeLit struct {
	TypeStr  string       // Go type string: "&MyStruct", "[]float64", "map[string]any"
	Elements []IRKeyValue // field/key-value pairs, or positional elements (Key empty)
	// contains filtered or unexported fields
}

IRCompositeLit is a composite literal (struct, slice, map). e.g., &MyStruct{Field: value}, []float64{1, 2, 3}, map[string]any{"k": v}

func (IRCompositeLit) ExprType added in v0.7.0

func (e IRCompositeLit) ExprType() GoTypeInfo

type IRConstDecl added in v0.7.0

type IRConstDecl struct {
	Name  string
	Value GoExpr // may be nil (uses iota)
}

IRConstDecl is a single constant declaration.

type IRConstGroupDecl added in v0.7.0

type IRConstGroupDecl struct {
	TypeName string // the type name (for typed constants)
	Consts   []IRConstDecl
	// contains filtered or unexported fields
}

IRConstGroupDecl is a package-level const block (for enums/iota).

type IRContinue added in v0.7.0

type IRContinue struct {
	Label string
	// contains filtered or unexported fields
}

IRContinue is a continue statement with optional label.

type IRDefer added in v0.7.0

type IRDefer struct {
	Call GoExpr // the deferred function call
	// contains filtered or unexported fields
}

IRDefer is a defer statement.

type IRDeref added in v0.7.0

type IRDeref struct {
	Expr GoExpr
	// contains filtered or unexported fields
}

IRDeref is the dereference operator: *expr

func (IRDeref) ExprType added in v0.7.0

func (e IRDeref) ExprType() GoTypeInfo

type IREmitter added in v0.7.0

type IREmitter struct {
	// contains filtered or unexported fields
}

IREmitter converts GOTIR nodes to Go source code. It is stateless with respect to type information — all type-driven decisions have already been made by the IRBuilder.

func NewIREmitter added in v0.7.0

func NewIREmitter(builder *IRBuilder) *IREmitter

NewIREmitter creates an emitter from a builder's state.

func (*IREmitter) EmitDecl added in v0.7.0

func (e *IREmitter) EmitDecl(decl GoDecl)

EmitDecl emits a Go declaration.

func (*IREmitter) EmitExpr added in v0.7.0

func (e *IREmitter) EmitExpr(expr GoExpr)

EmitExpr emits a Go expression from an IR node.

func (*IREmitter) EmitFile added in v0.7.0

func (e *IREmitter) EmitFile(file *GoFile) (string, error)

EmitFile generates the final Go source for a file.

func (*IREmitter) EmitStmt added in v0.7.0

func (e *IREmitter) EmitStmt(stmt GoStmt)

EmitStmt emits a Go statement from an IR node.

func (*IREmitter) EmitStmts added in v0.7.0

func (e *IREmitter) EmitStmts(stmts []GoStmt)

EmitStmts emits a list of statements.

func (*IREmitter) Result added in v0.7.0

func (e *IREmitter) Result() string

Result returns the accumulated Go source (without package/imports header).

type IREnumDecl added in v0.7.0

type IREnumDecl struct {
	Name       string
	BaseType   string // "float64", "string", or "int"
	Members    []IREnumMember
	IsExported bool
	// contains filtered or unexported fields
}

IREnumDecl declares an enum as a set of Go constants.

type IREnumMember added in v0.7.0

type IREnumMember struct {
	Name  string
	Value GoExpr // the constant value (may be nil for iota)
}

IREnumMember is a single enum constant.

type IRExprStmt added in v0.7.0

type IRExprStmt struct {
	Expr GoExpr
	// contains filtered or unexported fields
}

IRExprStmt is an expression used as a statement.

type IRFieldAccess added in v0.7.0

type IRFieldAccess struct {
	Object         GoExpr
	Field          string
	NeedsAssertion bool       // true if obj is any and needs .(Type)
	AssertType     GoTypeInfo // the type to assert to (when NeedsAssertion)
	// contains filtered or unexported fields
}

IRFieldAccess is a field/property access on an object.

func (IRFieldAccess) ExprType added in v0.7.0

func (e IRFieldAccess) ExprType() GoTypeInfo

type IRFor added in v0.7.0

type IRFor struct {
	Init GoStmt // may be nil
	Cond GoExpr // may be nil (infinite loop)
	Post GoStmt // may be nil
	Body []GoStmt
	// contains filtered or unexported fields
}

IRFor is a C-style for loop.

type IRFuncDecl added in v0.7.0

type IRFuncDecl struct {
	Name       string
	TypeParams []IRTypeParam // generic type parameters
	Params     []IRParam
	RetType    GoTypeInfo
	Body       []GoStmt
	Receiver   *IRReceiver // non-nil for methods
	IsAsync    bool        // wraps body in promise.New
	IsExported bool
	// contains filtered or unexported fields
}

IRFuncDecl is a top-level or method function declaration.

type IRFuncLit added in v0.7.0

type IRFuncLit struct {
	Params  []IRParam
	RetType GoTypeInfo
	Body    []GoStmt
	IsAsync bool // wraps body in promise.New[T](func(__resolve, __reject) { ... })
	// contains filtered or unexported fields
}

IRFuncLit is a function literal (closure).

func (IRFuncLit) ExprType added in v0.7.0

func (e IRFuncLit) ExprType() GoTypeInfo

type IRGo added in v0.7.0

type IRGo struct {
	Call GoExpr
	// contains filtered or unexported fields
}

IRGo is a go statement (goroutine launch).

type IRIdent added in v0.7.0

type IRIdent struct {
	Name    string // Go identifier name (already converted via goVarName/goExportedName)
	PkgName string // package qualifier, empty for local (e.g., "strings", "web")
	// contains filtered or unexported fields
}

IRIdent is a variable or constant reference.

func (IRIdent) ExprType added in v0.7.0

func (e IRIdent) ExprType() GoTypeInfo

type IRIf added in v0.7.0

type IRIf struct {
	Cond GoExpr
	Body []GoStmt
	Else []GoStmt // may be empty; single IRIf element = else if
	// contains filtered or unexported fields
}

IRIf is an if/else statement.

type IRImportDecl added in v0.7.0

type IRImportDecl struct {
	Path  string // import path
	Alias string // alias (empty for default)
	// contains filtered or unexported fields
}

IRImportDecl captures a required Go import.

type IRIncDec added in v0.7.0

type IRIncDec struct {
	Expr GoExpr
	Op   string // "++" or "--"
	// contains filtered or unexported fields
}

IRIncDec is an increment/decrement statement: i++ or i--

type IRIndexAccess added in v0.7.0

type IRIndexAccess struct {
	Object GoExpr
	Index  GoExpr
	// contains filtered or unexported fields
}

IRIndexAccess is an index/element access (arr[i], map[key]).

func (IRIndexAccess) ExprType added in v0.7.0

func (e IRIndexAccess) ExprType() GoTypeInfo

type IRInstanceOf added in v0.7.0

type IRInstanceOf struct {
	Expr     GoExpr
	TypeName string // Go type name to check against
	// contains filtered or unexported fields
}

IRInstanceOf generates an instanceof check. Emits as a Go type assertion check: _, ok := expr.(*Type)

func (IRInstanceOf) ExprType added in v0.7.0

func (e IRInstanceOf) ExprType() GoTypeInfo

type IRInterfaceDecl added in v0.7.0

type IRInterfaceDecl struct {
	Name       string
	TypeParams []IRTypeParam
	Methods    []IRMethodSig
	Embedded   []string // embedded interface names
	IsExported bool
	// contains filtered or unexported fields
}

IRInterfaceDecl declares an interface type.

type IRJSRTCall added in v0.7.0

type IRJSRTCall struct {
	Pattern string   // "Get", "Set", "Call", "TypeOf", etc.
	Object  GoExpr   // the object (may be nil for global operations)
	Field   string   // field/method name
	Args    []GoExpr // arguments
	// contains filtered or unexported fields
}

IRJSRTCall is a call through the jsrt runtime for dynamic/any-typed operations. e.g., jsrt.Obj(x).Get("field").Unwrap(), jsrt.Obj(x).Call("method", args...)

func (IRJSRTCall) ExprType added in v0.7.0

func (e IRJSRTCall) ExprType() GoTypeInfo

type IRKeyValue added in v0.7.0

type IRKeyValue struct {
	Key   string // field name or map key (empty for positional elements)
	Value GoExpr
}

IRKeyValue is a key-value pair in a composite literal.

type IRLabeled added in v0.7.0

type IRLabeled struct {
	Label string
	Stmt  GoStmt
	// contains filtered or unexported fields
}

IRLabeled is a labeled statement.

type IRLiteral added in v0.7.0

type IRLiteral struct {
	Value string // Go literal text: `"hello"`, "42", "true", "nil"
	// contains filtered or unexported fields
}

IRLiteral is a literal value (string, number, bool, nil).

func (IRLiteral) ExprType added in v0.7.0

func (e IRLiteral) ExprType() GoTypeInfo

type IRMakeCall added in v0.7.0

type IRMakeCall struct {
	TypeStr string // Go type: "[]float64", "map[string]any", "chan int"
	Len     GoExpr // length (may be nil)
	Cap     GoExpr // capacity (may be nil)
	// contains filtered or unexported fields
}

IRMakeCall is a make() expression for slices, maps, or channels.

func (IRMakeCall) ExprType added in v0.7.0

func (e IRMakeCall) ExprType() GoTypeInfo

type IRMethodCall added in v0.7.0

type IRMethodCall struct {
	Strategy DispatchTarget
	Object   GoExpr
	Method   string
	Args     []GoExpr
	// Array/string method-specific fields
	ElemGoType string // element type for array helpers (e.g., "float64")
	// contains filtered or unexported fields
}

IRMethodCall is a method call with a resolved dispatch strategy.

func (IRMethodCall) ExprType added in v0.7.0

func (e IRMethodCall) ExprType() GoTypeInfo

type IRMethodSig added in v0.7.0

type IRMethodSig struct {
	Name       string
	Params     []IRParam
	RetType    GoTypeInfo
	IsExported bool
}

IRMethodSig is a method signature in an interface.

type IRMultiValue added in v0.7.0

type IRMultiValue struct {
	Exprs []GoExpr
	// contains filtered or unexported fields
}

IRMultiValue represents a multi-return value expression in Go. e.g., val, err := someFunc()

func (IRMultiValue) ExprType added in v0.7.0

func (e IRMultiValue) ExprType() GoTypeInfo

type IRMultiVarDecl added in v0.7.0

type IRMultiVarDecl struct {
	Names []string
	Types []GoTypeInfo
	Init  GoExpr // the expression producing multiple values
	// contains filtered or unexported fields
}

IRMultiVarDecl is a multi-variable declaration (e.g., from destructuring or multi-return). val, err := someFunc()

type IRNewExpr added in v0.7.0

type IRNewExpr struct {
	TypeName string       // Go type name (without *)
	Args     []IRKeyValue // constructor arguments as field assignments
	// contains filtered or unexported fields
}

IRNewExpr generates a struct instantiation: &Type{fields...}

func (IRNewExpr) ExprType added in v0.7.0

func (e IRNewExpr) ExprType() GoTypeInfo

type IRNilCheck added in v0.7.0

type IRNilCheck struct {
	Expr GoExpr // expression to check for nil
	Then GoExpr // result if not nil
	Else GoExpr // result if nil (usually IRLiteral{Value:"nil"})
	// contains filtered or unexported fields
}

IRNilCheck generates an if-nil-check pattern or nil comparison. Used for optional chaining: if x != nil { x.Field } else { nil }

func (IRNilCheck) ExprType added in v0.7.0

func (e IRNilCheck) ExprType() GoTypeInfo

type IRParam added in v0.7.0

type IRParam struct {
	Name   string
	Typ    GoTypeInfo
	IsRest bool // ...args → variadic
}

IRParam is a function parameter.

type IRPromiseNew added in v0.7.0

type IRPromiseNew struct {
	InnerType GoTypeInfo // T in Promise[T]
	Body      []GoStmt   // statements inside the promise callback
	// contains filtered or unexported fields
}

IRPromiseNew wraps a body in promise.New[T](func(resolve, reject) { ... })

func (IRPromiseNew) ExprType added in v0.7.0

func (e IRPromiseNew) ExprType() GoTypeInfo

type IRRange added in v0.7.0

type IRRange struct {
	Key   string // "_" if unused
	Value string // "_" if unused, empty if no value binding
	Over  GoExpr
	Body  []GoStmt
	// contains filtered or unexported fields
}

IRRange is a for-range loop.

type IRRawDecl added in v0.7.0

type IRRawDecl struct {
	Code string
	// contains filtered or unexported fields
}

IRRawDecl is an escape hatch for emitting raw Go declaration text.

type IRRawExpr added in v0.7.0

type IRRawExpr struct {
	Code string
	// contains filtered or unexported fields
}

IRRawExpr is an escape hatch for emitting raw Go expression text. Used for not-yet-migrated patterns during incremental migration.

func (IRRawExpr) ExprType added in v0.7.0

func (e IRRawExpr) ExprType() GoTypeInfo

type IRRawStmt added in v0.7.0

type IRRawStmt struct {
	Code string
	// contains filtered or unexported fields
}

IRRawStmt is an escape hatch for emitting raw Go statement text.

type IRReceiver added in v0.7.0

type IRReceiver struct {
	Name string // receiver variable name (e.g., "r")
	Type string // receiver type (e.g., "*MyStruct")
}

IRReceiver is a method receiver.

type IRRejectCall added in v0.7.0

type IRRejectCall struct {
	Err GoExpr
	// contains filtered or unexported fields
}

IRRejectCall generates __reject(err) inside async promise bodies.

type IRResolveCall added in v0.7.0

type IRResolveCall struct {
	Value GoExpr // the value to resolve with (may be nil for void)
	// contains filtered or unexported fields
}

IRResolveCall generates __resolve(value) inside async promise bodies.

type IRReturn added in v0.7.0

type IRReturn struct {
	Values []GoExpr // may be empty for bare return
	// contains filtered or unexported fields
}

IRReturn is a return statement.

type IRSend added in v0.7.0

type IRSend struct {
	Chan  GoExpr
	Value GoExpr
	// contains filtered or unexported fields
}

IRSend is a channel send: ch <- value

type IRSliceExpr added in v0.7.0

type IRSliceExpr struct {
	Object GoExpr
	Low    GoExpr // may be nil
	High   GoExpr // may be nil
	// contains filtered or unexported fields
}

IRSliceExpr is a slice expression: s[low:high] or s[low:high:max].

func (IRSliceExpr) ExprType added in v0.7.0

func (e IRSliceExpr) ExprType() GoTypeInfo

type IRSprintfCall added in v0.7.0

type IRSprintfCall struct {
	Format string   // format string with %s/%v placeholders
	Args   []GoExpr // expressions for each placeholder
	// contains filtered or unexported fields
}

IRSprintfCall generates fmt.Sprintf for template literals.

func (IRSprintfCall) ExprType added in v0.7.0

func (e IRSprintfCall) ExprType() GoTypeInfo

type IRStdlibCall added in v0.7.0

type IRStdlibCall struct {
	Package string // "strings", "fmt", "jsarray", "jsrt", "" (builtin)
	Func    string // "Contains", "Sprintf", "len", "append"
	Args    []GoExpr
	// contains filtered or unexported fields
}

IRStdlibCall is a call to a Go standard library or runtime helper function. e.g., strings.Contains(s, sub), fmt.Sprintf(...), len(x), append(s, e)

func (IRStdlibCall) ExprType added in v0.7.0

func (e IRStdlibCall) ExprType() GoTypeInfo

type IRStmtDecl added in v0.7.0

type IRStmtDecl struct {
	Stmt GoStmt
	// contains filtered or unexported fields
}

IRStmtDecl wraps a statement as a declaration (for package-level init code).

type IRStructDecl added in v0.7.0

type IRStructDecl struct {
	Name       string
	TypeParams []IRTypeParam
	Embedded   []string // embedded type names (base class, composed interfaces)
	Fields     []IRStructField
	IsExported bool
	// contains filtered or unexported fields
}

IRStructDecl declares a struct type.

type IRStructField added in v0.7.0

type IRStructField struct {
	Name       string
	Typ        GoTypeInfo
	Tag        string // struct tag (e.g., `json:"name"`)
	IsExported bool
}

IRStructField is a field in a struct declaration.

type IRSwitch added in v0.7.0

type IRSwitch struct {
	Tag   GoExpr // may be nil for type switch
	Cases []IRCase
	// contains filtered or unexported fields
}

IRSwitch is a switch statement.

type IRTernary added in v0.7.0

type IRTernary struct {
	Cond GoExpr
	Then GoExpr
	Else GoExpr
	// contains filtered or unexported fields
}

IRTernary generates a Go inline conditional pattern. Since Go has no ternary, this typically becomes a helper call or IIFE.

func (IRTernary) ExprType added in v0.7.0

func (e IRTernary) ExprType() GoTypeInfo

type IRTryCatch added in v0.7.0

type IRTryCatch struct {
	TryBody     []GoStmt
	CatchVar    string   // catch parameter name (empty if unused)
	CatchBody   []GoStmt // may be empty if no catch
	FinallyBody []GoStmt // may be empty if no finally
	// contains filtered or unexported fields
}

IRTryCatch represents a try/catch/finally → Go error handling pattern. The specific Go pattern depends on context:

  • Simple: if-err-check after call
  • Complex: func() with recover()

type IRTypeAlias added in v0.7.0

type IRTypeAlias struct {
	Name       string
	Underlying string // Go type string
	TypeParams []IRTypeParam
	IsExported bool
	// contains filtered or unexported fields
}

IRTypeAlias declares a type alias: type Name = UnderlyingType

type IRTypeAssertion added in v0.7.0

type IRTypeAssertion struct {
	Expr       GoExpr
	TargetType GoTypeInfo
	Safe       bool // true for val, ok := expr.(Type) pattern
	// contains filtered or unexported fields
}

IRTypeAssertion is a Go type assertion: expr.(Type)

func (IRTypeAssertion) ExprType added in v0.7.0

func (e IRTypeAssertion) ExprType() GoTypeInfo

type IRTypeConversion added in v0.7.0

type IRTypeConversion struct {
	Expr       GoExpr
	TargetType string // Go type string
	// contains filtered or unexported fields
}

IRTypeConversion is a Go type conversion: Type(expr)

func (IRTypeConversion) ExprType added in v0.7.0

func (e IRTypeConversion) ExprType() GoTypeInfo

type IRTypeOf added in v0.7.0

type IRTypeOf struct {
	Expr GoExpr
	// contains filtered or unexported fields
}

IRTypeOf generates a typeof check. Emits as jsrt.TypeOf(expr) or a direct type switch pattern.

func (IRTypeOf) ExprType added in v0.7.0

func (e IRTypeOf) ExprType() GoTypeInfo

type IRTypeParam added in v0.7.0

type IRTypeParam struct {
	Name       string // Go name (PascalCase)
	Constraint string // Go constraint: "any", "comparable", etc.
}

IRTypeParam is a generic type parameter declaration.

type IRUnaryOp added in v0.7.0

type IRUnaryOp struct {
	Op      string // "!", "-", "^" (bitwise NOT)
	Operand GoExpr
	Postfix bool // true for i++ / i--
	// contains filtered or unexported fields
}

IRUnaryOp is a unary operation (prefix or postfix).

func (IRUnaryOp) ExprType added in v0.7.0

func (e IRUnaryOp) ExprType() GoTypeInfo

type IRVarDecl added in v0.7.0

type IRVarDecl struct {
	Name     string
	Typ      GoTypeInfo
	Init     GoExpr // may be nil for zero-value declarations
	IsConst  bool   // const vs var
	UseShort bool   // := vs var
	// contains filtered or unexported fields
}

IRVarDecl is a variable declaration.

type IRVarGroupDecl added in v0.7.0

type IRVarGroupDecl struct {
	Vars []IRVarDecl
	// contains filtered or unexported fields
}

IRVarGroupDecl is a package-level variable declaration (var block).

type PackageAnalysis

type PackageAnalysis struct {
	Name         string
	Version      string
	EntryFile    string   // Resolved entry point (.ts file)
	SourceFiles  []string // All .ts source files
	IsPureTS     bool
	Dependencies []string
	GoImportPath string // Resolved Go import path for this package
}

PackageAnalysis holds the result of analyzing an npm package.

type ProjectResult

type ProjectResult struct {
	// Files maps output file paths (relative to outDir) to Go source code.
	Files  map[string]string
	Errors []string
	// GoImports holds third-party Go module paths imported via go: prefix.
	GoImports []string
}

ProjectResult holds the output of a multi-file transpilation.

func TranspileProject

func TranspileProject(files []string, entryFile string, _ string, moduleName string) (*ProjectResult, error)

TranspileProject transpiles multiple TypeScript files into a Go project. entryFile is the main file (gets func main()), others become library packages. moduleName is the Go module name (e.g., "myapp").

func TranspileProjectWithNpm

func TranspileProjectWithNpm(files []string, entryFile string, _ string, moduleName string) (*ProjectResult, error)

TranspileProjectWithNpm transpiles multiple TS files with npm package resolution.

type TranspileResult

type TranspileResult struct {
	GoSource string // The generated Go source code
	Errors   []string
}

TranspileResult holds the output of a transpilation.

func TranspileFile

func TranspileFile(filename string, pkgName string) (*TranspileResult, error)

TranspileFile transpiles a single TypeScript file to Go source code. The file is treated as the entry point (generates func main()).

func TranspileFileIR added in v0.7.0

func TranspileFileIR(filename string, pkgName string) (*TranspileResult, error)

TranspileFileIR transpiles a TypeScript file using the IR pipeline.

func TranspileLibraryFile

func TranspileLibraryFile(filename string, pkgName string) (*TranspileResult, error)

TranspileLibraryFile transpiles a TypeScript file as a library (no func main()). Top-level statements become func init().

func TranspileLibraryFileIR added in v0.7.0

func TranspileLibraryFileIR(filename string, pkgName string) (*TranspileResult, error)

TranspileLibraryFileIR transpiles a TypeScript file as a library using the IR pipeline.

func TranspileSource

func TranspileSource(filename string, source string, pkgName string) (*TranspileResult, error)

TranspileSource transpiles TypeScript source code to Go source code.

func TranspileSourceIR added in v0.7.0

func TranspileSourceIR(filename string, source string, pkgName string) (*TranspileResult, error)

TranspileSourceIR transpiles TypeScript source code using the IR pipeline.

type Transpiler

type Transpiler struct {
	// contains filtered or unexported fields
}

Transpiler holds the state for a TypeScript-to-Go transpilation session.

type TypeGenerator

type TypeGenerator struct {
	// contains filtered or unexported fields
}

TypeGenerator generates TypeScript .d.ts declarations from Go packages.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL