gox

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddActionsClientScriptDecl

func AddActionsClientScriptDecl(bundle *Bundle, actionsRuntimeURL string, extraImportMapEntries map[string]string)

func AddBundleConstructor

func AddBundleConstructor(bundle *Bundle)

func AddBundleExports

func AddBundleExports(bundle *Bundle) error

func AddClientMethods

func AddClientMethods(file *ast.File, moduleName string, clients []ClientDecl)

func AddModuleConstructor

func AddModuleConstructor(file *ast.File, moduleName string, fields []VarDecl) error

func AddModuleConstructorWithOrigins

func AddModuleConstructorWithOrigins(file *ast.File, moduleName string, fields []VarDecl, origins *OriginTable) error

func AddTemplateStaticDecls

func AddTemplateStaticDecls(file *ast.File, statics []TemplateStaticDecl)

func AddTemplateStaticDeclsWithOrigins

func AddTemplateStaticDeclsWithOrigins(file *ast.File, statics []TemplateStaticDecl, origins *OriginTable)

func AddUserStatementLineMarkers

func AddUserStatementLineMarkers(file *ast.File, fset *token.FileSet, sourceFile string)

func BindModuleFieldIdentifiers

func BindModuleFieldIdentifiers(file *ast.File, fields []VarDecl, receiverName string) error

func BindModuleFieldIdentifiersWithOrigins

func BindModuleFieldIdentifiersWithOrigins(file *ast.File, fields []VarDecl, receiverName string, origins *OriginTable) error

func BindModuleMethodCallsWithOrigins

func BindModuleMethodCallsWithOrigins(file *ast.File, receiverName string, origins *OriginTable) error

func BuildActionParamsDecls

func BuildActionParamsDecls(bundle *Bundle) []ast.Decl

func BuildRuntimeDecls

func BuildRuntimeDecls(used map[string]struct{}) ([]ast.Decl, error)

func BuildRuntimeDeclsFromFile

func BuildRuntimeDeclsFromFile(runtimePath string, used map[string]struct{}) ([]ast.Decl, error)

func BuildTemplateStaticDecls

func BuildTemplateStaticDecls(statics []TemplateStaticDecl) []ast.Decl

func BundleSourceMapPath

func BundleSourceMapPath(outPath string) string

func CleanupRedundantReturns

func CleanupRedundantReturns(file *ast.File)

func ClientAdaptValues

func ClientAdaptValues() []string

ClientAdaptValues is the exhaustive, case-sensitive vocabulary used by the compiler and editor. Return a fresh slice so callers cannot mutate the contract.

func ClientComponentKey

func ClientComponentKey(framework string, src string, dev bool) string

ClientComponentKey returns the source-level portion of a client identity. It remains available for compatibility with compile results produced before declaration identities included module paths and names.

func ClientDeclarationKey

func ClientDeclarationKey(modulePath string, name string, framework string, src string, dev bool) string

ClientDeclarationKey returns the stable identity of one client declaration. Build identity is tracked separately so multiple declarations may reuse one equivalent bundle without colliding at runtime.

func DetectGoxReturnName

func DetectGoxReturnName(fn *ast.FuncDecl) string

func DetectUsedRuntimeHelpers

func DetectUsedRuntimeHelpers(decls []ast.Decl) map[string]struct{}

func EnsureActionReturns

func EnsureActionReturns(file *ast.File, fset *token.FileSet, mod *Module) error

func FormatBundleMapped

func FormatBundleMapped(bundle *Bundle, generatedURI string) (string, *goxmap.Map, error)

FormatBundleMapped formats the bundle and builds a source map from the formatted Go bytes to the original GOX documents.

func FormatSource

func FormatSource(path, source string) (string, error)

FormatSource formats the Go portion and template values of a GOX document while preserving client declarations byte-for-byte.

func FormatTemplate

func FormatTemplate(source, baseIndent string) (string, error)

FormatTemplate formats one complete GOX template. baseIndent is already present before the first tag and is applied to every following line.

func GenerateTemplateStmts

func GenerateTemplateStmts(tpl *Template, ctx *TemplateGenContext) ([]ast.Stmt, error)

func GoxActionName

func GoxActionName(module string, name string) string

func GoxActionParamsName

func GoxActionParamsName(module string, action string) string

func GoxConstName

func GoxConstName(module, name string) string

func GoxModuleConstructorName

func GoxModuleConstructorName(name string) string

func GoxModuleName

func GoxModuleName(name string) string

func GoxTemplateStaticName

func GoxTemplateStaticName(moduleName string, funcName string) string

func GoxTypeName

func GoxTypeName(module, name string) string

func InvalidateProjectGoGoroutineSafety

func InvalidateProjectGoGoroutineSafety(root, changedPath string)

InvalidateProjectGoGoroutineSafety evicts cached safety analysis for the directory containing changedPath. Passing an empty path evicts the whole project root. Compile and Analyze also verify filesystem metadata, so this invalidation is an eager hot-reload optimization rather than a correctness requirement for callers outside the server runtime.

func PruneActionTypesSources

func PruneActionTypesSources(root string, sourcePaths []string) error

PruneActionTypesSources removes cached Action sources that are not part of the supplied project index.

func PruneWebSocketEventTypesSources

func PruneWebSocketEventTypesSources(root string, sourcePaths []string) error

PruneWebSocketEventTypesSources removes cached sources that are not part of the current project index. This makes a fresh LSP workspace index authoritative even when .build/cache was produced by an earlier editor session.

func ReconcileModuleReferences

func ReconcileModuleReferences(graph *ModuleGraph) error

func RemoveActionTypesForSource

func RemoveActionTypesForSource(root, sourcePath string) error

