ixgo

package module
v1.2.6 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: Apache-2.0 Imports: 43 Imported by: 14 modules, 6 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ¶

iXGo The Go/XGo Interpreter

Build Status Coverage Status Go Reference

A fast Go interpreter that supports all Go language features, including generics and generic methods.

Go Version
  • Go 1.25 ~ 1.27
Compilers
Platforms
  • macOS
  • Linux
  • Windows
  • WebAssembly
Go ABI
Generics
  • Supports type parameters (generics)
  • Supports generic type aliases
  • Supports generic methods (Go 1.27)
install ixgo command line
go install github.com/goplus/ixgo/cmd/ixgo@latest
install ixgo export command line
go install github.com/goplus/ixgo/cmd/qexp@latest
ixgo command
ixgo             # ixgo repl mode
ixgo run         # run a Go/XGo package
ixgo build       # compile a Go/XGo package
ixgo test        # test a package
ixgo version     # print version
ixgo export      # export Go package to ixgo builtin package
ixgo run mode
Usage: ixgo run [build flags] [package] [arguments...]
  -exp-gc
    	experimental support runtime.GC
  -mod value
    	module download mode to use: readonly, vendor, or mod.
  -ssa
    	print SSA instruction code
  -ssa-trace
    	trace SSA interpreter code
  -tags value
    	a comma-separated list of build tags to consider satisfied during the build
  -v	print the names of packages as they are compiled.
  -x	print the commands.
ixgo repl mode
ixgo                       # run repl mode, support Go/XGo
ixgo repl                  # run repl mode, support Go/XGo
ixgo repl -go              # run repl mode, disable XGo syntax
ixgo test unsupported features
  • test -fuzz
  • test -cover
ifacefuncval (optional)

Alternative to reflectx icall stubs: methods share makeFuncStub. reflectx stores an untagged *makeFuncImpl in addReflectOff and sets tflagIfaceFuncval (1<<6). A patched runtime tags itab.Fun (makeFuncImpl*|1) so interface calls unwrap.

Needs a patched Go 1.25.x, 1.26.x, or 1.27.x and -tags goplus.ifacefuncval. Supported GOARCH: wasm, arm64, amd64, 386.

go install github.com/goplus/reflectx/cmd/iface_patch@latest
iface_patch /path/to/go   # 1.25.x, 1.26.x, or 1.27.x
cd /path/to/go/src && ./make.bash
export GOROOT=/path/to/go
export PATH="$GOROOT/bin:$PATH"
go test -tags goplus.ifacefuncval .
# wasip1: GOOS=wasip1 GOARCH=wasm go test -exec wasmtime -tags goplus.ifacefuncval .

Without the tag, a patched compiler matches official gc. An unpatched compiler still accepts the tag; interface method calls then trap.

You can export GOFLAGS='-tags=goplus.ifacefuncval', or prefix a command: GOFLAGS='-tags=goplus.ifacefuncval' go build (also go run / go test).

See goplus/reflectx cmd/iface_patch.

packages (optional)

Optional optimization packages can be enabled with blank imports:

Package Purpose
directcall Speeds up calls to supported standard-library functions with direct-call adapters. Import ixgo/pkg or individual export packages separately as needed.
directfunc Speeds up calls to interpreted closures and function values with supported signatures, including repeated calls inside loops.
memo Caches results and supported state transformations for eligible recursive functions and receiver methods. Use ixgo.DisableMemo to disable installation for a Context.
import (
	_ "github.com/goplus/ixgo/directcall"
	_ "github.com/goplus/ixgo/directfunc"
	_ "github.com/goplus/ixgo/memo"
)

These packages work with the standard Go toolchain. See each package's documentation for supported paths and limitations.

ixgo demo
The XGo Playground (WebAssembly)
The XGo REPL Playground (WebAssembly)
run simple Go source demo
package main

import (
	"github.com/goplus/ixgo"
	_ "github.com/goplus/ixgo/pkg/fmt"
)

var source = `
package main

import "fmt"

func main() {
	fmt.Println("Hello, World")
}
`

func main() {
	_, err := ixgo.RunFile("main.go", source, nil, 0)
	if err != nil {
		panic(err)
	}
}
run simple XGo source demo
package main

import (
	"github.com/goplus/ixgo"
	_ "github.com/goplus/ixgo/xgobuild"
)

var source = `
languages := [
	"C",
	"Go",
	"Python",
	"JavaScript",
]

echo "XGo :=", languages.join(" * "), "+ Scratch"
`

func main() {
	_, err := ixgo.RunFile("main.xgo", source, nil, 0)
	if err != nil {
		panic(err)
	}
}
build linkname mode
go install -tags linknamefix -ldflags="-checklinkname=0" github.com/goplus/ixgo/cmd/ixgo@latest

use runtime linkname for faster performance iter.Pull/iter.Pull2

ixgo more demo

https://github.com/visualfc/ixgo_demo

Documentation ¶

