Help us shape the future of Go! Take the 2026 Go Developer Survey

vuka

package module
v1.5.0 Latest Latest
Warning

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

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

README

Vuka

Vuka

Docs: vuka-lang.github.io

Vuka is Go with Result and Option, ? error propagation, pattern matching, function and method overloading, typed attributes, decorators, and JSX components (rendered by the UI library, on templ), with Elixir-style multi-clause functions on the way. It transpiles to plain Go and builds with the go command you already have.

func area(c Circle) float64 { return math.Pi * c.R * c.R }

@export("RectArea")
func area(r Rect) float64 { return r.W * r.H }

func (c *Counter) Add(by int)    { c.n += by }
func (c *Counter) Add(by string) { c.n += len(by) }

@cache.Memo{TTL: 5 * time.Minute}
func lookup(id int) User { … }
func lookup(arg string) Result[User] {
	id := strconv.Atoi(arg)?          // Go's (T, error) works directly
	u := find(id)?
	return Ok(u)
}

match lookup(arg) {
case Ok(u):
	fmt.Println(u.Name)
case Err(&NotFound{ID: id}):
	fmt.Println("missing user", id)
case Err(e) if errors.Is(e, strconv.ErrSyntax):
	fmt.Println("not a number:", arg)
case Err(e):
	fmt.Println("error:", e)
}
go install github.com/vuka-lang/vuka/cmd/vuka@latest
vuka new shop && cd shop && vuka run -watch .   # a web app: pages, sign-in, a database, tests

A Vuka project is a Go module: .vuka and .go files sit side by side in the same packages and call each other, the way Kotlin and Java share a project. Dependencies are Go's: go get a module and import it from any .vuka file.

Editors