RemoveActionTypesForSource removes one GOX source from the generated Action typings after that source is deleted or renamed.

func RemoveWebSocketEventTypesForSource

func RemoveWebSocketEventTypesForSource(root, sourcePath string) error

RemoveWebSocketEventTypesForSource removes a GOX source from the generated WebSocket event typings after the source is deleted or renamed.

func RenameActionFunctions

func RenameActionFunctions(file *ast.File, mod *Module)

func RenderBundleMapped

func RenderBundleMapped(bundle *Bundle, outPath string) (string, *goxmap.Map, error)

func ResolveGoxImport

func ResolveGoxImport(rootDir, importerPath, importPath string) (string, error)

ResolveGoxImport resolves one .gox import using the same project and alias rules as graph compilation. Editor features use it instead of duplicating module resolution.

func RewriteBundleSourceMapGeneratedURI

func RewriteBundleSourceMapGeneratedURI(sourceMapPath, generatedURI string) error

RewriteBundleSourceMapGeneratedURI keeps a persisted source map aligned when the generated Go artifact is moved to its final build-version path.

func RewriteWebSocketEmitAwait

func RewriteWebSocketEmitAwait(mod *Module)

RewriteWebSocketEmitAwait preserves the public Emit(...).Await(&out) syntax while compiling it into one atomic request operation.

func RewriteWebSocketEmitAwaitWithOrigins

func RewriteWebSocketEmitAwaitWithOrigins(mod *Module, origins *OriginTable)

func RewriteWebSocketOnSignatures

func RewriteWebSocketOnSignatures(mod *Module, fset *token.FileSet) error

RewriteWebSocketOnSignatures preserves callback parameter names that Go reflection discards. It changes On calls backed by a function literal or a named module function inside a module with a WebSocket or Channel entrypoint.

func RewriteWebSocketOnSignaturesWithOrigins

func RewriteWebSocketOnSignaturesWithOrigins(mod *Module, fset *token.FileSet, origins *OriginTable) error

func SemanticGoxPackageSource

func SemanticGoxPackageSource(packagePath string) (string, bool)

SemanticGoxPackageSource maps a synthetic go/types package path created for an imported .gox module back to its source file. Later navigation phases can use this without teaching go/types about runtime bundle rewrites.

func SpecializeRuntimeAnyCalls

func SpecializeRuntimeAnyCalls(decls []ast.Decl)

func TransformFunctionsToMethods

func TransformFunctionsToMethods(file *ast.File, moduleName string) error

func TransformFunctionsToMethodsWithOrigins

func TransformFunctionsToMethodsWithOrigins(file *ast.File, moduleName string, origins *OriginTable) error

func TransformGoxFunctionsWithOrigins

func TransformGoxFunctionsWithOrigins(file *ast.File, origins *OriginTable) error

func TransformTemplateExpressions

func TransformTemplateExpressions(path string, src string) (string, error)

func UpdateActionTypesForModule

func UpdateActionTypesForModule(root string, mod *Module) error

UpdateActionTypesForModule updates the generated Action typings for one GOX source. Development tooling can pass a Module parsed from unsaved editor text, making that in-memory document the source of truth for the source entry.

func UpdateWebSocketEventTypesForModule

func UpdateWebSocketEventTypesForModule(root string, mod *Module) error

UpdateWebSocketEventTypesForModule updates the generated WebSocket event typings for one GOX source. It is used by development tooling such as the LSP so an unsaved in-memory document can remain the source of truth.

func ValidateActions

func ValidateActions(mod *Module) error

func ValidateChannelEntrypoints

func ValidateChannelEntrypoints(mod *Module) error

ValidateChannelEntrypoints binds Channel declarations to the filesystem identity established by goxsource. A public Channel file owns exactly one factory; no other GOX module kind may declare a gox.Channel entrypoint.

func ValidateLocalComponentSemantics

func ValidateLocalComponentSemantics(mod *Module, templates []TemplateReturn) error

ValidateLocalComponentSemantics validates the named prop contract of local GOX components. It deliberately does not lower/reorder arguments (phase 6), generate children callbacks (phase 7), or resolve imported components (phase 8).

func ValidateModuleStructure

func ValidateModuleStructure(mod *Module) error

ValidateModuleStructure enforces the declaration boundary between the HTTP pages tree and the websocket tree. It restricts GOX entrypoint declarations; ordinary use of websocket APIs from Pages remains valid.

func ValidatePageEntrypoints

func ValidatePageEntrypoints(mod *Module) error

func ValidateTemplateComponentReferences

func ValidateTemplateComponentReferences(mod *Module, templates []TemplateReturn) error

func ValidateWebSocketEntrypoints

func ValidateWebSocketEntrypoints(mod *Module) error

func WriteBundle

func WriteBundle(bundle *Bundle, outPath string) error

Types

type AssetImport

type AssetImport struct {
	Path  string
	Alias string
	Kind  AssetKind

	Spec *ast.ImportSpec
}

type AssetKind

type AssetKind string
const (
	AssetCSS AssetKind = "css"
	AssetTS  AssetKind = "ts"
	AssetMTS AssetKind = "mts"
	AssetSVG AssetKind = "svg"
)

type Bundle

type Bundle struct {
	Entry   *Module
	Modules []*Module

	GoPackage string
	GoImports []ImportDecl
	Decls     []ast.Decl
	Origins   *OriginTable
	Sources   map[string]string
}

func BundleModules

func BundleModules(graph *ModuleGraph) (*Bundle, error)

type ClientDecl