Index ¶

Constants ¶

View Source
const (
	Compiler = runtime.Compiler
	IsLLGo   = false
)

Variables ¶

View Source
var (
	ErrNotFoundMain    = errors.New("not found main package")
	ErrTestFailed      = errors.New("test failed")
	ErrNotFoundPackage = errors.New("not found package")
	ErrGoexitDeadlock  = errors.New("fatal error: no goroutines (main called runtime.Goexit) - deadlock!")
	ErrNoFunction      = errors.New("no function")
	ErrNoTestFiles     = errors.New("[no test files]")
	ErrNoTestProcessor = errors.New("test processor not registered: import _ \"github.com/goplus/ixgo/pkg/testing\" or call ixgo.RegisterTestProcessor")
)

Functions ¶

func AppendComplex ¶ added in v1.1.1

func AppendComplex(dst []byte, c complex128, fmt byte, prec, bitSize int) []byte

AppendComplex appends the result of FormatComplex to dst. It is here for the runtime. There is no public strconv.AppendComplex.

func DirectCallArg ¶ added in v1.1.3

func DirectCallArg[T any](ctx DirectCallContext, index int) T

DirectCallArg returns the argument at index using its generated static type. A nil interface value is converted to the zero value of T.

func GoroutineID ¶ added in v1.2.4

func GoroutineID() uint64

GoroutineID returns the ID of the current goroutine.

func IcallCached ¶ added in v0.57.0

func IcallCached() int

IcallCached return reflectx icall cached. With -tags goplus.ifacefuncval there is no stub pool; the result is 0.

func IcallStat ¶

func IcallStat() (capacity int, allocate int, aviable int)

IcallStat return reflectx icall allocate stat. With -tags goplus.ifacefuncval there is no stub pool; all three values are 0.

func IsConstNil ¶

func IsConstNil(v ssa.Value) bool

func IsNil ¶

func IsNil(v reflect.Value) bool

func PackageList ¶

func PackageList() (list []string)

PackageList return all register packages

func ParseBuiltin ¶

func ParseBuiltin(fset *token.FileSet, pkg string) (*ast.File, error)

func RegisterCustomBuiltin ¶

func RegisterCustomBuiltin(key string, fn interface{}) error

func RegisterDirectCalls ¶ added in v1.1.3

func RegisterDirectCalls(pkgPath string, bindings map[string]DirectCallAdapter)

RegisterDirectCalls registers generated direct-call bindings for pkgPath. Registration must finish before constructing an interpreter that uses the package. Later registrations replace bindings with the same selector.

func RegisterDirectFunc ¶ added in v1.2.3

func RegisterDirectFunc(typ reflect.Type, maker DirectFuncMaker)

RegisterDirectFunc registers a maker for functions of type typ. Later registrations for the same type replace earlier ones. Passing a nil maker removes the registration. Do not unregister or replace a signature while function values of that type are still in use.

The maker must return a method value of type typ whose receiver embeds DirectFuncVal as its first field. On gc, registration panics if the maker does not satisfy that contract. func() is built in and is not taken from the registry.

func RegisterDirectFuncFor ¶ added in v1.2.3

func RegisterDirectFuncFor[F any](bind func(DirectFuncVal) F)

RegisterDirectFuncFor registers a DirectFunc for signature F.

type fn struct{ ixgo.DirectFuncVal }
func (c fn) Int(n int) int { return c.Call(n).(int) }

func init() {
    ixgo.RegisterDirectFuncFor(func(c ixgo.DirectFuncVal) func(int) int {
        return fn{c}.Int
    })
}

After registration, run source that uses that signature:

src := `package main
func main() {
	add := func(x int) int { return x + 1 }
	println(add(41))
}
`
ixgo.RunFile("main.go", src, nil, 0)

bind must return a method value whose receiver embeds DirectFuncVal as its first field. Passing a nil bind removes the registration.

func RegisterEmbedProcessor ¶ added in v1.0.8

func RegisterEmbedProcessor(processor EmbedProcessor)

RegisterEmbedProcessor registers a global EmbedProcessor for embed handling.

func RegisterExternal ¶

func RegisterExternal(key string, i interface{})

RegisterExternal is register external variable address or func

func RegisterFileProcess ¶

func RegisterFileProcess(ext string, fn SourceProcessFunc)

func RegisterMemoPlugin ¶ added in v1.2.4

func RegisterMemoPlugin(plugin MemoPlugin)

RegisterMemoPlugin enables an optional optimizer package. The plugin API is experimental and may change without notice.

func RegisterPackage ¶

func RegisterPackage(pkg *Package)

RegisterPackage register a pkg.

func RegisterPackageLazy ¶ added in v1.1.0

func RegisterPackageLazy(pkg string, load func() *Package)

RegisterPackageLazy registers a pkg with lazy initialization.

func RegisterPatch ¶

func RegisterPatch(pkg string, src ...interface{})

