lower

package
v0.0.1-beta.9 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: BSD-3-Clause Imports: 30 Imported by: 0

Documentation

Overview

Package lower is goesm's semantic lowering: it walks the typed Go AST (syntax from go/parser, semantics from go/types, both run by the go toolchain via go/packages) and emits one TypeScript module per Go package. Go-specific semantics that JavaScript lacks are expressed as calls into @goesm/runtime. Go's type checker makes every typing decision; the TypeScript types only describe the result (CI checks them with tsc).

Index

Constants

View Source
const (
	RuntimeFile = "@goesm/runtime/index.ts"
	NativesFile = "@goesm/runtime/natives.ts"
	ProgramFile = "@goesm/runtime/program.ts"
	JSABIFile   = "@goesm/runtime/jsabi.ts"
)

Layout of the generated TypeScript: the module of Go package p is the file p + ".ts" below the output root (example.com/app/cart.ts, strings.ts), and the runtime is @goesm/runtime/index.ts (natives: natives.ts) next to them. Modules import each other with relative specifiers ending in .ts, which TypeScript (allowImportingTsExtensions), Vite, Rolldown, esbuild and Bun resolve without configuration. A Go import path cannot start with "@", so the runtime never collides with a Go package.

View Source
const NoCheck = "// @ts-nocheck\n/* eslint-disable */\n"

NoCheck heads every generated module and runtime file: the code is type-checked by goesm's own tests (TestTSC), and a project's tsconfig (noUnusedLocals, noFallthroughCasesInSwitch, an ES2017 target that has no BigInt literals) or linter should not re-check it. Importers still see the modules' types.

Variables

This section is empty.

Functions

func EmbeddedFiles

func EmbeddedFiles(fset *token.FileSet, pkg *packages.Package) ([]string, error)

EmbeddedFiles returns the files the //go:embed directives of pkg embed, as absolute paths, sorted: the lowering reads them (internal/build hashes them into the cache key of the package's module).

func JSImportSpecifier

func JSImportSpecifier(file, target string) (old, new string)

JSImportSpecifier is the specifier a module written to file imports the file target with: generated modules import the JS and TS files of //goesm:import directives by absolute path, recorded in Module.Files, and internal/build makes them relative to where it writes the module.

func ModuleFile

func ModuleFile(importPath string) string

ModuleFile is the path of the module of a Go package below the root.

Types

type Diagnostic

type Diagnostic struct {
	Pos token.Position
	Msg string
	// Func is the full name of the function a warning is about.
	Func string `json:",omitempty"`
}

Diagnostic is a lowering diagnostic at an original .go position. These are goesm limitations ("not yet supported"), never Go compile errors: the frontend has already accepted the program.

func (Diagnostic) String

func (d Diagnostic) String() string

type Module

type Module struct {
	Path   string // Go import path
	TS     string // TypeScript source including an inline source map
	Map    []byte // generated TS -> .go source map (also inlined in TS)
	Native bool   // false: nothing to emit (e.g. package unsafe)
	// DTS declares the JS calling ABI of an entry package's module, its
	// exported functions and handle classes, as a TypeScript declaration
	// file (goesm emit-ts -dts); "" for other packages.
	DTS string
	// Files are the JS and TS files the module imports for //goesm:import
	// directives, by absolute path (see JSImportSpecifier).
	Files []string
}

Module is the lowering result for one Go package.

type Options

type Options struct {
	// Entries are the import paths of the packages a build starts from
	// (one for a program, several when one program serves several entry
	// points, such as the components of an app). An entry's `func main`,
	// if present, runs when its module is evaluated, and JavaScript calls
	// its exported functions and methods.
	Entries []string
}

Options control lowering.

func (Options) IsEntry

func (o Options) IsEntry(path string) bool

IsEntry reports whether the package path is one of the entries.

type Program

type Program struct {
	Fset *token.FileSet
	Pkgs []*packages.Package

	// Entries are the paths of the packages a build starts from, whose
	// exported functions and methods JavaScript calls (Options.Entries);
	// see reach.go.
	Entries map[string]bool

	// TracksGoroutines is set when the program uses goroutine-local storage
	// (runtime.GetTraceContextFromGLS and friends): async functions then
	// restore the running goroutine after every await.
	TracksGoroutines bool

	// Deps are the packages of third-party modules (see loader.Program).
	// Like the standard library, their functions that goesm cannot lower
	// become stubs that panic when called.
	Deps map[*packages.Package]bool

	Diags []Diagnostic
	// Warns are standard library and dependency functions that were
	// replaced by stubs that panic when called.
	Warns []Diagnostic
	// contains filtered or unexported fields
}