type ClientDecl struct {
	Name         string
	Key          string
	Framework    ClientFramework
	Entry        string
	EntryPath    string
	EntryAbsPath string
	Dev          bool

	Pos         token.Pos
	NamePos     token.Pos
	EntryPos    token.Pos
	EntryOffset int

	SourceOffset    int
	NameOffset      int
	FrameworkOffset int
	SrcKeyOffset    int
	DevKeyOffset    int
	DevValueOffset  int
	DevDeclared     bool
}

type ClientFramework

type ClientFramework string
const (
	ClientGox    ClientFramework = "Gox"
	ClientReact  ClientFramework = "React"
	ClientPreact ClientFramework = "Preact"
	ClientSolid  ClientFramework = "Solid"
	ClientVue    ClientFramework = "Vue"
	ClientSvelte ClientFramework = "Svelte"
)

type ClientNode

type ClientNode struct {
	Pos        TemplatePosition
	Name       string
	Attrs      []TemplateAttr
	Children   []TemplateNode
	SelfClosed bool
}

type ClientSemantic

type ClientSemantic struct {
	Source goxmap.SourceRange
	Detail string
}

type CommentNode

type CommentNode struct {
	Pos   TemplatePosition
	Value string
}

type CompileClientAsset

type CompileClientAsset struct {
	Kind string
	URL  string
	File string
}

type CompileClientBundle

type CompileClientBundle struct {
	Name      string
	Framework string
	Entry     string
	Path      string
	Mode      string

	EntryURL  string
	EntryFile string

	Assets []CompileClientAsset
	Graph  CompileClientDependencyGraph
}

type CompileClientComponent

type CompileClientComponent struct {
	Name          string `json:"name"`
	Key           string `json:"key"`
	Framework     string `json:"framework"`
	Entry         string `json:"entry"`
	Path          string `json:"path"`
	AbsPath       string `json:"-"`
	ModulePath    string `json:"module"`
	ModuleAbsPath string `json:"-"`
	Dev           bool
	Mode          string
	OutputDir     string
}

type CompileClientDependencyGraph

type CompileClientDependencyGraph struct {
	Entry          string
	EntryFile      string
	Framework      string
	Component      string
	OutputFiles    []string
	ModuleFiles    []string
	Imports        []string
	DynamicImports []string
	Nodes          []CompileClientDependencyGraphNode
}

type CompileClientDependencyGraphNode

type CompileClientDependencyGraphNode struct {
	File           string
	Imports        []string
	DynamicImports []string
}

type CompileDependency

type CompileDependency struct {
	Path               string
	AbsPath            string
	ModuleName         string
	DeclaredModuleName string
	IsEntry            bool

	Imports    []string
	GoImports  []string
	ImportedBy []string

	Size         int64
	ModTime      time.Time
	LoadDuration time.Duration
}

type CompileGoPackage

type CompileGoPackage struct {
	ImportPath string
	Dir        string
	Files      []string
	Imports    []string
	ImportedBy []string
	Direct     bool
}

CompileGoPackage describes a local Go package participating in a compile. ImportPath identifies the package as Go code imports it, while Dir and Files identify its physical sources in the project.

type CompileModule

type CompileModule struct {
	Path               string
	AbsPath            string
	ModuleName         string
	DeclaredModuleName string
	IsEntry            bool

	Imports      []string
	GoImports    []string
	Clients      []CompileClientComponent
	ImportedBy   []string
	LoadDuration time.Duration
}

type CompileResult

type CompileResult struct {
	EntryPath     string
	EntryAbsPath  string
	OutPath       string
	OutAbsPath    string
	SourceMapPath string

	StartedAt  time.Time
	FinishedAt time.Time
	Duration   time.Duration

	LoadGraphDuration time.Duration
	BundleDuration    time.Duration
	WriteDuration     time.Duration

	GoPackage       string
	ModuleCount     int
	DependencyCount int
	OutputBytes     int64
	Written         bool

	Dependencies           []CompileDependency
	GoPackages             []CompileGoPackage
	ResolutionDependencies []string
	Modules                []CompileModule
	ClientComponents       []CompileClientComponent
	ClientBundles          []CompileClientBundle
	ClientAssetMap         map[string]string
	ClientRuntimeURL       string
	ClientBaseStyleURL     string
	ActionsRuntimeURL      string
}

func Analyze

func Analyze(entryPath string) (*CompileResult, error)

Analyze loads and resolves a .gox module graph without generating Go output.

func Compile

func Compile(entryPath string, outPath string) (*CompileResult, error)

type ComponentContract

type ComponentContract struct {
	Name         string
	Props        []ComponentPropContract
	Children     *ComponentPropContract
	ChildrenLast bool
}

ComponentContract is the source-level semantic contract of one local GOX component. Props preserve declaration order so later lowering phases can bind named template attributes to Go call arguments without re-deriving the function signature.

type ComponentNode

type ComponentNode struct {
	Pos        TemplatePosition
	Name       string
	Attrs      []TemplateAttr
	Children   []TemplateNode
	SelfClosed bool
}

type ComponentPropContract

type ComponentPropContract struct {
	Name string
	Type ast.Expr
}

ComponentPropContract describes one named component parameter.

type ConstDecl

type ConstDecl struct {
	Name string

	Type  ast.Expr
	Value ast.Expr

	Spec *ast.ValueSpec
}

func TransformModuleConstsWithOrigins

func TransformModuleConstsWithOrigins(file *ast.File, moduleName string, origins *OriginTable) ([]ConstDecl, error)

type DirectiveNode

type DirectiveNode struct {
	Pos        TemplatePosition
	Name       string
	Attrs      []TemplateAttr
	Children   []TemplateNode
	SelfClosed bool
}

type ElementNode

type ElementNode struct {
	Pos        TemplatePosition
	Tag        string
	Attrs      []TemplateAttr
	Children   []TemplateNode
	SelfClosed bool
}