RegisterPatch register pkg with "pkg@patch"

func RegisterTestProcessor ¶ added in v1.0.8

func RegisterTestProcessor(processor TestProcessor)

RegisterTestProcessor registers a global TestProcessor for test handling.

func ResetAllIcall ¶

func ResetAllIcall()

ResetAllIcall is reset all reflectx icall, all interp methods invalid. With -tags goplus.ifacefuncval it still invalidates methods (no stub pool).

func Run ¶

func Run(path string, args []string, mode Mode) (exitCode int, err error)

func RunFile ¶

func RunFile(filename string, src interface{}, args []string, mode Mode) (exitCode int, err error)

func RunTest ¶

func RunTest(path string, args []string, mode Mode) error

func SetValue ¶

func SetValue(v reflect.Value, x reflect.Value)

Types ¶

type Context ¶

type Context struct {
	Loader       Loader          // types loader
	BuildContext build.Context   // build context, default build.Default
	RunContext   context.Context // run context, default unset
	Importer     types.Importer  // importer

	FileSet *token.FileSet // file set

	Lookup func(root, path string) (dir string, found bool) // lookup external import

	Mode        Mode            // mode
	BuilderMode ssa.BuilderMode // ssa builder mode
	Builder     *SSABuilder     // ssa builder

	MethodChecker MethodChecker // method checker
	// contains filtered or unexported fields
}

Context ssa context

func NewContext ¶

func NewContext(mode Mode) *Context

NewContext create a new Context

func (*Context) AddImport ¶

func (ctx *Context) AddImport(path string, dir string) (err error)

func (*Context) AddImportFile ¶

func (ctx *Context) AddImportFile(path string, filename string, src interface{}) (err error)

func (*Context) IsEvalMode ¶

func (ctx *Context) IsEvalMode() bool

func (*Context) LoadAstFile ¶

func (ctx *Context) LoadAstFile(path string, file *ast.File) (*ssa.Package, error)

func (*Context) LoadAstPackage ¶

func (ctx *Context) LoadAstPackage(path string, apkg *ast.Package) (*ssa.Package, error)

func (*Context) LoadDir ¶

func (ctx *Context) LoadDir(dir string, test bool) (pkg *ssa.Package, err error)

func (*Context) LoadDirEx ¶

func (ctx *Context) LoadDirEx(dir string, test bool, getImportPath func(pkgName string, dir string) (string, bool)) (pkg *ssa.Package, err error)

func (*Context) LoadFile ¶

func (ctx *Context) LoadFile(filename string, src interface{}) (*ssa.Package, error)

func (*Context) LoadInterp ¶

func (ctx *Context) LoadInterp(filename string, src interface{}) (*Interp, error)

func (*Context) NewInterp ¶

func (ctx *Context) NewInterp(mainPkg *ssa.Package) (*Interp, error)

func (*Context) ParseFile ¶

func (ctx *Context) ParseFile(filename string, src interface{}) (*ast.File, error)

func (*Context) PrebuildSSA ¶ added in v0.60.0

func (ctx *Context) PrebuildSSA(pkgs ...string) (err error)

func (*Context) RegisterExternal ¶

func (ctx *Context) RegisterExternal(key string, i interface{})

RegisterExternal register external value must variable address or func.

func (*Context) RegisterPatch ¶ added in v0.57.0

func (ctx *Context) RegisterPatch(pkg string, src interface{}) error

func (*Context) Run ¶

func (ctx *Context) Run(path string, args []string) (exitCode int, err error)

func (*Context) RunFile ¶

func (ctx *Context) RunFile(filename string, src interface{}, args []string) (exitCode int, err error)

func (*Context) RunFunc ¶

func (ctx *Context) RunFunc(mainPkg *ssa.Package, fnname string, args ...Value) (ret Value, err error)

func (*Context) RunInterp ¶

func (ctx *Context) RunInterp(interp *Interp, input string, args []string) (exitCode int, err error)

func (*Context) RunPkg ¶

func (ctx *Context) RunPkg(mainPkg *ssa.Package, input string, args []string) (exitCode int, err error)

func (*Context) RunTest ¶

func (ctx *Context) RunTest(dir string, args []string) error

func (*Context) SetDebug ¶

func (ctx *Context) SetDebug(fn func(*DebugInfo))

SetDebug enables debug metadata and sets its callback. For compiled code with metadata, the callback can be replaced or cleared without recompilation.

func (*Context) SetEvalMode ¶

func (ctx *Context) SetEvalMode(b bool)

func (*Context) SetExecutionTracker ¶ added in v1.2.4

func (ctx *Context) SetExecutionTracker(tracker *ExecutionTracker)

SetExecutionTracker binds a tracker to subsequently compiled interpreters. Set it before loading code, never concurrently with compilation. Nil disables tracking but leaves existing debug metadata enabled. SetDebug and SetFuncHook remain independent.

func (*Context) SetFuncHook ¶ added in v1.2.4