vuka lsp is a language server for .vuka files: gopls behind a proxy that keeps the generated Go open in gopls as unsaved buffers (nothing is written to your tree) and maps every position both ways. Completion, hover, signature help, go to definition, references, rename, outline, code actions, inlay hints and formatting (vuka fmt) all work; Vuka's own errors and Go's type errors show on the .vuka lines. Overloads show under the name you wrote (area, not areaCircle). vuka.File paths (@Page("views/pets.templ")) are clickable.

  • VS Code: the extension in editors/vscode (npm install && npx vsce package, then install the .vsix). It offers to serve your Go files too: run as gopls (a link the extension makes, set as the Go extension's go.alternateTools.gopls), vuka is a drop-in gopls, so .go files in a package with .vuka files see their code instead of "undefined" errors. Both servers use one shared gopls daemon (gopls -remote=auto), so the work is done once.
  • Any other editor: run vuka lsp over stdio for the vuka file type (needs gopls: go install golang.org/x/tools/gopls@latest).

Built to track Go

Vuka owns only its additions. Each one is found by go/scanner and lowered to Go in place; everything else passes through untouched, to be parsed and type-checked by the standard library's go/parser and go/types. When Go adds syntax, Vuka already accepts it.

  • Install Vuka with your own toolchain (go install, or go get -tool and go tool vuka). Its parser is the stdlib of the Go that built it, so it matches yours.
  • TestStdlibPassesThrough feeds every file of $GOROOT/src through Vuka and requires byte-identical output. Run it on a new Go release to find out what, if anything, has to change.
  • The generated code is plain Go; its only runtime is the small Result/Option package. //line directives point compile errors and panics at the .vuka source, down to the column.

What works

Result and Option live in the runtime package github.com/vuka-lang/vuka (its root; nothing else in it). Vuka code writes Result[User], Ok(u), Err(e), Some(x) and None unqualified, and the transpiler adds the import wherever the package doesn't declare those names itself. Err and None take their type from where the value goes (return Err(e) in a function returning Result[User]). Result's error is Go's error, so it meets Go code halfway: vuka.Of(os.ReadFile(p)) wraps a Go call, r.Get() hands back (T, error). Your module needs the dependency: go get github.com/vuka-lang/vuka.

? ends a statement: x := f()?, x = f()?, var x = f()?, return f()? or f()?. The operand is Go's (T…, error), an error, a Result, or an Option (in a function returning an Option). On failure the function returns: zero values plus the error, Err(e), or None, whichever its results call for. The operand stays where it is, so nothing is reordered.

match is a statement of cases, tried in order:

pattern matches
_, default anything
x anything, binding it to x (a constant's name compares instead)
0, "a", Max, pkg.Const, true an equal value
^x the value of the variable x (Elixir's pin)
Ok(p), Err(p), Some(p), None a Result or Option, then p inside
T{F: p, …}, &T{…} a struct's fields; against an interface, a type test too
1, 2, 3 any of them

case p if cond: adds a guard. A match must be exhaustive (Ok and Err, Some and None, true and false, or a case that takes anything), and a case after one that matches everything is an error; both are reported before Go sees the code.

Overloading. Functions and methods may share a name when their parameter types differ. Each declaration is named after its parameters' types, as Go would name it (areaCircle, AddIntInt), and each call goes to the overload that best fits its arguments' static types: identical types beat an untyped constant's default type, which beats any other assignable value. A tie is a compile error that lists the candidates. Calls whose argument types come from other overloaded calls resolve too.

Attributes come before a top-level declaration:

@doc("…") becomes the declaration's doc comment
@deprecated("…") adds a Deprecated: paragraph
@export("Name") generates Name, a wrapper with the declaration's signature: how Go code reaches one overload
@T / @pkg.T{…} any Go type, bare or as a composite literal; the generated code type-checks it

Decorators wrap a declaration, Python-style. The simplest kind works on any function, whatever its signature:

decorator logged(c) {
	fmt.Println("calling", c.Name, c.Args)
	c.Next()                                   // run the function (or the next decorator)
	fmt.Println("returned", c.Results)
}

decorator retry(times int)(c) {             // with parameters
	for i := 0; i < times; i++ {
		if c.Next(); c.Err() == nil {
			return
		}
	}
}

@retry(3)
@logged
func charge(ctx context.Context, id int) (Receipt, error) { … }

@logged
func (s *Store) Save(u User) error { … }   // methods too

decorator name(c) { … } is shorthand for func name(c *vuka.Call), a vuka.Decorator; plain Go functions of that type work the same, in .vuka or .go files. A decorator with parameters (retry(3)) is built once per decorated function, so state it keeps (a cache, a counter) isn't shared.

*vuka.Call
c.Name, c.Receiver "main.charge"; the receiver of a method
c.Args, c.Results arguments (change them before Next) and results
c.Next() run the rest; call it again to retry, or not at all
c.Return(v…) answer without running the function (caches, mocks)
c.Err(), c.SetErr(err) the trailing error result
c.Context() the context.Context argument
vuka.Arg[T](c, i) argument i as a T
c.Attr(&x), vuka.AttrOf[T](c) a typed attribute on the same declaration
@Perm("orders.write")
@guard                                      // reads it: var p Perm; c.Attr(&p)
func save(ctx context.Context, o Order) error { … }

A type decorator receives the type: func Model(t *vuka.Type) gets t.Name, t.Reflect and t.Attr, at init. Packing a call into a *vuka.Call costs a small allocation; for hot paths, a typed decorator func(F) F (or for a type, a generic func[T]) has none and checks every type. Vuka picks the form from the decorator's type, so both mix freely, and a decorator that fits neither is a compile error on its @ line. Functions keep their name for a wrapper that builds the decorated function once; recursion goes through it; init, overloads, generic functions and type ( … ) groups can be decorated.

A declarer, func(d *vuka.Decl) (or a call returning one, such as @Command("greet")), doesn't wrap calls: it runs once at init, top to bottom, with the function's name, attributes, parameter names and types, and the decorated function itself — the way to register routes, commands or jobs. A string literal passed where a decorator or attribute takes a vuka.File (@Page("views/pet.html")) is checked at compile time and embedded in the binary; f.Bytes() reads it, and with ui, templx.Components(f) gives a .templ file's components with their parameter names — also for a .templ file in a subdirectory, which is a package of its own (package views).

Static fields and methods belong to a type, as in Kotlin or Java:

type User struct {
	Name string

	static Table   = "users"
	static created int            // private: lowercase, as in Go
	static const Max = 100
}

func User.New(name string) *User {
	User.created++
	return &User{Name: name}
}

u := User.New("ada")
fmt.Println(User.Table, User.Max)

They lower to plain package-level Go: UserTable, userCreated, and for the constructor Go's func NewUser, which is also how Go code reaches them. A static can't share a name with a field or method (in Go, User.Save already means a method).

A static on a generic type has one value per instantiation, and statics are reached through embedding. With a base type whose type parameter is named Self, Vuka fills in the embedding type, and methods taking self *Self get the whole outer value:

type Model[Self any] struct {
	static Objects = Store[Self]{}           // one Store per embedding type
}

func (m *Model[Self]) Save(self *Self) { Model[Self].Objects.Add(self) }

type User struct {
	Model               // = Model[User]
	Name string
}

u.Save()                    // Save gets u itself as self
users := User.Objects.All() // User's own store, from Model

Model[User] written out works the same. Self is filled in only for a type parameter of that name, so other generics never get a type argument you didn't write. A type embedding User reaches User's statics, as Go promotes fields; self there is the embedded User. Calls that pass self must not have side effects in the receiver expression (Vuka uses it twice). The orm library's models are built this way.

Field attributes and references. A struct field takes typed attributes after it (after its tag, if any), and Type.Field — meaningless in Go — is a typed reference to the field:

type Post struct {
	ID     int64    @PK
	Title  string   `json:"title"` @Char{Max: 200}
	Author FK[User] @Rel{OnDelete: Cascade}
	Views  int      @Default(0)
}

q := vuka.And(Post.Title.Contains("go"), Post.Author.Name.Eq("ada"), Post.Views.Gt(100))
q.Match(post)                         // in memory; or translate q.Op, q.Path, q.Value
vuka.SortBy(posts, Post.Views.Desc())

Attributes are type-checked Go values, stripped from the struct and recorded at init: vuka.FieldAttrs[Post]()["Title"], vuka.FieldsOf[Post](), or Attrs in a type decorator's fields. A reference continues through struct and pointer fields, embedded structs, and types implementing vuka.Related[U] (a foreign key's Related() *U). Its type follows the field's — StringRef has Contains, OrderedRef has Gt, NullableRef has IsNil — and its predicates are vuka.Pred[Post], so an API taking them rejects a User field. Hover and go to definition on a reference land on the field.

Dependency injection comes from a type decorator, with no annotations on fields: a struct's fields are its dependencies.

@di.Component
type OrderService struct {
	db    *DB
	users *UserService
	mu    sync.Mutex `inject:"-"`   // not a dependency
}

A type decorator func(t *vuka.Type) on a struct gets t.New, a constructor taking each injected field as a parameter, func(db *DB, users *UserService) *OrderService: the shape nexus.Provide, fx.Provide and dig.Provide take, so a container wires it from parameter types, with no reflection on fields (and unexported fields work). Every field is injected except _, those tagged inject:"-", and embedded values (embedded pointers and interfaces are). A struct that declares its own static New is built with that instead; otherwise the generated constructor is its static New, handy in tests: OrderService.New(fakeDB, fakeUsers). t.Fields lists the fields with their tags, attributes and whether they're injected.

The whole nexus integration is a few lines (examples/nexus-di):

var providers []any

func Component(t *vuka.Type) { providers = append(providers, t.New) }
func Module() nexus.Option  { return nexus.Provide(providers...) }

CLI

vuka new <dir> [module path] [flags]
vuka add module <name>
vuka mod tidy|why|vendor|… [args]
vuka explain [-full] file.vuka
vuka fix [-n] [fixer…]
vuka fmt [-l] [-w] [-d] [paths…]
vuka build|run|test|vet|install [go flags] [packages]
vuka gen [-check] [-o build]
vuka gen -inplace [-check] [dir | dir/...]
vuka lsp

build, run and the rest transpile the module into a temporary overlay (go build -overlay), so no generated file lands among your sources.

vuka explain file.vuka shows each line Vuka rewrites beside the Go it becomes, then the code it adds after the source (decorator wrappers, statics), each labelled with the line it comes from; -full prints the whole generated file.

vuka fmt formats .vuka files the way gofmt formats Go (-w writes them back, -l lists those that differ, -d shows the diff): the Go exactly as gofmt prints it, Vuka's syntax spaced to match, and JSX laid out Prettier-style, without changing what a page renders.

vuka fix repairs what tooling can: runtime upgrades the module's Vuka runtime when generated code needs a newer one, static-names rewrites statics spelt by their Go names (User_Table) to User.Table in .vuka files, orphans removes files vuka gen -inplace wrote for .vuka files that are gone, attr-of renames vuka.Attr[T](c) to vuka.AttrOf[T](c) (v0.5.0), ui moves UI code to github.com/vuka-lang/ui (v0.10.0), attributes and hooks write struct tags and hooks found by name as attributes, ui-structs writes the ui kit's components as struct literals, templates-package starts each .vuka.html with its package clause, and db-schema and queries move code to orm v1.0.0's DBSchema and model managers. -n reports without changing anything; name fixers to run only those. It is also where future syntax changes will get their codemods.

vuka, ui, web, the command and vukavet share one version, and from v1.0.0 they keep the compatibility promise: an app that builds and passes its tests on v1.x keeps doing so on every later v1. vuka version prints the set and warns when an app's go.mod mixes sets; vuka upgrade [version] moves an app to a set, runs the vuka fix rewrites for the releases in between, then vet and tests. See Versions and compatibility.

JSX. Markup is an expression, and a component is a function. JSX is syntax: what it renders with is the library the file imports, its JSX target — github.com/vuka-lang/ui, where ui.Node is templ.Component:

import "github.com/vuka-lang/ui"

func PetRow(pet Pet) ui.Node {
	return <tr><td>{pet.Name}</td><td>{pet.Age}</td></tr>
}

func Page(pets []Pet) ui.Node {
	return <Shell title="Pets">                      // a templ component
		<table>{for _, p := range pets { <PetRow pet={p} /> }}</table>
	</Shell>
}

Attributes bind to parameters by name (or to a props struct's fields), children to a children parameter; {for}, {if} and {match} blocks hold markup; all of it type-checked against the target's declarations. A package is a target when it declares const VukaJSX = 1 and the contract's names. ui renders HTML (ui.Handler/Write/String) and terminal text (ui/term), and its stateful components — a struct embedding ui.Live, onClick={c.Inc} — stay live for a connected page through ui/live. State the browser keeps (ui.State, a menu's open) is read in JSX as plain Go expressions. A Vue, React or Svelte component imported into a .vuka file is an island, its props read from its TypeScript and type-checked; with @web.Get on its Go type it is a whole page. .templ files compile with the package, no templ generate, in modules that require templ. See JSX, UI and Islands.

The build module

Like Kotlin's build/, vuka build and vuka gen keep a build/ directory: a complete Go module with the same module path, where every .vuka file is replaced by its generated Go and everything else is copied (.go files, embedded assets, testdata; relative replace paths in go.mod adjusted). Inside it, plain Go tools need no Vuka at all:

vuka gen
cd build && go build ./... && go test ./... && go vet ./...

The sync is incremental (only changed files are written, deleted sources are removed), compile errors in build/ point at the .vuka lines, and a .vuka-build marker means vuka never syncs over a directory it didn't make. vuka new adds /build/ to .gitignore. vuka gen -check fails when build/ is out of date, for CI.

Roadmap

  1. Enums (sum types) with exhaustive match; lambdas, ?., ??, tuples, functional helpers (the rest of Dingo's set)
  2. Multi-clause functions with patterns and guards; arity overloading for default arguments; Elixir-style module attributes (@max 3, read as @max)
  3. @derive and generator attributes; lowering to native Go when a Go release adds an equivalent feature

Libraries

  • web — a web framework: routes, services and controllers declared with decorators, parameters bound by name, templ / html / JSX views, dependency injection, .env configuration and live components over a WebSocket. Docs: vuka-lang.github.io/web.
  • orm — a Django-style ORM: models declared with field attributes (a Schema method in Go), queries written with typed fields, orm.Transaction, search, several databases and Go migrations. Docs: vuka-lang.github.io/orm.

Other modules go get your repository root, not build/. To publish a Vuka library for Go users, write the generated files beside the sources and commit them (vuka gen -inplace, and vuka gen -inplace -check in CI).

Known limits

  • Overloads are resolved within a package; calling another package's overloads goes through its @export names.
  • Generic functions can't be overloaded yet.
  • Go's own error messages, outside the editor, show the overloads' Go names (areaInt).
  • An overloaded method can't satisfy an interface method of the plain name.
  • ? ends a statement; it can't sit inside a larger expression, or in an if, for or switch header.
  • Struct patterns of generic types aren't supported yet.

Documentation

Overview

Package vuka is the runtime of Vuka programs: Result and Option.

Vuka code writes Result[User], Ok(u), Err(e), Some(x) and None unqualified; the transpiler points them here. Go code uses the package like any other.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFunc = errors.New("vuka: not a function")

ErrNotFunc is FuncOf's error for a value that is no function, or nil.

Functions

func Arg added in v0.2.0

func Arg[T any](c *Call, i int) T

Arg is argument i as a T.

func As added in v0.2.0

func As[T any](v any) T

As converts a value held in an any back to T; nil is T's zero value. It panics, naming both types, when a decorator put something else there.

func AttrOf added in v0.5.0

func AttrOf[T any](c *Call) (T, bool)

AttrOf is the declaration's typed attribute of type T.

func DeclareWith deprecated added in v0.10.0

func DeclareWith(b Bundle, d *Decl)

DeclareWith is b.Declare(d).

Deprecated: call b.Declare(d); code generated by older versions of the vuka command calls DeclareWith.

func DecorateType deprecated added in v0.10.0

func DecorateType(b Bundle, t *Type)

DecorateType is b.Decorate(t).

Deprecated: call b.Decorate(t); code generated by older versions of the vuka command calls DecorateType.

func FieldAttrs added in v0.7.0

func FieldAttrs[T any]() map[string][]any

FieldAttrs is the typed attributes of T's fields, by field name: for

type Post struct {
	Title string @Char{Max: 200}
}

FieldAttrs[Post]()["Title"] is []any{Char{Max: 200}}. It is nil for a type whose fields carry none. It holds the attributes RegisterFields recorded and those a FieldAttrsDeclarer declares: a model's Schema method's (s.Field(&p.Title, orm.Char{Max: 200})), with its model attributes on its embedded orm.Model field, where a Vuka model writes them.

func FieldAttrsOf added in v0.7.0

func FieldAttrsOf(t reflect.Type) map[string][]any

FieldAttrsOf is FieldAttrs for a reflect.Type.

func Instance

func Instance[F any](s *Instances, build func() F) F

Instance returns the instantiation of a generic decorated function whose type is F, building it the first time.

func ObserveCalls added in v0.14.0

func ObserveCalls(fn CallObserver) (stop func())

ObserveCalls has fn see the steps of every decorated call of the program: the hook of a tracer, or of a web framework's development toolbar timing each decorator. It returns what stops it.

func RegisterAdapter added in v1.0.0

func RegisterAdapter[F any](adapt func(next F, call Caller) F)

RegisterAdapter has Wrap call functions of type F through adapt instead of reflection: adapt packs a call's arguments for call and unpacks its results. The vuka command writes one per signature a package decorates, in vuka_calls_gen.go:

vuka.RegisterAdapter(func(next func(int, int) int, call vuka.Caller) func(int, int) int {
	invoke := func(a []any) []any { return []any{next(vuka.As[int](a[0]), vuka.As[int](a[1]))} }
	return func(a0, a1 int) int {
		r := call([]any{a0, a1}, invoke)
		return vuka.As[int](r[0])
	}
})

The first adapter registered for F is kept.

func RegisterFields added in v0.7.0

func RegisterFields[T any](attrs map[string][]any)

RegisterFields records the typed attributes of T's fields, by field name, for FieldAttrs to read: Vuka's field attributes on a struct with no schema method to hold them (orm.Base's Schema, ui.Live's LiveSchema), written at init.

func init() {
	vuka.RegisterFields[Address](map[string][]any{"City": {Char{Max: 50}}})
}

func RegisterFunc added in v0.16.0

func RegisterFunc(fn any, attrs ...any)

RegisterFunc records the typed attributes of a function, or of a method given as its method expression ((*Board).Clear). Generated code calls it at init; Go code may too, for a declaration it writes by hand.

func RegisterType added in v0.16.0

func RegisterType[T any](attrs ...any)

RegisterType records the typed attributes of type T. Generated code calls it at init.

func SortBy added in v0.7.0

func SortBy[T any](xs []T, orders ...Order[T])

SortBy sorts xs by the orders, the first deciding, the next breaking ties; the sort is stable.

func Wrap added in v1.0.0

func Wrap[F any](fn F, info FuncInfo, chain ...Decorator) F

Wrap is fn with chain around each of its calls, outermost first: what a call decorator on a function is, written by hand.

var save = vuka.Wrap(saveOrder, vuka.FuncInfo{Name: "orders.save"}, logged, retry(3))

A method keeps its name and calls the wrapped method expression, built on first use (a package-level var can't refer to itself):

var storeSave vuka.Decorated[func(*Store, context.Context, Order) error]

func (s *Store) Save(ctx context.Context, o Order) error {
	return storeSave.Get(func() func(*Store, context.Context, Order) error {
		return vuka.Wrap((*Store).save, vuka.FuncInfo{Name: "Store.Save", Method: true}, logged)
	})(s, ctx, o)
}

The call goes through reflection unless an adapter for F is registered (RegisterAdapter), which the vuka command generates for a package's decorated functions. With no decorators Wrap is fn.

Types

type Attrs added in v0.16.0

type Attrs []any

Attrs are a declaration's typed attributes, as the lookups return them.

func MethodAttrs added in v0.16.0

func MethodAttrs(t reflect.Type, name string) Attrs

MethodAttrs are the typed attributes declared on method name of t (or of the type t points to), its bundles' included; not its type's, which TypeAttrs has. None for a method Vuka registered nothing for.

func TypeAttrs added in v0.16.0

func TypeAttrs(t reflect.Type) Attrs

TypeAttrs are the typed attributes declared on t (or on the type t points to); none for a type Vuka registered nothing for.

func (Attrs) Attr added in v0.16.0

func (a Attrs) Attr(ptr any) bool

Attr fills ptr with the attribute of ptr's element type, reporting whether there is one, as Call.Attr and Decl.Attr do: var g Gate; attrs.Attr(&g).

type Bundle added in v0.10.0

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

Bundle is a composed decorator: decorators and attributes applied as one, as Spring's @RestController stands for @Controller and @ResponseBody.

decorator ApiRoute(path string) = @web.Get(path) @web.Use(auth) @timed

declares a function returning a Bundle; @ApiRoute("/pets") on a function applies each of them, in order, as if written there. Plain Go builds one with Compose.

func Compose added in v0.10.0

func Compose(items ...any) Bundle

Compose bundles decorators and attributes: each item is a call decorator (func(*Call)), a declarer (func(*Decl)), a type decorator (func(*Type)), another Bundle (its items, in place), or an attribute (any other value).

func Dual added in v0.30.0

func Dual(decl func(*Decl), typ func(*Type)) Bundle

Dual is a decorator for a function and for a type alike: written on a function it runs decl, on a type typ. web.Get is one: a route on a handler, a page on a component type.

func (Bundle) Attrs added in v0.10.0

func (b Bundle) Attrs() []any

Attrs are the bundle's typed attributes, in order.

func (Bundle) Calls added in v0.10.0

func (b Bundle) Calls() []Decorator

Calls are the bundle's call decorators, outermost first.

func (Bundle) Declare added in v1.0.0

func (b Bundle) Declare(d *Decl)

Declare runs the bundle's declarers with d, as when it is written on the function d describes: b.Declare(vuka.DeclOf(ShowPet)).

func (Bundle) Decls added in v0.10.0

func (b Bundle) Decls() []func(*Decl)

Decls are the bundle's declarers, in order.

func (Bundle) Decorate added in v1.0.0

func (b Bundle) Decorate(t *Type)

Decorate runs the bundle's type decorators with t, as when it is written on the type t describes: b.Decorate(vuka.TypeFor[Board](NewBoard)).

func (Bundle) Types added in v0.10.0

func (b Bundle) Types() []func(*Type)

Types are the bundle's type decorators, in order.

type Call added in v0.2.0

type Call struct {
	Name     string
	Receiver any   // the receiver, for a method
	Args     []any // the arguments; a variadic parameter is one slice
	Results  []any // the results, once Next has run (or Return was called)
	// contains filtered or unexported fields
}

Call is one call of a decorated function, passed down its decorators.

func NewCall deprecated added in v0.2.0

func NewCall(fn *Func, chain []Decorator, recv any, args []any, invoke func(c *Call) []any) *Call

NewCall starts a call through chain, ending in invoke.

Deprecated: use Wrap; code generated by older versions of the vuka command calls NewCall.

func (*Call) Attr added in v0.2.0

func (c *Call) Attr(ptr any) bool

Attr fills ptr with the declaration's typed attribute of ptr's element type, reporting whether there is one: var r Route; c.Attr(&r).

func (*Call) Attrs added in v0.16.0

func (c *Call) Attrs() Attrs

Attrs are the declaration's typed attributes, its bundles' included: on a method, its own (a type's call decorators advising it see the method's, not the type's).

func (*Call) Context added in v0.2.0

func (c *Call) Context() context.Context

Context is the call's context.Context argument, or context.Background().

func (*Call) Err added in v0.2.0

func (c *Call) Err() error

Err is the function's error result, or nil.

func (*Call) Next added in v0.2.0

func (c *Call) Next()

Next runs the rest of the chain: the next decorator, or the function itself. It can be called more than once.

func (*Call) ParamAttr added in v0.10.0

func (c *Call) ParamAttr(i int, ptr any) bool

ParamAttr fills ptr with parameter i's typed attribute of ptr's element type, reporting whether there is one. i indexes c.Args:

func Create(@Valid in NewPet) error

for i := range c.Args {
	var v Valid
	if c.ParamAttr(i, &v) { … }
}

func (*Call) Return added in v0.2.0

func (c *Call) Return(results ...any)

Return sets the results without running the function; the rest of the chain is skipped unless Next is called.

func (*Call) Run added in v0.2.0

func (c *Call) Run()

Run runs the chain of a NewCall and checks what it left in Results.

func (*Call) SetErr added in v0.2.0

func (c *Call) SetErr(err error)

SetErr replaces the error result. Before Next, it makes the call fail with zero values and err.

type CallObserver added in v0.14.0

type CallObserver func(c *Call, d Decorator) (done func())

CallObserver sees a decorated call go through its steps, on the goroutine of the call: each decorator (d), and the function itself (d nil). What it returns, when not nil, is called once the step returns.

type Caller added in v1.0.0

type Caller func(args []any, invoke func(args []any) []any) []any

Caller runs a call through its decorators: args are the call's, the receiver first for a method, and invoke calls the function with the arguments the decorators leave; it returns the results they leave.

type CompareRef added in v0.7.0

type CompareRef[T any, V interface{ Compare(V) int }] struct{ Ref[T, V] }

CompareRef is a reference to a field whose type orders itself, such as time.Time.

func CompareRefOf added in v0.7.0

func CompareRefOf[T any, V interface{ Compare(V) int }](index [][]int, _ func(*T)) CompareRef[T, V]

func CompareRefTo added in v1.0.0

func CompareRefTo[T any, V interface{ Compare(V) int }](field func(*T) *V) CompareRef[T, V]

func (CompareRef[T, V]) Asc added in v0.7.0

func (r CompareRef[T, V]) Asc() Order[T]

func (CompareRef[T, V]) Desc added in v0.7.0

func (r CompareRef[T, V]) Desc() Order[T]

func (CompareRef[T, V]) Ge added in v0.7.0

func (r CompareRef[T, V]) Ge(v V) Pred[T]

Ge is the predicate field >= v, by V's Compare.

func (CompareRef[T, V]) Gt added in v0.7.0

func (r CompareRef[T, V]) Gt(v V) Pred[T]

Gt is the predicate field > v, by V's Compare.

func (CompareRef[T, V]) Le added in v0.7.0

func (r CompareRef[T, V]) Le(v V) Pred[T]

Le is the predicate field <= v, by V's Compare.

func (CompareRef[T, V]) Lt added in v0.7.0

func (r CompareRef[T, V]) Lt(v V) Pred[T]

Lt is the predicate field < v, by V's Compare.

type Decl added in v0.6.0

type Decl struct {
	Name  string // "main.ShowPet", "PetAdmin.Index"
	Pkg   string // the package's import path
	File  string // the source file's base name, and the line of the name, for messages
	Line  int
	Attrs []any // the declaration's typed attributes
	// Func is the function, wrapped by the declaration's other decorators, so
	// calling it runs them too. For a method it is the method expression:
	// func(recv, args…).
	Func     any
	Recv     reflect.Type // the receiver type, for a method
	Params   []Param      // the parameters, receiver excluded
	Results  []reflect.Type
	Variadic bool
}

Decl describes a declaration for a declarer: a decorator of type func(d *vuka.Decl), which runs once at program start rather than around each call. Declarers register things — routes, commands, jobs — from the declarations they decorate:

func Get(path string) func(*vuka.Decl) {
	return func(d *vuka.Decl) { routes[path] = d.Func }
}

func DeclOf added in v1.0.0

func DeclOf(fn any, params ...Param) *Decl

DeclOf describes a function, or a method by its method expression ((*Store).Save), for its declarers, which are called with it:

Get("/pets/{id}")(vuka.DeclOf(ShowPet, vuka.Param{Name: "id"}))

params name its parameters and give their attributes, in order, the receiver excluded (reflection can't see names). Its attributes are those registered for it (RegisterFunc), its file and line where the compiler puts it, and its Name the runtime's: the package is its import path's last element ("main" in a program, though a main package's tests build it under its path).

func FuncDecl deprecated added in v0.6.0

func FuncDecl(d Decl, params ...string) *Decl

FuncDecl describes a function for its declarers.

Deprecated: use DeclOf; code generated by older versions of the vuka command calls FuncDecl.

func MethodDecl deprecated added in v0.6.0

func MethodDecl(d Decl, params ...string) *Decl

MethodDecl describes a method, d.Func being its method expression.

Deprecated: use DeclOf; code generated by older versions of the vuka command calls MethodDecl.

func (*Decl) Attr added in v0.6.0

func (d *Decl) Attr(ptr any) bool

Attr fills ptr with the declaration's typed attribute of ptr's element type, reporting whether there is one: var r Route; d.Attr(&r).

type Decorated

type Decorated[F any] struct {
	// contains filtered or unexported fields
}

Decorated holds a decorated function, built from its decorators on first use. Vuka generates one per decorated function or method.

func (*Decorated[F]) Get

func (d *Decorated[F]) Get(build func() F) F

Get returns the decorated function, building it the first time.

type Decorator added in v0.2.0

type Decorator func(c *Call)

Decorator wraps a call of any function: it runs code around c.Next(), may change c.Args before it, read or replace c.Results after it, call it again (retries) or not at all (caches). Written once, it decorates any function or method:

func logged(c *vuka.Call) {
	fmt.Println("calling", c.Name, c.Args)
	c.Next()
}

A decorator with parameters is a function returning one; it runs once per decorated function, so state it keeps isn't shared between functions.

type Field added in v0.3.0

type Field struct {
	Name     string
	Type     reflect.Type
	Tag      reflect.StructTag
	Attrs    []any // the field's typed attributes
	Injected bool  // not blank, not tagged inject:"-": a parameter of New, when a pointer or interface for a type declaring a schema
}

Field is a field of a struct.

func FieldsOf added in v0.7.0

func FieldsOf[T any]() []Field

FieldsOf describes the fields of the struct T, with their tags and attributes. It is nil when T isn't a struct.

func (Field) Attr added in v0.7.0

func (f Field) Attr(ptr any) bool

Attr fills ptr with the field's typed attribute of ptr's element type, reporting whether there is one: var c Char; f.Attr(&c).

type FieldAttrsDeclarer added in v1.0.0

type FieldAttrsDeclarer interface {
	DeclaredFieldAttrs(t reflect.Type, registered map[string][]any) map[string][]any
}

FieldAttrsDeclarer is a struct whose fields' attributes are declared another way than RegisterFields: by a library's schema method, as a model's are in its Schema method (orm.Model and orm.Base implement it). FieldAttrsOf asks it for t's — t being the struct or one embedding it — given what RegisterFields recorded for t, which it returns with the attributes it declares after them, or as they are when t isn't its own. It is asked of a zero t: a method of a pointer receiver it doesn't read is safe behind a nil embedded pointer.

type FieldPath added in v0.7.0

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

FieldPath is where a field reference leads from its root struct: one step per field written (Post.Author.Name has two), each step an index path that passes through embedded structs. Between steps it goes through a pointer or a Related value.

func (FieldPath) Attr added in v0.7.0

func (p FieldPath) Attr(ptr any) bool

Attr fills ptr with the last field's typed attribute of ptr's element type.

func (FieldPath) Attrs added in v0.7.0

func (p FieldPath) Attrs() []any

Attrs are the typed attributes of the last field.

func (FieldPath) Fields added in v0.7.0

func (p FieldPath) Fields() []reflect.StructField

Fields are the struct fields of each step.

func (FieldPath) Index added in v0.7.0

func (p FieldPath) Index() [][]int

Index is the reflect index path of each step.

func (FieldPath) Names added in v0.7.0

func (p FieldPath) Names() []string

Names are the fields as written: ["Author", "Name"].

func (FieldPath) Root added in v0.7.0

func (p FieldPath) Root() reflect.Type

Root is the struct type the path starts from.

func (FieldPath) String added in v0.7.0

func (p FieldPath) String() string

func (FieldPath) Value added in v0.7.0

func (p FieldPath) Value(root any) (any, bool)

Value follows the path in root, a value or pointer of the root type. It reports false when a nil pointer or relation is on the way.

type File added in v0.6.0

type File string

File names a file of the program's source tree. A string literal written where a decorator or typed attribute takes a File is checked when the program is compiled (it must exist, in the package's directory or below) and embedded into the binary; the File then holds "importpath:relative/path" and Bytes returns the embedded content:

func Template(view vuka.File) func(*vuka.Decl) { … view.Bytes() … }

@Template("views/pet.html")
func showPet(id int) Pet { … }

A .templ file may be in a subdirectory that is a package of its own (views/pets.templ with `package views`): its File is then that package's ("module/views:pets.templ"). With templ and github.com/vuka-lang/ui, the file's components are registered too: templx.Components(f).

func FileOf added in v0.6.0

func FileOf(key, data string) File

FileOf is an embedded file's File. Generated code calls it.

func (File) Bytes added in v0.6.0

func (f File) Bytes() ([]byte, error)

Bytes is the file's content: embedded, or for a File Vuka didn't embed (a conversion such as vuka.File("x.txt")) read from disk.

func (File) Path added in v0.6.0

func (f File) Path() string

Path is the file's path, relative to its package's directory.

func (File) Pkg added in v0.6.0

func (f File) Pkg() string

Pkg is the import path of the package the file belongs to; "" for a File Vuka didn't embed.

type Func deprecated added in v0.2.0

type Func struct {
	Name  string // "main.charge", "Store.Save"
	Attrs []any  // the declaration's typed attributes
	// ParamAttrs are each parameter's typed attributes, receiver excluded:
	// func Show(@Path("id") id int) has [][]any{{Path("id")}}. Nil when no
	// parameter has any.
	ParamAttrs [][]any
	ErrIndex   int // the trailing error result's index, or -1
	CtxIndex   int // the context.Context argument's index, or -1
	Zero       func() []any
}

Func describes a decorated function for NewCall.

Deprecated: use Wrap and FuncInfo; code generated by older versions of the vuka command builds a Func.

type FuncInfo added in v1.0.0

type FuncInfo struct {
	Name       string
	Method     bool
	Attrs      []any
	ParamAttrs [][]any
}

FuncInfo describes a function for its call decorators: the name they see (c.Name), whether its first parameter is a receiver (a method expression, (*Store).save), and the typed attributes c.Attr and c.ParamAttr read, the receiver's excluded.

type FuncRef added in v0.16.0

type FuncRef struct {
	Name string // the runtime's name for the code: "example.com/app.(*Board).Clear-fm"
	// Recv is a method's receiver type as declared (Board for *Board) when
	// Vuka registered the type or one of its methods; Method is the
	// method's name.
	Recv   reflect.Type
	Method string
	// Attrs are the declaration's typed attributes: a method's own (its
	// type's are TypeAttrs(Recv)).
	Attrs Attrs
	// Literal says fn is a function literal ("…(*Board).Render.func1"): it
	// is no declaration and has no attributes, and what it calls is found
	// only when it runs.
	Literal bool
}

FuncRef is the declaration a function value's code belongs to, as FuncOf finds it.

func FuncOf added in v0.16.0

func FuncOf(fn any) (FuncRef, error)

FuncOf finds the declaration fn's code belongs to: a function, a method expression ((*Board).Clear) or a method value (b.Clear). A function literal is reported as one (Literal); a function or method nothing registered has no Attrs. A method value made by reflection (reflect.Value.Method) names no declaration either: look it up with MethodAttrs. Answers are cached per function, so a lookup costs a map read after the first.

type Instances

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

Instances holds a generic decorated function's instantiations, each built from its decorators on first use.

type NoAdvice added in v0.10.0

type NoAdvice struct{}

NoAdvice, on a method, leaves it out of its type's advice: the call decorators written on the type, which wrap its other exported methods.

@logged
type Store struct{ … }

@vuka.NoAdvice
func (s *Store) Dump() string { … }

type NullableRef added in v0.7.0

type NullableRef[T, V any] struct{ Ref[T, V] }

NullableRef is a reference to a field that can be nil or None.

func NullableRefOf added in v0.7.0

func NullableRefOf[T, V any](index [][]int, _ func(*T)) NullableRef[T, V]

func NullableRefTo added in v1.0.0

func NullableRefTo[T, V any](field func(*T) *V) NullableRef[T, V]

func (NullableRef[T, V]) IsNil added in v0.7.0

func (r NullableRef[T, V]) IsNil() Pred[T]

IsNil is the predicate that the field is nil or None (or that a nil pointer or relation is on the way).

func (NullableRef[T, V]) NotNil added in v0.7.0

func (r NullableRef[T, V]) NotNil() Pred[T]

NotNil is the predicate that the field is neither nil nor None.

type Op added in v0.7.0

type Op string

Op is what a predicate tests.

const (
	OpEq         Op = "eq"
	OpNe         Op = "ne"
	OpLt         Op = "lt"
	OpLe         Op = "le"
	OpGt         Op = "gt"
	OpGe         Op = "ge"
	OpIn         Op = "in"
	OpContains   Op = "contains"
	OpStartsWith Op = "startswith"
	OpEndsWith   Op = "endswith"
	OpIsNil      Op = "isnil"
	OpNotNil     Op = "notnil"
	OpAnd        Op = "and"
	OpOr         Op = "or"
	OpNot        Op = "not"
)

type Option

type Option[T any] struct {
	// contains filtered or unexported fields
}

Option is a value that may be absent. The zero Option is None.

func FromPtr

func FromPtr[T any](p *T) Option[T]

FromPtr is None for a nil pointer and Some(*p) otherwise.

func MapOption

func MapOption[T, U any](o Option[T], f func(T) U) Option[U]

MapOption applies f to a present value.

func None

func None[T any]() Option[T]

None is an absent value. Vuka code writes plain None; the transpiler fills in T from where the value goes.

func Some

func Some[T any](v T) Option[T]

Some is a present value.

func (Option[T]) Get

func (o Option[T]) Get() (T, bool)

Get is Go's comma-ok form: v, ok := o.Get().

func (Option[T]) IsNone

func (o Option[T]) IsNone() bool

func (Option[T]) IsSome

func (o Option[T]) IsSome() bool

func (Option[T]) String

func (o Option[T]) String() string

func (Option[T]) Unwrap

func (o Option[T]) Unwrap() T

Unwrap is the value; it panics when o is None.

func (Option[T]) UnwrapOr

func (o Option[T]) UnwrapOr(def T) T

UnwrapOr is the value, or def when o is None.

func (Option[T]) Value

func (o Option[T]) Value() T

Value is the value, or T's zero value when o is None.

type Order added in v0.7.0

type Order[T any] struct {
	Path FieldPath
	Desc bool
	// contains filtered or unexported fields
}

Order is an ordering of Ts by a field: Post.Views.Desc().

func (Order[T]) Compare added in v0.7.0

func (o Order[T]) Compare(a, b T) int

Compare orders a and b by o: negative when a comes first. A value whose field can't be reached (a nil pointer or relation on the way) comes first.

func (Order[T]) String added in v0.7.0

func (o Order[T]) String() string

type OrderedRef added in v0.7.0

type OrderedRef[T any, V cmp.Ordered] struct{ Ref[T, V] }

OrderedRef is a reference to a number field (or any cmp.Ordered type).

func OrderedRefOf added in v0.7.0

func OrderedRefOf[T any, V cmp.Ordered](index [][]int, _ func(*T)) OrderedRef[T, V]

func OrderedRefTo added in v1.0.0

func OrderedRefTo[T any, V cmp.Ordered](field func(*T) *V) OrderedRef[T, V]

func (OrderedRef[T, V]) Asc added in v0.7.0

func (r OrderedRef[T, V]) Asc() Order[T]

func (OrderedRef[T, V]) Desc added in v0.7.0

func (r OrderedRef[T, V]) Desc() Order[T]

func (OrderedRef[T, V]) Ge added in v0.7.0

func (r OrderedRef[T, V]) Ge(v V) Pred[T]

Ge is the predicate field >= v.

func (OrderedRef[T, V]) Gt added in v0.7.0

func (r OrderedRef[T, V]) Gt(v V) Pred[T]

Gt is the predicate field > v.

func (OrderedRef[T, V]) Le added in v0.7.0

func (r OrderedRef[T, V]) Le(v V) Pred[T]

Le is the predicate field <= v.

func (OrderedRef[T, V]) Lt added in v0.7.0

func (r OrderedRef[T, V]) Lt(v V) Pred[T]

Lt is the predicate field < v.

type Param added in v0.6.0

type Param struct {
	Name  string
	Type  reflect.Type
	Attrs []any
}

Param is a parameter of a declared function: its name as written ("" when unnamed), type, and the typed attributes written before it:

func Show(@Path("pet_id") id int)

func (Param) Attr added in v0.10.0

func (p Param) Attr(ptr any) bool

Attr fills ptr with the parameter's typed attribute of ptr's element type, reporting whether there is one: var p Path; param.Attr(&p).

type Pred added in v0.7.0

type Pred[T any] struct {
	Op    Op
	Path  FieldPath // the field tested; zero for and, or and not
	Value any       // the operand: a V, a []V for in; nil for isnil, notnil and the combinations
	Preds []Pred[T] // the operands of and, or and not
	// contains filtered or unexported fields
}

Pred is a condition on a T, built from field references — Post.Views.Gt(100), vuka.Or(…) — and kept as data, so a query builder can translate it (Op, the field's Path and attributes, the Value) or Match can test it in memory. Being typed by T, a Pred[User] can't be passed where a Pred[Post] is wanted.

func And added in v0.7.0

func And[T any](ps ...Pred[T]) Pred[T]

And holds when every p does.

func Not added in v0.7.0

func Not[T any](p Pred[T]) Pred[T]

Not holds when p doesn't.

func Or added in v0.7.0

func Or[T any](ps ...Pred[T]) Pred[T]

Or holds when any p does.

func (Pred[T]) Match added in v0.7.0

func (p Pred[T]) Match(t T) bool

Match tests p on t. A comparison fails when a nil pointer or relation is on the way to its field; IsNil holds.

func (Pred[T]) String added in v0.7.0

func (p Pred[T]) String() string

String writes p readably: Author.Name = "ada", (Views > 100 OR Title contains "go").

type Ref added in v0.7.0

type Ref[T, V any] struct {
	// contains filtered or unexported fields
}

Ref is a field reference: Post.Title in Vuka source, a typed handle on the Title field of Post, of type V. Through pointer, struct and Related fields it reaches further: Post.Author.Name. Its methods build predicates and orderings over T, or read the field.

Vuka picks the most capable kind for the field's type: StringRef for strings, OrderedRef for numbers, CompareRef for types with a Compare method (time.Time), NullableRef for pointers, slices, maps, interfaces and Options, and Ref for the rest.

func RefOf deprecated added in v0.7.0

func RefOf[T, V any](index [][]int, _ func(*T)) Ref[T, V]

RefOf, OrderedRefOf, StringRefOf, CompareRefOf and NullableRefOf make references from index paths. The function is never called: it is there so the compiler and the editor see the fields the reference names.

Deprecated: use RefTo and its kinds, which name the field by address; code generated by older versions of the vuka command calls these.

func RefTo added in v1.0.0

func RefTo[T, V any](field func(*T) *V) Ref[T, V]

RefTo is a reference to the field whose address field returns, the way a field reference is written in Go, Post.Title in Vuka source:

title := vuka.StringRefTo(func(p *Post) *string { return &p.Title })
city := vuka.StringRefTo(func(p *Post) *string { return &p.Home.City })
name := vuka.StringRefTo(func(p *Post) *string { return &p.Author.Related().Name })

The path goes through embedded structs, pointers and Related values. The compiler checks the fields; field runs once per instantiation, on a value of T made for it (nil pointers filled in), and must only select fields. OrderedRefTo, StringRefTo, CompareRefTo and NullableRefTo make the other kinds (see Ref).

func (Ref[T, V]) Asc added in v0.7.0

func (r Ref[T, V]) Asc() Order[T]

Asc orders by the field, smallest first.

func (Ref[T, V]) Attr added in v0.7.0

func (r Ref[T, V]) Attr(ptr any) bool

Attr fills ptr with the field's typed attribute of ptr's element type.

func (Ref[T, V]) Attrs added in v0.7.0

func (r Ref[T, V]) Attrs() []any

Attrs are the typed attributes of the field referred to.

func (Ref[T, V]) Desc added in v0.7.0

func (r Ref[T, V]) Desc() Order[T]

Desc orders by the field, largest first.

func (Ref[T, V]) Eq added in v0.7.0

func (r Ref[T, V]) Eq(v V) Pred[T]

Eq is the predicate field == v.

func (Ref[T, V]) FieldPath added in v0.7.0

func (r Ref[T, V]) FieldPath() FieldPath

FieldPath is where the reference leads.

func (Ref[T, V]) Get added in v0.7.0

func (r Ref[T, V]) Get(t T) V

Get is the field's value in t, or V's zero value when a nil pointer or relation is on the way.

func (Ref[T, V]) In added in v0.7.0

func (r Ref[T, V]) In(vs ...V) Pred[T]

In is the predicate that the field equals one of vs.

func (Ref[T, V]) Lookup added in v0.7.0

func (r Ref[T, V]) Lookup(t T) (V, bool)

Lookup is the field's value in t; false when a nil pointer or relation is on the way.

func (Ref[T, V]) Name added in v0.7.0

func (r Ref[T, V]) Name() string

Name is the path as written, dotted: "Author.Name".

func (Ref[T, V]) Ne added in v0.7.0

func (r Ref[T, V]) Ne(v V) Pred[T]

Ne is the predicate field != v.

func (Ref[T, V]) Path added in v0.7.0

func (r Ref[T, V]) Path() []string

Path is the fields as written: ["Author", "Name"].

type Related[T any] interface{ Related() *T }

Related is implemented by a field type that refers to a T held elsewhere, such as a foreign key. A field reference continues through it into T's fields: with Author of a type implementing Related[User], Post.Author.Name is a Ref[Post, string]. Related returns nil when there is no T.

type Result

type Result[T any] struct {
	// contains filtered or unexported fields
}

Result is a value or an error. It is Ok when it holds no error; the zero Result is Ok with T's zero value.

func AndThen

func AndThen[T, U any](r Result[T], f func(T) Result[U]) Result[U]

AndThen chains a step that can fail.

func Err

func Err[T any](err error) Result[T]

Err is a failed Result. err must not be nil.

func Map

func Map[T, U any](r Result[T], f func(T) U) Result[U]

Map applies f to an Ok value.

func Of

func Of[T any](v T, err error) Result[T]

Of turns Go's (T, error) into a Result: vuka.Of(os.ReadFile(name)).

func Ok

func Ok[T any](v T) Result[T]

Ok is a successful Result.

func (Result[T]) Err

func (r Result[T]) Err() error

Err is the error, or nil when r succeeded.

func (Result[T]) Get

func (r Result[T]) Get() (T, error)

Get turns r back into Go's (T, error).

func (Result[T]) IsErr

func (r Result[T]) IsErr() bool

func (Result[T]) IsOk

func (r Result[T]) IsOk() bool

func (Result[T]) String

func (r Result[T]) String() string

func (Result[T]) Unwrap

func (r Result[T]) Unwrap() T

Unwrap is the value; it panics when r failed.

func (Result[T]) UnwrapOr

func (r Result[T]) UnwrapOr(def T) T

UnwrapOr is the value, or def when r failed.

func (Result[T]) Value

func (r Result[T]) Value() T

Value is the value, or T's zero value when r failed.

type Static added in v0.2.0

type Static[V any] struct {
	V V
}

Static is the storage of a static field of a generic type: one per instantiation, so Model[User] and Model[Order] each have their own.

func StaticOf added in v0.2.0

func StaticOf[K, V any](s *Statics, init func() V) *Static[V]

StaticOf returns the static field of the instantiated type K, built by init on first use: a package-level value per instantiation, which Go has no variable for. Vuka's static of a generic type, static Objects = &Store[Self]{} in Model[Self], is

var modelObjectsStatics vuka.Statics

func ModelObjects[Self any]() *vuka.Static[*Store[Self]] {
	return vuka.StaticOf[Model[Self]](&modelObjectsStatics, func() *Store[Self] { return &Store[Self]{} })
}

type Statics added in v0.2.0

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

Statics holds one generic static field's instantiations.

type StringRef added in v0.7.0

type StringRef[T any, V ~string] struct{ OrderedRef[T, V] }

StringRef is a reference to a string field.

func StringRefOf added in v0.7.0

func StringRefOf[T any, V ~string](index [][]int, _ func(*T)) StringRef[T, V]

func StringRefTo added in v1.0.0

func StringRefTo[T any, V ~string](field func(*T) *V) StringRef[T, V]

func (StringRef[T, V]) Contains added in v0.7.0

func (r StringRef[T, V]) Contains(s V) Pred[T]

Contains is the predicate that the field contains s.

func (StringRef[T, V]) EndsWith added in v0.7.0

func (r StringRef[T, V]) EndsWith(s V) Pred[T]

EndsWith is the predicate that the field ends with s.

func (StringRef[T, V]) StartsWith added in v0.7.0

func (r StringRef[T, V]) StartsWith(s V) Pred[T]

StartsWith is the predicate that the field starts with s.

type Targets added in v0.10.0

type Targets uint16

Targets restricts where an attribute type may be written, as Java's @Target does. Written on the type, it makes any other use a compile error at the attribute:

@vuka.Targets(vuka.OnField)
type Char struct{ Max int }

Go code declares the same with a method whose result's length is the targets: func (Char) vukaTargets() [vuka.OnField]struct{} { return {} }.

const (
	OnFunc   Targets = 1 << iota // a function declaration
	OnMethod                     // a method declaration
	OnType                       // a type declaration
	OnField                      // a struct field
	OnParam                      // a function's or method's parameter
	OnVar                        // a var or const declaration
)

type Type added in v0.2.0

type Type struct {
	Name    string // "main.User"
	Reflect reflect.Type
	Attrs   []any   // the declaration's typed attributes
	New     any     // the constructor, for a struct; nil otherwise
	Fields  []Field // the struct's fields
}

Type describes a decorated type, for a type decorator:

func Model(t *vuka.Type) { registry[t.Name] = t.Reflect }

For a struct, New is a constructor taking each dependency field as a parameter (or the type's own static New, when it declares one), which is the shape dependency-injection containers take:

func Component(t *vuka.Type) { providers = append(providers, t.New) }

func TypeFor added in v1.0.0

func TypeFor[T any](ctor any, attrs ...any) *Type

TypeFor describes T for its type decorators, which are called with it:

component(vuka.TypeFor[UserService](NewUserService))

ctor is T's constructor (NewUserService), nil when it has none; attrs are its typed attributes, a Bundle's own included (its other decorators are not). Name is T as reflect writes it ("main.UserService").

func TypeOf deprecated added in v0.2.0

func TypeOf[T any](name string, attrs ...any) *Type

TypeOf describes T for its decorators.

Deprecated: use TypeFor; code generated by older versions of the vuka command calls TypeOf.

func TypeWith deprecated added in v0.3.0

func TypeWith[T any](name string, ctor any, attrs ...any) *Type

TypeWith describes a struct T with its constructor.

Deprecated: use TypeFor; code generated by older versions of the vuka command calls TypeWith.

func (*Type) Attr added in v0.2.0

func (t *Type) Attr(ptr any) bool

Attr fills ptr with the type's typed attribute of ptr's element type.

Directories

Path Synopsis
cmd
vuka module
vukavet module
Package diag is the shape of every diagnostic the vuka toolchain reports: the transpiler, vuka vet, the editor and the libraries' boot-time checks.
Package diag is the shape of every diagnostic the vuka toolchain reports: the transpiler, vuka vet, the editor and the libraries' boot-time checks.
Package docs holds the diagnostic catalogue: docs/errors/<code>.md, one page per code, rendered by the docs site and printed by `vuka explain`.
Package docs holds the diagnostic catalogue: docs/errors/<code>.md, one page per code, rendered by the docs site and printed by `vuka explain`.
internal
format
Package format formats Vuka source: the Go in it exactly as gofmt does, and its JSX the way Prettier lays out markup, without changing what it renders.
Package format formats Vuka source: the Go in it exactly as gofmt does, and its JSX the way Prettier lays out markup, without changing what it renders.
load
Package load finds Vuka packages in a module and supplies what transpiling them needs from the go command: build-context file selection, export data for imports, and the overlay that puts generated files in front of the compiler.
Package load finds Vuka packages in a module and supplies what transpiling them needs from the go command: build-context file selection, export data for imports, and the overlay that puts generated files in front of the compiler.
tsprops
Package tsprops reads the props a client component declares — a Vue SFC's defineProps/defineModel/defineEmits, a React component's props parameter, a Svelte component's $props(), a vanilla island's mount(el, props, ctx) — from its source, without Node: a small reader of the TypeScript types people write for props.
Package tsprops reads the props a client component declares — a Vue SFC's defineProps/defineModel/defineEmits, a React component's props parameter, a Svelte component's $props(), a vanilla island's mount(el, props, ctx) — from its source, without Node: a small reader of the TypeScript types people write for props.
Package transpile turns Vuka source into Go.
Package transpile turns Vuka source into Go.

Jump to

Keyboard shortcuts

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