type ExprNode

type ExprNode struct {
	Pos        TemplatePosition
	Source     goxmap.SourceRange
	ExprSource goxmap.SourceRange
	Expr       ast.Expr
	Raw        string
	Mode       TemplateExprMode
}

type FragmentNode

type FragmentNode struct {
	Pos      TemplatePosition
	Children []TemplateNode
}

type FuncDecl

type FuncDecl struct {
	Name string
	Kind FuncKind

	Node *ast.FuncDecl

	Params            []flatParam
	ActionReturnTypes []string
}

type FuncKind

type FuncKind string
const (
	FuncNormal    FuncKind = "normal"
	FuncPage      FuncKind = "page"
	FuncHandler   FuncKind = "handler"
	FuncComponent FuncKind = "component"
	FuncAPI       FuncKind = "api"
	FuncJSON      FuncKind = "json"
	FuncFile      FuncKind = "file"
	FuncText      FuncKind = "text"
	FuncAction    FuncKind = "action"
	FuncConfig    FuncKind = "config"
	FuncWebSocket FuncKind = "websocket"
	FuncChannel   FuncKind = "channel"
)

type GoxImport

type GoxImport struct {
	Path   string // "./buttons.gox"
	Name   string // Button, Ux, Layout, etc.
	Source goxmap.SourceRange

	ResolvedPath         string
	ResolutionCandidates []string
}

func TransformModuleImports

func TransformModuleImports(
	file *ast.File,
	origins *OriginTable,
) ([]GoxImport, error)

type GoxReturnKind

type GoxReturnKind string
const (
	GoxReturnNone       GoxReturnKind = ""
	GoxReturnHTML       GoxReturnKind = "html"
	GoxReturnText       GoxReturnKind = "text"
	GoxReturnJSON       GoxReturnKind = "json"
	GoxReturnBinary     GoxReturnKind = "binary"
	GoxReturnAction     GoxReturnKind = "action"
	GoxReturnWebSocket  GoxReturnKind = "websocket"
	GoxReturnChannel    GoxReturnKind = "channel"
	GoxReturnEventReply GoxReturnKind = "event-reply"
)

func DetectGoxReturnKind

func DetectGoxReturnKind(fn *ast.FuncDecl) GoxReturnKind

DetectGoxReturnKind and DetectGoxReturnName are retained for focused callers that only have a declaration node. Runtime/compiler production paths use the file-aware helpers above so semantic identity cannot be inferred from a bare type name.

type ImportDecl

type ImportDecl struct {
	Path  string // "fmt", "net/http"
	Alias string // "", ".", "_", "json"

	Spec *ast.ImportSpec

	SourceFile string
	SourceLine int
	Source     goxmap.SourceRange
}

func RuntimeImportsForUsedHelpers

func RuntimeImportsForUsedHelpers(used map[string]struct{}) []ImportDecl

type LocalSymbol

type LocalSymbol struct {
	Name              string
	Kind              SourceSymbolKind
	Source            goxmap.SourceRange
	Scope             goxmap.SourceRange
	Type              string
	Initializer       string
	InitializerResult int
	Detail            string
	Signature         bool
}

LocalSymbol describes a declaration whose identity depends on lexical scope. Source and Scope always use offsets in the original .gox document.

type Module

type Module struct {
	Path         string
	Name         string
	DeclaredName string
	GoPackage    string
	Structure    goxsource.ModuleContext

	// File/Origins are the runtime/compiler representation and may be mutated
	// by GOX lowering after parsing. Editor type semantics live in Semantic.
	File   *ast.File
	Source string

	ParseSource           string
	ParseSourceMap        *goxmap.Map
	Origins               *OriginTable
	Semantic              *SemanticModel
	GoSemanticTokens      []SemanticToken
	Symbols               []SourceSymbol
	LocalSymbols          []LocalSymbol
	SelectorReferences    []SelectorReference
	UnresolvedIdentifiers []UnresolvedIdentifier
	References            []SourceReference

	GoImports  []ImportDecl
	GoxImports []GoxImport
	Assets     []AssetImport

	Vars   []VarDecl
	Consts []ConstDecl
	Types  []TypeDecl
	Funcs  []FuncDecl

	Clients             []ClientDecl
	ClientSemantics     []ClientSemantic
	Templates           []TemplateReturn
	TemplateOccurrences []TemplateOccurrence
	ComponentCalls      []pendingComponentCall
	WebSocketContracts  []WebSocketContract

	LoadDuration time.Duration
}

func ParseModule

func ParseModule(path string, src string) (*Module, error)

func ParseModuleForTooling

func ParseModuleForTooling(path string, src string) (*Module, error)

ParseModuleForTooling parses a GOX source for editor intelligence. It keeps structural and declaration semantics, but tolerates incomplete component invocations so completion can operate while required props are still being typed. Compiler entry points must continue using ParseModule.

func ParseProjectModule

func ParseProjectModule(root, path, src string) (*Module, error)

ParseProjectModule parses a GOX source using its path relative to the project root as the structural authority. Development tooling should prefer this when the project root is known so absolute directory names cannot affect the pages/websocket classification.

func ParseProjectModuleCached

func ParseProjectModuleCached(root, path, src string, cache *SemanticWorkspaceCache) (*Module, error)

ParseProjectModuleCached is the incremental-tooling variant of ParseProjectModule. The optional cache reuses immutable Go package type identities across document versions while every GOX source projection is still rebuilt from its current source.

func ParseProjectModuleCachedForTooling

func ParseProjectModuleCachedForTooling(root, path, src string, cache *SemanticWorkspaceCache) (*Module, error)