func (ctx *Context) SetFuncHook(entry func(*FuncInfo), leave func(*FuncInfo))

SetFuncHook sets callbacks invoked when an interpreted function is entered and when it exits. Either callback may be nil. The leave callback runs after user defers, including when the function unwinds due to panic, runtime.Goexit, or os.Exit. These are interpreter exit notifications; they do not imply that real Go executes defers on os.Exit.

Hooks are captured when functions are compiled by NewInterp. Set them before compilation; later changes do not affect already compiled functions. Do not call SetFuncHook concurrently with compilation. Callbacks may run concurrently from interpreted goroutines and must synchronize any shared state. FuncInfo and its embedded Frame must not be retained after the callback returns.

A non-nil leave callback adds an internal defer and enables panic unwinding for each interpreted function, adding execution overhead. Functions compiled without hooks retain their usual execution paths.

func (*Context) SetLeastCallForEnablePool ¶

func (ctx *Context) SetLeastCallForEnablePool(count int)

SetLeastCallForEnablePool set least call count for enable function pool, default 64

func (*Context) SetPanic ¶

func (ctx *Context) SetPanic(fn func(*PanicInfo))

func (*Context) SetPrintOutput ¶

func (ctx *Context) SetPrintOutput(output *bytes.Buffer)

SetPrintOutput is captured builtin print/println output

func (*Context) SetUnsafeSizes ¶

func (ctx *Context) SetUnsafeSizes(sizes types.Sizes)

SetUnsafeSizes set the sizing functions for package unsafe.

func (*Context) SourcePackage ¶

func (ctx *Context) SourcePackage(path string) *SourcePackage

func (*Context) TestPkg ¶

func (ctx *Context) TestPkg(pkg *ssa.Package, input string, args []string) error

type DebugInfo ¶

type DebugInfo struct {
	*ssa.DebugRef
	// contains filtered or unexported fields
}

func (*DebugInfo) AsFunc ¶

func (i *DebugInfo) AsFunc() (*types.Func, bool)

func (*DebugInfo) AsVar ¶

func (i *DebugInfo) AsVar() (*types.Var, interface{}, bool)

func (*DebugInfo) Position ¶

func (i *DebugInfo) Position() token.Position

type DirectCallAdapter ¶ added in v1.1.3

type DirectCallAdapter func(DirectCallContext)

DirectCallAdapter is a qexp-generated, reflection-free call adapter.

type DirectCallContext ¶ added in v1.1.3

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

DirectCallContext gives a generated direct-call adapter access to the current call's arguments and result register.

func (DirectCallContext) SetResult ¶ added in v1.1.3

func (ctx DirectCallContext) SetResult(result any)

SetResult stores the result produced by a generated direct-call adapter.

type DirectFuncMaker ¶ added in v1.2.3

type DirectFuncMaker func(DirectFuncVal) reflect.Value

DirectFuncMaker builds a Go function value for an interpreted function of a specific signature. The result should be a method value whose receiver embeds DirectFuncVal as its first field, so the interpreter can recover the payload without reflect.MakeFunc.

type DirectFuncVal ¶ added in v1.2.3

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

DirectFuncVal is the receiver payload for DirectFunc method values. Embed it as the first field of a value receiver, then register the method:

type fn struct{ ixgo.DirectFuncVal }
func (c fn) Int(n int) int { return c.Call(n).(int) }

func init() {
    ixgo.RegisterDirectFuncFor(func(c ixgo.DirectFuncVal) func(int) int {
        return fn{c}.Int
    })
}

Interpreted functions of that type then call as ordinary Go functions. func() is built in. Import github.com/goplus/ixgo/directfunc for common func() T results.

func (DirectFuncVal) Call ¶ added in v1.2.3

func (c DirectFuncVal) Call(args ...any) any

Call runs the interpreted function and returns its result. A function with no result returns nil. Multiple results are returned as a Tuple.

func (DirectFuncVal) CallDiscard ¶ added in v1.2.3

func (c DirectFuncVal) CallDiscard(args ...any)

CallDiscard runs the interpreted function and discards its results.

type EmbedProcessor ¶ added in v1.0.8

type EmbedProcessor interface {
	LoadPkg(bp *build.Package, fset *token.FileSet, files []*ast.File, test bool, xtest bool) (*ast.File, error)
	LoadFiles(pkgName string, dir string, fset *token.FileSet, files []*ast.File) (*ast.File, error)
}

EmbedProcessor handles processing of embed directives and returns a embed data AST file.

type Eval ¶

type Eval struct {
	Value interface{} // constant.Value or interface{}
	Type  reflect.Type
}

func (*Eval) String ¶

func (e *Eval) String() string

type ExecutionOptions ¶ added in v1.2.4

type ExecutionOptions struct {
	// Filter runs during compilation; nil accepts all valid positions.
	// It must return consistent results and be safe for concurrent compilation.
	Filter func(token.Position) bool
	// ReportRepeated reports every accepted DebugRef position, even on the same
	// line. Caller restores and clears remain deduplicated.
	ReportRepeated bool
}