Program holds whole-program facts needed while lowering any one package.

func NewProgram

func NewProgram(fset *token.FileSet, pkgs []*packages.Package, std map[*packages.Package]bool) *Program

func (*Program) BoxOf

func (p *Program) BoxOf(T types.Type) *boxInfo

BoxOf is boxOf, cached. It depends only on DynMethod and CalledMethod of the methods of T, which Facts covers.

func (*Program) CallAlwaysAsync

func (p *Program) CallAlwaysAsync(info *types.Info, call *ast.CallExpr) bool

CallAlwaysAsync reports whether a call that may block is always of an async function, which returns a Promise: a call of a declared function or method, or a waiting lock. A call of a function value or an interface method may be of a function that is not async.

func (*Program) CallBlocks

func (p *Program) CallBlocks(info *types.Info, call *ast.CallExpr) bool

CallBlocks reports whether the call may block (and must be awaited).

func (*Program) CallBlocksIn

func (p *Program) CallBlocksIn(info *types.Info, call *ast.CallExpr, assume *types.Func) bool

CallBlocksIn is CallBlocks for a call in the synchronous clone of assume (paramsync.go), or, for a nil assume, anywhere else.

func (*Program) CalledMethod

func (p *Program) CalledMethod(fn *types.Func) bool

CalledMethod reports whether method fn, listed in method tables (DynMethod), may be called through them: whether the program calls an interface method that it implements, and stores a type with the method in an interface value. A method left out has an entry without its function.

func (*Program) DynMethod

func (p *Program) DynMethod(fn *types.Func) bool

DynMethod reports whether method fn (a method of a concrete type, possibly promoted) belongs in method tables.

func (*Program) Facts

func (p *Program) Facts() (digests map[*packages.Package][32]byte, ok bool)

Facts returns, for every package, a digest of the whole-program facts that lowering it reads: what the blocking, address and linkname analyses decided about the functions, literals, range statements and variables the package declares, and the answers to the per-node questions the lowering asks the Program (CallBlocks, CallAlwaysAsync, RangeBlocks, WaitLock, WaitLockVal, SyncClone, and CallBlocksIn for the calls in clones). The module of a package is fully determined by its own source, the source of the packages it depends on, these digests for itself and its dependencies, and the Program-wide switches; internal/build keys its cache on them. Positions in the digests are offsets within files, so editing one package does not change the digests of the others.

ok is false if a fact could not be attributed to a package, in which case nothing may be cached.

Every Program field that lowering reads must be covered here; TestFactsCoverProgram fails when lowering reads one that is not.

func (*Program) HasClone

func (p *Program) HasClone(fn *types.Func) bool

HasClone reports whether fn has a synchronous clone.

func (*Program) ImportedEntry

func (p *Program) ImportedEntry(path string) bool

ImportedEntry reports whether the entry package path is also imported by another package of the program, as a component's package imports a package that JavaScript imports too. JavaScript calls the exported functions of an entry under their Go names, through wrappers that convert its values (exportWrapper); such an entry also exports the functions themselves, for the Go code importing it, as Name$go, and its exported methods as Type$Method$go (goMethodSuffix).

func (*Program) InitCalled

func (p *Program) InitCalled(fn *types.Func) bool

InitCalled reports whether the module calls init function fn: one that only assigns package-level variables runs only if reachable code uses one of them.

func (*Program) IsAsync

func (p *Program) IsAsync(fn *types.Func) bool

IsAsync reports whether the function declared by fn may block.

func (*Program) JSONv2

func (p *Program) JSONv2() bool

JSONv2 reports whether a package of the program outside encoding/json declares a method named MarshalJSONTo or UnmarshalJSONFrom, which json v2 calls (json.Number's are encoding/json's own). Without one, encoding/json's Marshal and Unmarshal go to its legacy encoder and decoder, and json v2 is left out (see the patch of v2_decode.go).

func (*Program) LazyVar

func (p *Program) LazyVar(v *types.Var) bool

LazyVar reports whether the initializer of package-level variable v has no effect besides computing its value (effects.go), so that it is declared as a pure expression.

func (*Program) LitAsync