ParseProjectModuleCachedForTooling is the incremental editor variant of ParseProjectModuleCached. Component invocation completeness is intentionally not a parse blocker; the strict compiler path still validates it.

func ParseProjectModuleForTooling

func ParseProjectModuleForTooling(root, path, src string) (*Module, error)

ParseProjectModuleForTooling is the project-aware tooling variant of ParseModuleForTooling.

func (*Module) SemanticAtOffset

func (m *Module) SemanticAtOffset(offset int) (SemanticNode, bool)

SemanticAtOffset returns the most specific exact semantic AST node that contains the byte offset in the original .gox source. Runtime/compiler nodes are deliberately ignored: editor semantics come exclusively from Module.Semantic.File and its own Origins table.

type ModuleGraph

type ModuleGraph struct {
	Entry                  *Module
	Modules                []*Module
	ByPath                 map[string]*Module
	RootDir                string
	ResolutionDependencies []string
}

func LoadGraph

func LoadGraph(entryPath string) (*ModuleGraph, error)

type NodeOrigin

type NodeOrigin struct {
	Source goxmap.SourceRange
	Kind   goxmap.MappingKind
}

NodeOrigin records the GOX source range represented by one Go AST node. Exact nodes came from preserved source bytes; Anchor nodes were parsed from compiler-generated Go associated with a GOX construct.

func (NodeOrigin) Exact

func (o NodeOrigin) Exact() bool

Exact reports whether the node preserves its source bytes exactly.

type OriginTable

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

OriginTable stores source provenance by AST node identity. Nodes are pointer values in Go's AST, so their entries survive in-place tree mutations.

func NewOriginTable

func NewOriginTable() *OriginTable

NewOriginTable creates an empty origin table.

func SeedOriginTable

func SeedOriginTable(file *ast.File, fset *token.FileSet, sourceMap *goxmap.Map) *OriginTable

SeedOriginTable records every parsed node fully contained in one source-map segment. Larger nodes crossing mapping boundaries are omitted deliberately.

func (*OriginTable) AnchorGeneratedSelectors

func (t *OriginTable) AnchorGeneratedSelectors(file *ast.File, receiverName string)

AnchorGeneratedSelectors records receiver-qualified selectors introduced by a binding pass. The original identifier is reused as Sel and remains exact.

func (*OriginTable) Get

func (t *OriginTable) Get(node ast.Node) (NodeOrigin, bool)

Get returns the origin associated with node.

func (*OriginTable) Inherit

func (t *OriginTable) Inherit(generated ast.Node, source ast.Node) bool

Inherit associates a generated node with the source range of another node. The inherited origin is always an anchor because the generated node does not preserve the source node's bytes.

func (*OriginTable) InheritTree

func (t *OriginTable) InheritTree(generated ast.Node, source ast.Node) bool

InheritTree anchors every node in a generated subtree to source. Existing entries are preserved so reused parsed expressions retain exact provenance.

func (*OriginTable) Len

func (t *OriginTable) Len() int

Len returns the number of nodes with known provenance.

func (*OriginTable) Merge

func (t *OriginTable) Merge(other *OriginTable)

Merge adds origins from another table. Existing entries are replaced only when the incoming table contains the same AST node identity.

func (*OriginTable) Set

func (t *OriginTable) Set(node ast.Node, origin NodeOrigin)

Set associates a node with an explicit origin.

type SelectorReference

type SelectorReference struct {
	Name      string
	Kind      SourceSymbolKind
	Source    goxmap.SourceRange
	Target    goxmap.SourceRange
	Container string
}

type SemanticDependency

type SemanticDependency struct {
	// SourcePath is the .gox module that owns this import edge. Keeping the
	// importer on every edge lets the next phase build a reverse dependency
	// graph without rediscovering imports or flattening GOX module chains.
	SourcePath           string
	Kind                 SemanticDependencyKind
	ImportPath           string
	PackagePath          string
	ResolvedPath         string
	ResolutionCandidates []string
}

type SemanticDependencyKind

type SemanticDependencyKind string

SemanticDependencyKind identifies the workspace namespace resolved by one source import during semantic analysis.

const (
	SemanticDependencyGoPackage SemanticDependencyKind = "go-package"
	SemanticDependencyGoxModule SemanticDependencyKind = "gox-module"
)

type SemanticGoxReturn

type SemanticGoxReturn struct {
	Function   ast.Node
	ReturnName string
	Kind       GoxReturnKind
	Mode       SemanticGoxReturnMode
}

SemanticGoxReturn records one GOX marker function lowered for semantic tooling. Function is either *ast.FuncDecl or *ast.FuncLit and remains the node used by the semantic projection after lowering.

type SemanticGoxReturnMode

type SemanticGoxReturnMode string

SemanticGoxReturnMode describes how a GOX marker return is represented in the source-level semantic projection. The runtime/compiler transforms remain authoritative for execution; this lowering exists only so go/types can analyze the Go expressions written by the user without treating GOX marker types as ordinary Go return types.

const (
	// SemanticGoxReturnFlexibleRequired keeps one semantic result. Any single Go
	// value is accepted, but normal Go control-flow still requires a return.
	SemanticGoxReturnFlexibleRequired SemanticGoxReturnMode = "flexible-required"

	// SemanticGoxReturnFlexibleOptional keeps one semantic result while allowing
	// both bare returns and control flow to reach the closing brace.
	SemanticGoxReturnFlexibleOptional SemanticGoxReturnMode = "flexible-optional"

	// SemanticGoxReturnVoid removes the marker result completely. Return values
	// therefore remain ordinary Go errors, while a body with no return is valid.
	SemanticGoxReturnVoid SemanticGoxReturnMode = "void"
)

type SemanticModel