ExecutionOptions controls source-position reporting.

type ExecutionPosition ¶ added in v1.2.4

type ExecutionPosition struct {
	GoroutineID uint64
	Position    token.Position
	// Clear removes the location. Position is zero for clear events.
	Clear bool
	// Sequence increases within a tracker. Keep the latest per goroutine,
	// including clears, to ignore delayed events.
	Sequence uint64
}

ExecutionPosition reports a goroutine's source location.

type ExecutionTracker ¶ added in v1.2.4

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

ExecutionTracker tracks each goroutine's source position, merging consecutive positions on the same line unless ReportRepeated is set. Calls inherit their caller's position and restore it after user defers; the outermost call clears it on exit. Positions come from DebugRef metadata, not a callback before every statement. Share a tracker across interpreters to follow synchronous host callbacks between them.

Create with NewExecutionTracker, do not copy, and Close when the session ends. Interpreter control methods, including RunMain and Abort, do not close it.

func NewExecutionTracker ¶ added in v1.2.4

func NewExecutionTracker(hook func(ExecutionPosition), options ...ExecutionOptions) *ExecutionTracker

NewExecutionTracker creates a source-line tracking session. Omitting options uses defaults; passing more than one panics. Callbacks run synchronously and may overlap, without tracker locks held. They must return normally and promptly; events may be retained or queued. Use the event's GoroutineID and Sequence to update host state. Tracking adds execution overhead.

func (*ExecutionTracker) Close ¶ added in v1.2.4

func (t *ExecutionTracker) Close()

Close stops tracking and sends clears synchronously on the closing goroutine, including for pending notifications. Execution continues. Repeated calls do not wait. In-flight callbacks may still arrive; retain sequence watermarks after clears. To track again, create a new tracker and recompile.

type ExitError ¶

type ExitError int

func (ExitError) Error ¶

func (r ExitError) Error() string

type FatalError ¶

type FatalError struct {
	Value value
	// contains filtered or unexported fields
}

run func fatal error

func (FatalError) Error ¶

func (p FatalError) Error() string

func (FatalError) Stack ¶

func (p FatalError) Stack() []byte

type FindMethod ¶

type FindMethod interface {
	FindMethod(mtyp reflect.Type, fn *types.Func) func([]reflect.Value) []reflect.Value
}

type Frame ¶

type Frame = frame

func (*Frame) CallerFrames ¶

func (fr *Frame) CallerFrames() (frames []runtime.Frame)

type FuncInfo ¶ added in v1.2.4

type FuncInfo struct {
	*ssa.Function
	*Frame
	// contains filtered or unexported fields
}

FuncInfo describes an interpreted function invocation. Its embedded Frame is valid only during the hook callback and must not be retained.

func (*FuncInfo) Position ¶ added in v1.2.4

func (i *FuncInfo) Position() token.Position

Position returns the function declaration position, not the call or exit site.

type Importer ¶

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

func NewImporter ¶

func NewImporter(ctx *Context) *Importer

func (*Importer) Import ¶

func (i *Importer) Import(path string) (ret *types.Package, err error)

type Interp ¶

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

func NewInterp ¶

func NewInterp(ctx *Context, mainpkg *ssa.Package) (*Interp, error)

func (*Interp) Abort ¶

func (i *Interp) Abort()

func (*Interp) Exit ¶

func (i *Interp) Exit(code int)

func (*Interp) ExitCode ¶

func (i *Interp) ExitCode() int

func (*Interp) FindMethod ¶

func (i *Interp) FindMethod(mtyp reflect.Type, fn *types.Func) func([]reflect.Value) []reflect.Value

func (*Interp) GetConst ¶

func (i *Interp) GetConst(key string) (constant.Value, bool)

func (*Interp) GetFunc ¶

func (i *Interp) GetFunc(key string) (interface{}, bool)

func (*Interp) GetSymbol ¶

func (i *Interp) GetSymbol(key string) (m ssa.Member, v interface{}, ok bool)

func (*Interp) GetType ¶

func (i *Interp) GetType(key string) (reflect.Type, bool)

func (*Interp) GetVarAddr ¶

func (i *Interp) GetVarAddr(key string) (interface{}, bool)

func (*Interp) IcallAlloc ¶

func (i *Interp) IcallAlloc() int

IcallAlloc return reflectx icall allocate for this interp. With -tags goplus.ifacefuncval there is no stub pool; the result is 0.

func (*Interp) MainPkg ¶

func (i *Interp) MainPkg() *ssa.Package

func (*Interp) ResetIcall ¶

func (i *Interp) ResetIcall()

ResetIcall is reset reflectx icall, all methods invalid. With -tags goplus.ifacefuncval it still invalidates methods (no stub pool).

func (*Interp) RunFunc ¶