func (p *Program) LitAsync(lit *ast.FuncLit) bool

LitAsync reports whether a function literal may block.

func (*Program) LowerAll

func (p *Program) LowerAll(opts Options) []*Module

LowerAll lowers every package of the program, dependencies first.

func (*Program) LowerPackage

func (p *Program) LowerPackage(pkg *packages.Package, opts Options) *Module

LowerPackage lowers one package of the program. LowerAll is LowerPackage for every package; lowering one package never depends on whether another was lowered, which lets internal/build reuse cached modules.

func (*Program) PureEmitter

func (p *Program) PureEmitter(pkg *types.Package) *pkgEmitter

PureEmitter returns an emitter of the package pkg that only answers whether its functions return pure expressions (returnsPure), for the lowering of an importer of pkg.

func (*Program) RangeBlocks

func (p *Program) RangeBlocks(info *types.Info, s *ast.RangeStmt) bool

RangeBlocks reports whether a range-over-func statement's call of its iterator may block (and must be awaited).

func (*Program) RangeBodyAsync

func (p *Program) RangeBodyAsync(s *ast.RangeStmt) bool

RangeBodyAsync reports whether the body of a range-over-func loop (its yield function) may block.

func (*Program) RegexpJS

func (p *Program) RegexpJS() map[string]string

RegexpJS returns the jsPattern entries of the patterns the program compiles, if it matches every regular expression with a RegExp (regexpjs.go), or nil.

func (*Program) SetEntries

func (p *Program) SetEntries(paths []string)

NewProgram analyses the loaded packages (dependencies first). std is the set of standard library packages. SetEntries sets the entry packages (Options.Entries).

func (*Program) SortedDiags

func (p *Program) SortedDiags() []Diagnostic

SortedDiags returns diagnostics in position order.

func (*Program) SortedWarns

func (p *Program) SortedWarns() []Diagnostic

SortedWarns returns warnings in position order. SortedWarns returns the warnings about functions that code reachable from the program's roots may call: the others are never called, so a stub does no harm.

func (*Program) StdFixed

func (p *Program) StdFixed(name string) bool

StdFixed reports whether the program never changes the variable name of stdFiles (see printCall).

func (*Program) StoredType

func (p *Program) StoredType(T types.Type) bool

StoredType reports whether reachable code may store a value of type T (a defined type or a pointer to one) in an interface value: whether one of the methods of T is a method of a stored type. The method table of a type never stored is left empty, as the dynamic type of no interface value is ever T: type assertions, interface calls and reflection never look it up, and the signatures of its methods do not keep the types they mention. A type that has methods still gets an empty table ($rt.hasMethods).

func (*Program) SyncClone

func (p *Program) SyncClone(info *types.Info, call *ast.CallExpr, assume *types.Func) bool

SyncClone reports whether call calls the synchronous clone of its function (see above). assume is the function whose clone the call is in, or nil.

func (*Program) SyncOnly

func (p *Program) SyncOnly(key any) bool

SyncOnly reports whether a function (*types.Func) or literal is lowered as synchronous although it contains channel operations (see natives.Sync).

func (*Program) UnicodeClasses

func (p *Program) UnicodeClasses() bool

UnicodeClasses reports whether the program may parse a regular expression with a Unicode class (\p or \P): whether reachable code outside regexp passes a pattern that is not a constant to one of patternFuncs, or one with \p or \P, refers to one without calling it, or reaches (*regexp.Regexp).UnmarshalText. regexp/syntax's unicodeTable is not lowered otherwise.

func (*Program) VarReached

func (p *Program) VarReached(v *types.Var, init ast.Expr) bool

VarReached reports whether the initializer of package-level variable v may run: one without effects runs only if reachable code uses v (reach.go); the module leaves the others out.

func (*Program) WaitLock

func (p *Program) WaitLock(call *ast.CallExpr) (fn *types.Func, locker bool)

WaitLock returns the waiting function to call instead of a Lock or RLock call, or nil. For a sync.Locker call it is lockerSlow, a method of a helper type whose receiver is unused, taking the Locker as its argument.

func (*Program) WaitLockVal

func (p *Program) WaitLockVal(sel *ast.SelectorExpr) (fn *types.Func, locker bool)

WaitLockVal returns the waiting function a Lock method value or method expression value is bound to, or nil (see WaitLock).

Jump to

Keyboard shortcuts

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