type SemanticModel struct {
	File      *ast.File
	FileSet   *token.FileSet
	Origins   *OriginTable
	SourceMap *goxmap.Map

	Package      *types.Package
	Info         *types.Info
	Errors       []error
	Dependencies []SemanticDependency
}

SemanticModel is the source-level Go semantic representation of a .gox module. It owns an AST that is intentionally independent from Module.File: Module.File is free to undergo runtime/compiler rewrites while File remains the stable tree used as keys in Info. Positions belong to FileSet and source provenance belongs to Origins/SourceMap from the semantic projection.

type SemanticNode

type SemanticNode struct {
	Node      ast.Node
	Expr      ast.Expr
	Ident     *ast.Ident
	Selector  *ast.SelectorExpr
	TypeValue types.TypeAndValue
	Object    types.Object
	Selection *types.Selection
}

SemanticNode is the typed Go AST node that represents a position in the original .gox source. Node identity is preserved, so Info can be queried directly with Expr, Ident, or Selector.

type SemanticProjection

type SemanticProjection struct {
	Source     string
	SourceMap  *goxmap.Map
	FileSet    *token.FileSet
	File       *ast.File
	Origins    *OriginTable
	GoxReturns []SemanticGoxReturn
}

SemanticProjection is a Go-only representation of GOX source intended for tooling. It deliberately stays separate from the runtime/compiler AST: GOX constructs are lowered to generated Go scaffolding while user-authored Go expressions remain exact source bytes with exact origins. Source is the mapped Go text parsed into File; marker-return lowering is intentionally an AST-only semantic step so exact user positions never move after parsing.

func BuildSemanticProjection

func BuildSemanticProjection(path, source string) (*SemanticProjection, error)

BuildSemanticProjection builds the source-level Go projection used by semantic tooling. Template discovery is intentionally delegated to the same extraction/transformation pipeline used by ParseModule; the projection consumes the resulting TemplateOccurrences instead of defining a second set of rules for where templates may appear. ParseModule uses the lower-level buildSemanticProjectionFromOccurrences helper so it can reuse occurrences already discovered by its normal pipeline without repeating that work.

type SemanticToken

type SemanticToken struct {
	Line   int
	Column int
	Length int
	Kind   SemanticTokenKind
}

func CollectSemanticTokens

func CollectSemanticTokens(path, source string) ([]SemanticToken, error)

type SemanticTokenKind

type SemanticTokenKind string
const (
	SemanticNamespace          SemanticTokenKind = "namespace"
	SemanticType               SemanticTokenKind = "type"
	SemanticStruct             SemanticTokenKind = "struct"
	SemanticInterface          SemanticTokenKind = "interface"
	SemanticParameter          SemanticTokenKind = "parameter"
	SemanticVariable           SemanticTokenKind = "variable"
	SemanticProperty           SemanticTokenKind = "property"
	SemanticEnumMember         SemanticTokenKind = "enumMember"
	SemanticFunction           SemanticTokenKind = "function"
	SemanticMethod             SemanticTokenKind = "method"
	SemanticLabel              SemanticTokenKind = "label"
	SemanticComment            SemanticTokenKind = "comment"
	SemanticString             SemanticTokenKind = "string"
	SemanticNumber             SemanticTokenKind = "number"
	SemanticKeyword            SemanticTokenKind = "keyword"
	SemanticGoxModuleKeyword   SemanticTokenKind = "goxModuleKeyword"
	SemanticGoxClientKeyword   SemanticTokenKind = "goxClientKeyword"
	SemanticGoxClientFramework SemanticTokenKind = "goxClientFramework"
	SemanticGoxTag             SemanticTokenKind = "goxTag"
	SemanticGoxAttribute       SemanticTokenKind = "goxAttribute"
	SemanticGoxAttributeValue  SemanticTokenKind = "goxAttributeValue"
	SemanticGoxDirective       SemanticTokenKind = "goxDirective"
	SemanticGoxComponent       SemanticTokenKind = "goxComponent"
	SemanticGoxClient          SemanticTokenKind = "goxClient"
)

type SemanticWorkspaceCache

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

SemanticWorkspaceCache owns immutable Go package identities that are safe to reuse across semantic analyses of different GOX document versions. GOX modules themselves are intentionally not cached here: their source may be edited independently and is tracked by the LSP dependency graph.

Each semantic workspace also receives a generation token for its root. Root invalidation advances that generation by replacing the active lease. Analyses that were already in flight may finish against their old importer universe, but generation-aware cache reads/stores prevent them from mixing old *types.Package identities into the new universe.

func NewSemanticWorkspaceCache

func NewSemanticWorkspaceCache() *SemanticWorkspaceCache

func (*SemanticWorkspaceCache) GoPackage

func (c *SemanticWorkspaceCache) GoPackage(root, importPath string) (*types.Package, bool)

func (*SemanticWorkspaceCache) InvalidateAll

func (c *SemanticWorkspaceCache) InvalidateAll()

func (*SemanticWorkspaceCache) InvalidateRoot

func (c *SemanticWorkspaceCache) InvalidateRoot(root string)

func (*SemanticWorkspaceCache) StoreGoPackage

func (c *SemanticWorkspaceCache) StoreGoPackage(root, importPath string, pkg *types.Package)

type SourceParameter

type SourceParameter struct {
	Name string
	Type string
}

type SourceReference

type SourceReference struct {
	Name      string
	Qualifier string
	Kind      SourceReferenceKind
	Source    goxmap.SourceRange
	Container string
}

SourceReference records a GOX-specific symbol use in original source.

type SourceReferenceKind

type SourceReferenceKind string
const (
	ReferenceComponent SourceReferenceKind = "component"
	ReferenceClient    SourceReferenceKind = "client"
)