func (i *Interp) RunFunc(name string, args ...Value) (r Value, err error)

func (*Interp) RunInit ¶

func (i *Interp) RunInit() (err error)

func (*Interp) RunMain ¶

func (i *Interp) RunMain() (exitCode int, err error)

func (*Interp) UnsafeRelease ¶

func (i *Interp) UnsafeRelease()

UnsafeRelease is unsafe release relectx icall.

type Loader ¶

type Loader interface {
	Import(path string) (*types.Package, error)
	Installed(path string) (*Package, bool)
	Packages() []*types.Package
	LookupReflect(typ types.Type) (reflect.Type, bool)
	LookupTypes(typ reflect.Type) (types.Type, bool)
	SetImport(path string, pkg *types.Package, load func() error) error
	Iterate(f func(typ types.Type, value interface{}))
}

Loader types loader interface

func NewTypesLoader ¶

func NewTypesLoader(ctx *Context, mode Mode) Loader

NewTypesLoader install package and readonly

type MemoInstaller ¶ added in v1.2.4

type MemoInstaller interface {
	InstallScalarMemo()
	InstallReceiverMemo(*MemoReceiverPlan)
	InstallAccumulatorMemo(output int, state bool)
}

MemoInstaller exposes the memoization installers available to an optional optimizer.

type MemoPlugin ¶ added in v1.2.4

type MemoPlugin func(MemoInstaller, *ssa.Function)

MemoPlugin is called for each eligible function when an optional memo package is registered.

type MemoReceiverPlan ¶ added in v1.2.4

type MemoReceiverPlan struct {
	Receiver  *MemoReceiverState
	Functions map[*ssa.Function]bool
	Updates   map[*ssa.Store]MemoReceiverUpdate
}

MemoReceiverPlan describes the receiver state needed by the interpreter.

type MemoReceiverState ¶ added in v1.2.4

type MemoReceiverState struct {
	Fields   [][]int
	Additive []bool
	Affine   []bool
	Bitwise  []bool
}

MemoReceiverState describes the cached numerical leaves of a receiver.

type MemoReceiverUpdate ¶ added in v1.2.4

type MemoReceiverUpdate struct {
	Field   int
	Op      token.Token
	Operand ssa.Value
}

MemoReceiverUpdate records an isolated store that updates one cached leaf.

type MethodChecker ¶ added in v1.1.0

type MethodChecker func(ctx *Context, prog *ssa.Program) func(typ reflect.Type, method reflectx.Method) bool

MethodChecker returns a validator that reports whether method is valid for typ.

type Mode ¶

type Mode uint

Mode is a bitmask of options affecting the interpreter.

const (
	DisableRecover                 Mode          = 1 << iota // Disable recover() in target programs; show interpreter crash instead.
	DisableCustomBuiltin                                     // Disable load custom builtin func
	EnableDumpImports                                        // print import packages
	EnableDumpInstr                                          // Print packages & SSA instruction code
	EnableTracing                                            // Print a trace of all instructions as they are interpreted.
	EnablePrintAny                                           // Enable builtin print for any type ( struct/array )
	EnableNoStrict                                           // Enable no strict mode
	ExperimentalSupportGC                                    // experimental support runtime.GC
	SupportMultipleInterp                                    // Support multiple interp, must manual release interp reflectx icall.
	CheckGopOverloadFunc                                     // Check and skip gop overload func
	DisableAutoLoadPatchs                                    // Disable automatic loading of package patches.
	DisableDynamicFuncCallAnalysis                           // Disable dynamic func call analysis and optimization.
	OptionLoadRutimeImethod                                  // Option load runtime imethod for less imethod and memory space.
	OptionLoadAllImethod                                     // Option load all imethod.
	EnableCachedReg                                          // Enable per-frame cache registers.
	DisableMemo                                              // Disable the optional memo optimizer.
	OptionLoadDefaultImethod       = 0                       // Option load default imethod.
	LastMode                       = DisableMemo             // Last Mode
)

type Package ¶

type Package struct {
	Interfaces    map[string]reflect.Type
	NamedTypes    map[string]reflect.Type
	AliasTypes    map[string]reflect.Type
	Vars          map[string]reflect.Value
	Funcs         map[string]reflect.Value
	TypedConsts   map[string]TypedConst
	UntypedConsts map[string]UntypedConst
	Deps          map[string]string // path -> name
	Alias         map[string]alias.Type
	Name          string
	Path          string
	Source        string
	Import        func(fset *token.FileSet, pkgs map[string]*types.Package) (*types.Package, error)
}

func LookupPackage ¶

func LookupPackage(name string) (pkg *Package, ok bool)

LookupPackage lookup register pkgs

type PanicError ¶

type PanicError struct {
	Value value
	// contains filtered or unexported fields
}

If the target program panics, the interpreter panics with this type.

func (PanicError) Error ¶

func (p PanicError) Error() string

func (PanicError) Stack ¶

