Documentation
¶
Overview ¶
Package gox compiles GoX templates into typed EVM functions.
Index ¶
- Constants
- func AmbientSchema() *evmbind.Schema
- func BuilderType() *values.Type
- func CheckSyntax(filename, source string) error
- func FormatSource(filename, source string, packages ...evm.Package) (string, error)
- func HTMLType() *values.Type
- func Package() evm.Package
- func PackageSource(path string, packages ...evm.Package) (string, error)
- func PackagesSource(packages ...evm.Package) (string, error)
- func Schema() *evmbind.Schema
- func SplitFrontmatter(filename, source string) (data []byte, body string, err error)
- func TrustedContentSchema() *evmbind.Schema
- type Builder
- func (b *Builder) Attr(name string, value any) error
- func (b *Builder) AttrOrOmit(name string, value any) error
- func (b *Builder) Class(value string) error
- func (b *Builder) Close() error
- func (b *Builder) Data(name, value string) error
- func (b *Builder) HTML(value HTML) error
- func (b *Builder) Open(name string) error
- func (b *Builder) Text(value string) error
- type CSS
- type Class
- type ClassList
- type Content
- type Diagnostic
- type Environment
- type File
- type Format
- type HTML
- type HTMLAttr
- type JS
- type JSStr
- type LinkEnvironment
- type LinkOptions
- type Optional
- type Options
- func (o Options) CheckSyntax(filename, source string) (err error)
- func (o Options) Compile(filename, source string, packages ...evm.Package) (*Template, error)
- func (options Options) CompileFiles(entry string, sources map[string]string, packages ...evm.Package) (*Template, error)
- func (options Options) CompileSources(sources map[string]string, packages ...evm.Package) (*Template, error)
- func (o Options) FormatSource(filename, source string, packages ...evm.Package) (_ string, err error)
- func (o Options) Preprocess(filename, source string, packages ...evm.Package) (*Preprocessed, error)
- func (o Options) PreprocessFiles(entry string, sources map[string]string, packages ...evm.Package) (*Preprocessed, error)
- func (o Options) PreprocessSources(sources map[string]string, packages ...evm.Package) (*Preprocessed, error)
- type Parameter
- type Preprocessed
- type Program
- func (p *Program) EVM() *evm.Program
- func (p *Program) File(filename string) (File, bool)
- func (p *Program) Files() []File
- func (p *Program) Frontmatter(name string) (any, bool)
- func (p *Program) FunctionFile(name string) (File, bool)
- func (p *Program) ParametersFor(name string) []Parameter
- func (p *Program) Render(ctx context.Context, args []values.Value, options RenderOptions) (string, error)
- func (p *Program) RenderFunc(ctx context.Context, name string, args []values.Value, options RenderOptions) (string, error)
- func (p *Program) RenderFuncNative(ctx context.Context, name string, args []any, options RenderOptions) (string, error)
- func (p *Program) RenderFunction(ctx context.Context, fn *evm.Callable, args []values.Value, ...) (string, error)
- func (p *Program) RenderFunctionInCall(c *evm.VM, fn *evm.Callable, args []values.Value, options RenderOptions) (string, error)
- func (p *Program) RenderNative(ctx context.Context, args []any, options RenderOptions) (string, error)
- type RenderOptions
- type Srcset
- type Template
- type URL
Examples ¶
Constants ¶
const MaxTagNesting = 100
MaxTagNesting bounds elements inside elements. The formatter indents one level per element, so its output grows with the square of the depth, and a component with children compiles to a function literal per level.
Variables ¶
This section is empty.
Functions ¶
func AmbientSchema ¶
AmbientSchema shares native inherited context with host rendering adapters.
func BuilderType ¶
BuilderType returns the guest type for the renderer's builder parameter.
func CheckSyntax ¶
CheckSyntax checks Go and markup syntax without resolving names or types. Compilation still checks call signatures, rendering contexts and EVM support.
func FormatSource ¶
FormatSource formats GoX and organizes imports, adding the missing ones. Packages supply virtual import paths; no host implementations or type checking are needed. Unknown packages remain unresolved. Layout is fixed, with an 80-column merge/split threshold.
func PackageSource ¶
PackageSource prints declarations with GoX argument annotations.
func PackagesSource ¶
PackagesSource prints all exposed packages with GoX annotations.
func Schema ¶
Schema shares GoX's native builder and trusted-content types with host bindings. Builder fields remain private; the runtime package supplies its render methods.
func SplitFrontmatter ¶
SplitFrontmatter extracts an optional leading --- block without interpreting its contents. A nil result means absent; an empty non-nil result means present. Body excludes the delimiters. Delimiters must occupy whole lines.
func TrustedContentSchema ¶
TrustedContentSchema shares GoX's supported html/template content types with host bindings: HTML, HTMLAttr, CSS, JS, JSStr, URL and Srcset.
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder is the render-scoped capability supplied implicitly to GoX helpers. Its opening tag remains mutable until the first child output. Do not retain it after a render or use it concurrently.
func (*Builder) AttrOrOmit ¶
AttrOrOmit sets an attribute unless value is nil or an empty string. Named string types retain Attr's escaping and trusted-content handling. An empty value does nothing, preserving any existing attribute.
func (*Builder) Close ¶
Close ends the current element. It returns an error if there is no open element.
func (*Builder) Data ¶
Data sets a data-* attribute as escaped text, without URL or CSS filtering. name is the suffix, for example "action" for data-action.
type CSS ¶
CSS marks trusted CSS fragment for context-sensitive rendering. Construct it only from trusted input.
type Class ¶
type Class struct {
Name string
Position evm.SourcePosition
}
Class identifies a statically known CSS class, including classes in helpers.
type ClassList ¶
type ClassList struct {
// contains filtered or unexported fields
}
ClassList builds a space-separated class attribute for passing to another renderer. Prefer Builder.Class when styling the current element directly. The zero value is ready to use. Do not copy a ClassList after the first Add.
type Content ¶
Content holds either plain text or explicitly trusted HTML. Its zero value is empty. TrustedHTML is a trust assertion, not a request to sanitize the content.
func TrustedHTML ¶
TrustedHTML constructs content whose markup is trusted by the caller.
type Diagnostic ¶
type Diagnostic struct {
Position evm.SourcePosition
Message string
}
Diagnostic identifies a GoX source error before rendering.
func (Diagnostic) Error ¶
func (d Diagnostic) Error() string
Error formats the source filename, line, column, and diagnostic.
type Environment ¶
type Environment struct {
// contains filtered or unexported fields
}
Environment is a set of host packages prepared for compiling many templates. It holds what every template can import: the supplied packages, the GoX runtime and the evmstd standard packages.
Building one type-checks all of those packages once. Compiles that name it in Options.Environment check only their own sources. An Environment never changes and is safe for concurrent use.
func NewEnvironment ¶
func NewEnvironment(packages ...evm.Package) (*Environment, error)
NewEnvironment prepares the packages. It fails if any package cannot be imported, including one that no template would import.
func (*Environment) Compiler ¶
func (e *Environment) Compiler() *evmcompiler.Environment
Compiler returns the prepared packages for compiling ordinary Go with evmcompiler. Its sources can import everything a template can.
func (*Environment) NewLinkEnvironment ¶
func (e *Environment) NewLinkEnvironment(packages ...evm.Package) (*LinkEnvironment, error)
NewLinkEnvironment prepares packages for linking what this environment compiles. The packages declare what the environment was built from and bind the implementations, which a compile does not need.
type File ¶
type File struct {
Filename string // Source map key, including directories and .gox extension.
Name string // Basename without .gox, suitable for host resource naming.
Functions []string
Frontmatter any // Host-parsed value; treat as immutable.
HasFrontmatter bool
}
File describes a GoX source file. Functions lists its named package functions in declaration order (excluding init, blank names and methods). Function literals have no package name and are not included. Files need not have frontmatter or functions.
type HTML ¶
Trusted content types bypass selected escaping steps. Only construct them from trusted source, never by casting unvalidated input.
type HTMLAttr ¶
HTMLAttr marks trusted HTML attribute for context-sensitive rendering. Construct it only from trusted input.
type JS ¶
JS marks trusted JavaScript expression for context-sensitive rendering. Construct it only from trusted input.
type JSStr ¶
JSStr marks trusted JavaScript string content for context-sensitive rendering. Construct it only from trusted input.
type LinkEnvironment ¶
type LinkEnvironment struct {
// contains filtered or unexported fields
}
LinkEnvironment is a set of bound host packages prepared for linking many templates and modules. It adds the GoX runtime and the evmstd standard packages, as Template.Link does.
Building one validates and binds the packages once. Its programs share what the packages alone determine. A LinkEnvironment never changes and is safe for concurrent use.
func NewLinkEnvironment ¶
func NewLinkEnvironment(packages ...evm.Package) (*LinkEnvironment, error)
NewLinkEnvironment prepares the packages for linking. It fails where every link against them would fail.
func (*LinkEnvironment) EVM ¶
func (l *LinkEnvironment) EVM() *evm.LinkEnvironment
EVM returns the prepared packages for linking with package evm.
func (*LinkEnvironment) Link ¶
func (l *LinkEnvironment) Link(t *Template) (*Program, error)
Link binds a template to the prepared packages; see Template.Link.
func (*LinkEnvironment) LinkModule ¶
func (l *LinkEnvironment) LinkModule(module *evm.Module) (*Program, error)
LinkModule links an ordinary Go module with GoX builder support; see LinkModule.
type LinkOptions ¶
type LinkOptions struct {
DefaultLimits *evm.Limits
// Compilers are the compile environments that produce the templates and
// modules to link. Programs of what they compile also share the linked
// form of the host storage shapes. Anything else links the same way,
// with shapes of its own.
Compilers []*evmcompiler.Environment
}
LinkOptions configures a link environment.
func (LinkOptions) NewEnvironment ¶
func (o LinkOptions) NewEnvironment(packages ...evm.Package) (*LinkEnvironment, error)
NewEnvironment prepares the packages for linking; see NewLinkEnvironment.
type Optional ¶
Optional distinguishes an omitted component argument from an explicit zero. XML calls construct Value and Present through structural optional recognition.
type Options ¶
type Options struct {
// AllowMissingPackage accepts legacy files without a package clause.
// They inherit the package name from the other files, or use plugin.
AllowMissingPackage bool
// ParseFrontmatter interprets file metadata during preprocessing, before type checking.
// Nil rejects files containing frontmatter.
ParseFrontmatter func([]byte) (any, error)
Format Format
ImplicitTypes []string
// Environment compiles against prepared packages instead of a package
// list. Functions that take packages must then receive none.
Environment *Environment
}
Options fixes the output language during compilation. The zero value is HTML.
func (Options) CheckSyntax ¶
CheckSyntax validates host frontmatter and Go/markup syntax without type checking.
func (Options) CompileFiles ¶
func (options Options) CompileFiles(entry string, sources map[string]string, packages ...evm.Package) (*Template, error)
CompileFiles compiles the package and selects its default renderer by function name or filename.
func (Options) CompileSources ¶
func (options Options) CompileSources(sources map[string]string, packages ...evm.Package) (*Template, error)
CompileSources compiles Go and GoX files together with these options.
func (Options) FormatSource ¶
func (o Options) FormatSource(filename, source string, packages ...evm.Package) (_ string, err error)
FormatSource formats source, accepting a missing package clause only in legacy mode. Frontmatter stays opaque even if Options supplies a parser.
func (Options) Preprocess ¶
func (o Options) Preprocess(filename, source string, packages ...evm.Package) (*Preprocessed, error)
Preprocess lowers a single GoX file for inspection with these options.
func (Options) PreprocessFiles ¶
func (o Options) PreprocessFiles(entry string, sources map[string]string, packages ...evm.Package) (*Preprocessed, error)
PreprocessFiles preprocesses the package and selects its default renderer.
func (Options) PreprocessSources ¶
func (o Options) PreprocessSources(sources map[string]string, packages ...evm.Package) (*Preprocessed, error)
PreprocessSources lowers the supplied package sources for inspection.
type Parameter ¶
type Parameter struct {
Name, Type string
Optional bool
Implicit bool
LegacyName string
// Ambient names a read-only inherited value; callers cannot supply this input.
Ambient string
}
Parameter describes an entry input in Render argument order. Parameter describes a Go input and its legacy argument adapter metadata. Optional is effective optionality, including structural optional types.
type Preprocessed ¶
type Preprocessed struct {
GeneratedSources map[string]string
// contains filtered or unexported fields
}
Preprocessed holds lowered Go and the rendering plan needed to compile it. GeneratedSources is for inspection, not standalone native Go builds. Treat the result and its maps as immutable.
func Preprocess ¶
func Preprocess(filename, source string, packages ...evm.Package) (*Preprocessed, error)
Preprocess lowers one GoX file with the supplied EVM package descriptions. It validates types without generating bytecode or linking host implementations.
func PreprocessFiles ¶
func PreprocessFiles(entry string, sources map[string]string, packages ...evm.Package) (*Preprocessed, error)
PreprocessFiles selects a default renderer by function name or GoX filename.
func PreprocessSources ¶
PreprocessSources lowers a mixed Go/GoX package without selecting a render entry.
func (*Preprocessed) Compile ¶
func (p *Preprocessed) Compile() (_ *Template, err error)
Compile validates the lowered Go and emits EVM bytecode, retaining the rendering plan.
type Program ¶
type Program struct {
// contains filtered or unexported fields
}
Program binds a template to host implementations and supports concurrent renders.
func LinkModule ¶
LinkModule links an ordinary Go module with GoX builder support. Modules compiled from markup must use their Template.Link to retain the operations.
func ProgramOf ¶
ProgramOf returns the GoX runtime that owns this linked program, or nil for programs linked without GoX. Retained functions keep this runtime alive.
func (*Program) Frontmatter ¶
Frontmatter returns the declaring file's metadata for a named function.
func (*Program) FunctionFile ¶
FunctionFile finds the GoX file declaring a named package function.
func (*Program) ParametersFor ¶
ParametersFor returns declared inputs, excluding the builder, for a named renderer.
func (*Program) Render ¶
func (p *Program) Render(ctx context.Context, args []values.Value, options RenderOptions) (string, error)
Render executes with EVM values in Parameters order. Globals and temporary state reset between renders. Host package implementations retain their own state.
func (*Program) RenderFunc ¶
func (p *Program) RenderFunc(ctx context.Context, name string, args []values.Value, options RenderOptions) (string, error)
RenderFunc executes a named renderer. args excludes its explicit builder parameter.
func (*Program) RenderFuncNative ¶
func (p *Program) RenderFuncNative(ctx context.Context, name string, args []any, options RenderOptions) (string, error)
RenderFuncNative executes a named renderer with ordinary Go values as its arguments, excluding the builder: strings and other scalars, time values, pointers to bound native structs, and registered interface implementations. A Go slice or map passes when a linked schema binds its type, as a field or in a signature. Each value must have the Go type its parameter is bound to; there are no implicit numeric conversions. Native pointers and collections are shared with the template, not copied. Conversion counts against options.Budget.
func (*Program) RenderFunction ¶
func (p *Program) RenderFunction(ctx context.Context, fn *evm.Callable, args []values.Value, options RenderOptions) (string, error)
RenderFunction executes a retained renderer, including a closure or bound method. Captures remain shared; the render VM and builder reset between calls. args excludes the renderer's explicit builder parameter.
func (*Program) RenderFunctionInCall ¶
func (p *Program) RenderFunctionInCall(c *evm.VM, fn *evm.Callable, args []values.Value, options RenderOptions) (string, error)
RenderFunctionInCall renders within an active native call, sharing its VM globals, captures, context and budget. It supports nested renders with separate builders. options.Budget must be zero; the enclosing invocation owns limits.
func (*Program) RenderNative ¶
func (p *Program) RenderNative(ctx context.Context, args []any, options RenderOptions) (string, error)
RenderNative executes the default renderer with ordinary Go values. See RenderFuncNative.
type RenderOptions ¶
type RenderOptions struct {
// Coverage collects execution for this linked program; nil disables it.
// Rendering inside a native call inherits its collector.
Coverage *evm.Coverage
// Strict fails on nil field access in output instead of reporting and omitting it.
Strict bool
// Report receives recoverable output diagnostics. Nil logs through slog.
Report func(Diagnostic)
// Budget applies the same execution limits as an EVM script.
Budget evm.Budget
// MaxOutputBytes defaults to 16 MiB. A failed render returns no partial output.
MaxOutputBytes int
}
RenderOptions controls execution limits, output size, and strict rendering.
type Srcset ¶
Srcset marks trusted image source set for context-sensitive rendering. Construct it only from trusted input.
type Template ¶
type Template struct {
Entry string
GeneratedSources map[string]string
DynamicClasses bool
Module *evm.Module
Parameters []Parameter
FunctionParameters map[string][]Parameter
Classes []Class
GeneratedSource string
// contains filtered or unexported fields
}
Template holds bytecode and its immutable rendering plan. Keep the plan with the module; the module alone does not contain the contextual escaping filters. Treat exported metadata as read-only after compilation.
func Compile ¶
Compile compiles an HTML GoX file using EVM's standard and supplied packages.
Example ¶
package main
import (
"context"
"fmt"
"github.com/andreyvit/evm/gox"
"github.com/andreyvit/evm/values"
)
func main() {
tmpl, err := gox.Compile("greeting.gox", `package plugin
import "github.com/andreyvit/evm/gox"
func Greeting(b *gox.Builder, name string) {
<p>
"Hello, "
name
"!"
</p>
}`)
if err != nil {
panic(err)
}
program, err := tmpl.Link()
if err != nil {
panic(err)
}
output, err := program.Render(context.Background(), []values.Value{
values.String("Alice & Bob"),
}, gox.RenderOptions{Strict: true})
if err != nil {
panic(err)
}
fmt.Println(output)
}
Output: <p>Hello, Alice & Bob!</p>
func CompileFiles ¶
func CompileFiles(entry string, sources map[string]string, packages ...evm.Package) (*Template, error)
CompileFiles compiles one package and selects the default renderer by function name or filename. Component tags use exact Go callable names.
func CompileSources ¶
CompileSources compiles ordinary Go and GoX files into one package. Each GoX renderer declares its name and builder parameter. Use RenderFunc to select one. Every file imports the packages it names, including this one.
func (*Template) Files ¶
Files returns all GoX files in filename order. Returned slices may be modified.
func (*Template) Frontmatter ¶
Frontmatter returns the host-parsed metadata of the file declaring name. Presence is independent of the parser's value, which may itself be nil. Treat returned metadata as immutable.
func (*Template) FunctionFile ¶
FunctionFile returns the GoX file declaring a named package function. Ordinary Go files and unknown function names return false.
Source Files
¶
- ambient_call.go
- arg_metadata.go
- bindings.go
- builder.go
- classlist.go
- compile.go
- component_conventions.go
- components.go
- content.go
- content_cell.go
- declarations.go
- environment.go
- expressions.go
- files.go
- format.go
- frontmatter.go
- implicit.go
- link_environment.go
- nil.go
- optimize.go
- optional.go
- output.go
- package.go
- runtime.go
- scan.go
- syntax.go
- template.go
- tooling.go