type SourceSymbol

type SourceSymbol struct {
	Name       string
	Kind       SourceSymbolKind
	Source     goxmap.SourceRange
	Container  string
	Exported   bool
	Type       string
	Underlying string
	Alias      bool
	Value      string
	Results    []string
	Parameters []SourceParameter
	Detail     string
}

SourceSymbol is a user-authored declaration that editor features may reference. Its range always points into the original .gox source.

func CollectSourceSymbols

func CollectSourceSymbols(path, source string) ([]SourceSymbol, error)

CollectSourceSymbols exposes the compiler's declaration model without duplicating GOX parsing rules in the language server.

type SourceSymbolKind

type SourceSymbolKind string
const (
	SymbolModule    SourceSymbolKind = "module"
	SymbolClient    SourceSymbolKind = "client"
	SymbolFunction  SourceSymbolKind = "function"
	SymbolMethod    SourceSymbolKind = "method"
	SymbolType      SourceSymbolKind = "type"
	SymbolStruct    SourceSymbolKind = "struct"
	SymbolInterface SourceSymbolKind = "interface"
	SymbolVariable  SourceSymbolKind = "variable"
	SymbolConstant  SourceSymbolKind = "constant"
	SymbolField     SourceSymbolKind = "field"
)

type Template

type Template struct {
	Root   TemplateNode
	Source goxmap.SourceRange
}

func ParseTemplate

func ParseTemplate(src string) (*Template, error)

func ParseTemplateAt

func ParseTemplateAt(src string, file string, line int, column int) (*Template, error)

func ParseTemplateAtOffset

func ParseTemplateAtOffset(src string, file string, line int, column int, sourceOffset int) (*Template, error)

type TemplateAttr

type TemplateAttr struct {
	Pos        TemplatePosition
	Source     goxmap.SourceRange
	NameSource goxmap.SourceRange
	Name       string
	Kind       TemplateAttrKind

	Value       string
	ValueSource goxmap.SourceRange

	Expr       ast.Expr
	ExprSource goxmap.SourceRange
	Raw        string
	Mode       TemplateExprMode
}

type TemplateAttrKind

type TemplateAttrKind string
const (
	AttrStatic  TemplateAttrKind = "static"
	AttrExpr    TemplateAttrKind = "expr"
	AttrBoolean TemplateAttrKind = "boolean"
	AttrSpecial TemplateAttrKind = "special"
)

type TemplateExprMode

type TemplateExprMode string
const (
	ExprEscaped TemplateExprMode = "escaped"
	ExprRaw     TemplateExprMode = "raw"
)

type TemplateExpressionTransformation

type TemplateExpressionTransformation struct {
	Source      string
	SourceMap   *goxmap.Map
	Statics     []TemplateStaticDecl
	Occurrences []TemplateOccurrence
}

TemplateExpressionTransformation contains one transformed source document and the map from that document back to its original GOX input.

func TransformTemplateExpressionsMapped

func TransformTemplateExpressionsMapped(moduleName string, path string, src string, upstream *goxmap.Map) (*TemplateExpressionTransformation, error)

TransformTemplateExpressionsMapped rewrites template expressions and emits their source map. When upstream is provided, the stage map is composed with it so the result resolves directly to the original GOX source.

type TemplateGenContext

type TemplateGenContext struct {
	WriterName string
	LoopDepth  int

	StaticVarName  string
	StaticLiterals *[]string

	TypeEnv *TemplateTypeEnv

	Clients map[string]ClientDecl

	InjectActionsClient bool
	InjectClientRuntime bool
	ModulePath          string
}

type TemplateLexer

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

func NewTemplateLexer

func NewTemplateLexer(src string) *TemplateLexer

func NewTemplateLexerAt

func NewTemplateLexerAt(src string, file string, line int, col int) *TemplateLexer

func NewTemplateLexerAtOffset

func NewTemplateLexerAtOffset(src string, file string, line int, col int, sourceOffset int) *TemplateLexer

func (*TemplateLexer) LexAll

func (l *TemplateLexer) LexAll() ([]TemplateToken, error)

func (*TemplateLexer) NextToken

func (l *TemplateLexer) NextToken() (TemplateToken, error)

type TemplateNode

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

type TemplateOccurrence

type TemplateOccurrence struct {
	Kind       TemplateOccurrenceKind
	ModuleName string
	FuncName   string
	Source     goxmap.SourceRange
	Content    goxmap.SourceRange
	Raw        string
	Template   *Template
	StaticName string
}

TemplateOccurrence describes one template embedded in GOX source. Source covers the complete user-facing template syntax. Content covers the exact bytes parsed by Template; fragments therefore exclude their <> and </> delimiters from Content while retaining them in Source.

type TemplateOccurrenceKind

type TemplateOccurrenceKind string
const (
	TemplateOccurrenceReturn TemplateOccurrenceKind = "return"
	TemplateOccurrenceValue  TemplateOccurrenceKind = "value"
)

type TemplateParser

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

func (*TemplateParser) Parse

func (p *TemplateParser) Parse() (*Template, error)

func (*TemplateParser) ParseRootOnly

func (p *TemplateParser) ParseRootOnly() (TemplateNode, error)

type TemplatePosition

type TemplatePosition struct {
	File   string
	Line   int
	Column int
}

TemplatePosition points back to the user-facing .gox source.

func (TemplatePosition) IsValid

func (p TemplatePosition) IsValid() bool

type TemplateReturn

type TemplateReturn struct {
	ID         string
	ModuleName string
	FuncName   string
	Start      int
	End        int
	Source     goxmap.SourceRange
	Content    goxmap.SourceRange

	Raw      string
	Template *Template
}