func (p PanicError) Stack() []byte

type PanicInfo ¶

type PanicInfo struct {
	*Frame

	Error error // PanicError / FatalError / PlainError / RuntimeError
	// contains filtered or unexported fields
}

func (*PanicInfo) Position ¶

func (i *PanicInfo) Position() token.Position

type PlainError ¶

type PlainError string

func (PlainError) Error ¶

func (e PlainError) Error() string

func (PlainError) RuntimeError ¶

func (e PlainError) RuntimeError()

type Repl ¶

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

func NewRepl ¶

func NewRepl(ctx *Context) *Repl

NewRepl creates a REPL.

func (*Repl) Eval ¶

func (r *Repl) Eval(expr string) (tok token.Token, dump []*Eval, err error)

func (*Repl) Interp ¶

func (r *Repl) Interp() *Interp

func (*Repl) SetFileName ¶

func (r *Repl) SetFileName(filename string)

func (*Repl) Source ¶

func (r *Repl) Source() string

type RuntimeError ¶

type RuntimeError string

func (RuntimeError) Error ¶

func (e RuntimeError) Error() string

func (RuntimeError) RuntimeError ¶

func (e RuntimeError) RuntimeError()

type SSABuilder ¶ added in v0.60.0

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

SSABuilder builds SSA (Static Single Assignment) form packages incrementally. It maintains a program and tracks which packages have already been created to avoid duplicate builds.

func NewSSABuilder ¶ added in v0.60.0

func NewSSABuilder(ctx *Context) *SSABuilder

func (*SSABuilder) BuildImports ¶ added in v0.60.0

func (b *SSABuilder) BuildImports(pkg *types.Package, src bool)

func (*SSABuilder) BuildMain ¶ added in v0.60.0

func (b *SSABuilder) BuildMain(sp *SourcePackage) (pkg *ssa.Package, err error)

func (*SSABuilder) BuildPackages ¶ added in v0.60.0

func (b *SSABuilder) BuildPackages(pkgs []*types.Package)

func (*SSABuilder) PrebuildSSA ¶ added in v0.60.0

func (b *SSABuilder) PrebuildSSA(packages ...string) error

func (*SSABuilder) Program ¶ added in v0.60.0

func (b *SSABuilder) Program() *ssa.Program

func (*SSABuilder) Reset ¶ added in v0.60.0

func (b *SSABuilder) Reset()

type SourcePackage ¶

type SourcePackage struct {
	Context  *Context
	Package  *types.Package
	Info     *types.Info
	Importer types.Importer
	Files    []*ast.File
	Links    []*load.LinkSym
	Dir      string
	Register bool // register package
	NoCache  bool // skip caching in importer
}

func (*SourcePackage) Load ¶

func (sp *SourcePackage) Load() (err error)

func (*SourcePackage) Loaded ¶

func (sp *SourcePackage) Loaded() bool

type SourceProcessFunc ¶

type SourceProcessFunc func(ctx *Context, filename string, src interface{}) ([]byte, error)

type TestProcessor ¶ added in v1.0.8

type TestProcessor interface {
	LoadMain(ctx *build.Context, bp *build.Package) ([]byte, error)
}

TestProcessor handles loading of test main data.

type Tuple ¶

type Tuple = tuple

type TypedConst ¶

type TypedConst struct {
	Typ   reflect.Type
	Value constant.Value
}

type TypesLoader ¶

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

func (*TypesLoader) GetPackage ¶

func (r *TypesLoader) GetPackage(pkg string) *types.Package

func (*TypesLoader) Import ¶

func (r *TypesLoader) Import(path string) (*types.Package, error)

func (*TypesLoader) Insert ¶

func (r *TypesLoader) Insert(v reflect.Value)

func (*TypesLoader) InsertAlias ¶

func (r *TypesLoader) InsertAlias(p *types.Package, name string, rt reflect.Type)

func (*TypesLoader) InsertConst ¶

func (r *TypesLoader) InsertConst(p *types.Package, name string, typ types.Type, c constant.Value)

func (*TypesLoader) InsertFunc ¶

func (r *TypesLoader) InsertFunc(p *types.Package, name string, v reflect.Value)

func (*TypesLoader) InsertInterface ¶

func (r *TypesLoader) InsertInterface(p *types.Package, name string, rt reflect.Type)

func (*TypesLoader) InsertNamedType ¶

func (r *TypesLoader) InsertNamedType(p *types.Package, name string, rt reflect.Type)

func (*TypesLoader) InsertTypedConst ¶

func (r *TypesLoader) InsertTypedConst(p *types.Package, name string, v TypedConst)

func (*TypesLoader) InsertUntypedConst ¶

func (r *TypesLoader) InsertUntypedConst(p *types.Package, name string, v UntypedConst)

func (*TypesLoader) InsertVar ¶

func (r *TypesLoader) InsertVar(p *types.Package, name string, v reflect.Value)

func (*TypesLoader) Installed ¶

func (r *TypesLoader) Installed(path string) (pkg *Package, ok bool)

func (*TypesLoader) Iterate ¶ added in v1.1.0

func (r *TypesLoader) Iterate(fn func(typ types.Type, value interface{}))

func (*TypesLoader) LookupPackage ¶

func (r *TypesLoader) LookupPackage(pkgpath string) (*types.Package, bool)

func (*TypesLoader) LookupReflect ¶

func (r *TypesLoader) LookupReflect(typ types.Type) (reflect.Type, bool)

func (*TypesLoader) LookupType ¶

func (r *TypesLoader) LookupType(typ string) types.Type

func (*TypesLoader) LookupTypes ¶

func (r *TypesLoader) LookupTypes(typ reflect.Type) (types.Type, bool)

func (*TypesLoader) Packages ¶

func (r *TypesLoader) Packages() (pkgs []*types.Package)

func (*TypesLoader) SetImport ¶

func (r *TypesLoader) SetImport(path string, pkg *types.Package, load func() error) error

func (*TypesLoader) ToType ¶

func (r *TypesLoader) ToType(rt reflect.Type) types.Type

type TypesRecord ¶

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

func NewTypesRecord ¶

func NewTypesRecord(ctx *Context, rctx *reflectx.Context, prog *ssa.Program, loader Loader, finder FindMethod, nested map[*types.Named]int) *TypesRecord

func (*TypesRecord) EnterInstance ¶

func (r *TypesRecord) EnterInstance(fn *ssa.Function)

func (*TypesRecord) LeaveInstance ¶

func (r *TypesRecord) LeaveInstance(fn *ssa.Function)

func (*TypesRecord) Load ¶

func (r *TypesRecord) Load(pkg *ssa.Package)

func (*TypesRecord) LookupLocalTypes ¶

func (r *TypesRecord) LookupLocalTypes(rt reflect.Type) (typ types.Type, ok bool)

func (*TypesRecord) LookupReflect ¶

func (r *TypesRecord) LookupReflect(typ types.Type) (rt reflect.Type, ok bool, nested bool)

func (*TypesRecord) LookupTypes ¶

func (r *TypesRecord) LookupTypes(rt reflect.Type) (typ types.Type, ok bool)

func (*TypesRecord) Release ¶

func (r *TypesRecord) Release()

func (*TypesRecord) ToType ¶

func (r *TypesRecord) ToType(typ types.Type) (reflect.Type, bool)

func (*TypesRecord) ToTypeList ¶

func (r *TypesRecord) ToTypeList(tuple *types.Tuple) ([]reflect.Type, bool)

type UntypedConst ¶

type UntypedConst struct {
	Typ   string
	Value constant.Value
}

type Value ¶

type Value = value

Directories ¶

Path Synopsis
cmd
internal/base
Package base defines shared xtype pieces of the gop command, in particular logging and the Command structure.
Package base defines shared xtype pieces of the gop command, in particular logging and the Command structure.
internal/build
Package build implements the “ixgo build” command.
Package build implements the “ixgo build” command.
internal/help
Package help implements the “ixgo help” command.
Package help implements the “ixgo help” command.
internal/run
Package run implements the “gop run” command.
Package run implements the “gop run” command.
internal/test
Package test implements the “ixgo test” command.
Package test implements the “ixgo test” command.
internal/version
Package build implements the “ixgo version” command.
Package build implements the “ixgo version” command.
ixgo command
ixgotest command
qexp command
fmt
io
net
os
Package directfunc registers DirectFunc wrappers for func() T with common result types.
Package directfunc registers DirectFunc wrappers for func() T with common result types.
internal
memo
Package memo contains shared runtime helpers for memoization.
Package memo contains shared runtime helpers for memoization.
ixgo module
mod
Package memo enables optional interpreter memoization.
Package memo enables optional interpreter memoization.
pkg
cmp
fmt
io
iter/_patch
Package iter provides basic definitions and operations related to iterators over sequences.
Package iter provides basic definitions and operations related to iterators over sequences.
log
net
os
test
patch/errors command
patch/iter command
patch/reflect command
patch/runtime command
patch/sync command
patch/unique command
patch/weak command
sccp
Package sccp implements sparse conditional constant propagation for golang.org/x/tools/go/ssa.
Package sccp implements sparse conditional constant propagation for golang.org/x/tools/go/ssa.
x
abi
race
Package race contains helper functions for manually instrumenting code for the race detector.
Package race contains helper functions for manually instrumenting code for the race detector.
testdeps
Package testdeps provides access to dependencies needed by test execution.
Package testdeps provides access to dependencies needed by test execution.
testlog
Package testlog provides a back-channel communication path between tests and package os, so that cmd/go can see which environment variables and files a test consults.
Package testlog provides a back-channel communication path between tests and package os, so that cmd/go can see which environment variables and files a test consults.
pkg

Jump to

Keyboard shortcuts

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