func (TemplateReturn) Occurrence

func (t TemplateReturn) Occurrence() TemplateOccurrence

type TemplateReturnExtraction

type TemplateReturnExtraction struct {
	Source    string
	SourceMap *goxmap.Map
	Templates []TemplateReturn
}

func ExtractTemplateReturns

func ExtractTemplateReturns(moduleName string, path string, src string) (*TemplateReturnExtraction, error)

func ExtractTemplateReturnsMapped

func ExtractTemplateReturnsMapped(moduleName string, path string, src string, upstream *goxmap.Map) (*TemplateReturnExtraction, error)

type TemplateStaticDecl

type TemplateStaticDecl struct {
	Name     string
	Literals []string
}

func RewriteTemplateReturnsWithOrigins

func RewriteTemplateReturnsWithOrigins(file *ast.File, templates []TemplateReturn, clients []ClientDecl, origins *OriginTable, environments ...*TemplateTypeEnv) ([]TemplateStaticDecl, error)

func TransformTemplateExpressionsWithStatics

func TransformTemplateExpressionsWithStatics(moduleName string, path string, src string) (string, []TemplateStaticDecl, error)

type TemplateToken

type TemplateToken struct {
	Kind TemplateTokenKind
	Lit  string

	ExprMode TemplateExprMode
	Source   goxmap.SourceRange
	GoSource goxmap.SourceRange

	Line int
	Col  int
}

type TemplateTokenKind

type TemplateTokenKind string
const (
	TokenEOF TemplateTokenKind = "EOF"

	TokenText    TemplateTokenKind = "TEXT"
	TokenComment TemplateTokenKind = "COMMENT"

	TokenOpenTagStart      TemplateTokenKind = "OPEN_TAG_START"      // <
	TokenCloseTagStart     TemplateTokenKind = "CLOSE_TAG_START"     // </
	TokenDirectiveTagStart TemplateTokenKind = "DIRECTIVE_TAG_START" // <:
	TokenComponentTagStart TemplateTokenKind = "COMPONENT_TAG_START" // <&
	TokenClientTagStart    TemplateTokenKind = "CLIENT_TAG_START"    // <@

	TokenTagEnd       TemplateTokenKind = "TAG_END"        // >
	TokenSelfCloseEnd TemplateTokenKind = "SELF_CLOSE_END" // />

	TokenIdent TemplateTokenKind = "IDENT"
	TokenEqual TemplateTokenKind = "EQUAL"

	TokenString TemplateTokenKind = "STRING"
	TokenExpr   TemplateTokenKind = "EXPR" // { ... }
)

type TemplateTypeEnv

type TemplateTypeEnv struct {
	Vars             map[string]string
	StructFields     map[string]map[string]string
	Components       map[string]ComponentContract
	ComponentValues  map[string]bool
	ComponentCalls   *[]pendingComponentCall
	StrictComponents bool
}

func NewTemplateTypeEnv

func NewTemplateTypeEnv() *TemplateTypeEnv

func (*TemplateTypeEnv) Clone

func (e *TemplateTypeEnv) Clone() *TemplateTypeEnv

func (*TemplateTypeEnv) ExprType

func (e *TemplateTypeEnv) ExprType(expr ast.Expr) string

type TextNode

type TextNode struct {
	Pos   TemplatePosition
	Value string
}

type TypeDecl

type TypeDecl struct {
	Name string

	Node *ast.TypeSpec
}

func TransformModuleTypesWithOrigins

func TransformModuleTypesWithOrigins(file *ast.File, moduleName string, origins *OriginTable) ([]TypeDecl, error)

type UnresolvedIdentifier

type UnresolvedIdentifier struct {
	Name   string
	Source goxmap.SourceRange
}

type VarDecl

type VarDecl struct {
	Name string

	Type  ast.Expr
	Value ast.Expr

	Spec *ast.ValueSpec
}

func CollectModuleFields

func CollectModuleFields(file *ast.File, moduleName string) ([]VarDecl, error)

func CollectModuleFieldsWithOrigins

func CollectModuleFieldsWithOrigins(file *ast.File, moduleName string, origins *OriginTable) ([]VarDecl, error)

type WebSocketContract

type WebSocketContract struct {
	Scope        WebSocketContractScope
	Direction    WebSocketContractDirection
	Channel      string
	Event        string
	Arguments    []WebSocketContractArgument
	HasReply     bool
	ReplyTarget  ast.Expr
	ReplyHandler ast.Expr
	Source       token.Pos
}

WebSocketContract is the server-side source of truth for one dynamic client WebSocket event. ReplyTarget is populated for Emit(...).Await(&target); the target's concrete Go type is resolved by the type-inference phase.

type WebSocketContractArgument

type WebSocketContractArgument struct {
	Name string
	Type ast.Expr
	Expr ast.Expr
}

WebSocketContractArgument keeps the Go syntax that defines one client-side argument. On contracts carry a Type; Emit contracts carry an Expr. TypeScript inference is deliberately a later step.

type WebSocketContractDirection

type WebSocketContractDirection string

WebSocketContractDirection is expressed from the browser's point of view. ClientEmit is declared by GOX On; ClientOn is declared by GOX Emit.

const (
	WebSocketContractClientEmit WebSocketContractDirection = "client-emit"
	WebSocketContractClientOn   WebSocketContractDirection = "client-on"
)

type WebSocketContractScope

type WebSocketContractScope string

WebSocketContractScope identifies the client API governed by a server-side WebSocket declaration.

const (
	WebSocketContractSocket  WebSocketContractScope = "socket"
	WebSocketContractChannel WebSocketContractScope = "channel"
)

Source Files

Jump to

Keyboard shortcuts

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