value

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 18 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package value defines Ant's run-time values (section 12): their kinds, the tags of named types, records, tagged primitives, arrays, maps, functions, and sync objects, together with equality, hashing, rendering, arithmetic, and conversions.

A Value is a Go interface value holding one of: the ten numeric Go types int8 … uint64, float32, float64; bool; string; the sentinels Null and Void; *Array; *Map; *Set; *Record; *Tagged; a Callable (functions, defined by the interpreter, and *Constructor); *Tag; or a sync object.

Every slot that two goroutines can reach, a record field, an array element, a module variable, or a captured local, is a Slot: one machine word, an atomic pointer to an immutable cell. That is what makes a data race memory-safe (section 9).

Index

Constants

View Source
const HtmlInvalidURL = "about:invalid#ant"

HtmlInvalidURL replaces a URL whose scheme is not safe.

Variables

View Source
var (
	// HtmlVoid are the void elements, written self-closing and rendered without an end tag.
	HtmlVoid = set("area base br col embed hr img input link meta source track wbr")
	// HtmlRawText are the elements whose content is literal text, rendered unescaped.
	HtmlRawText = set("script style")
	// HtmlTextOnly are the elements that hold text only, outside <svg> and <math>.
	HtmlTextOnly = set("title textarea")
	// HtmlObsolete are the elements that are syntax errors.
	HtmlObsolete = set("xmp plaintext noembed noframes")
	// HtmlBoolean are the boolean attributes, where true gives the empty value and false leaves the
	// attribute out.
	HtmlBoolean = set(`allowfullscreen async autofocus autoplay checked controls default defer disabled
		formnovalidate hidden inert ismap itemscope loop multiple muted nomodule novalidate open
		playsinline readonly required reversed selected`)
	// HtmlURL are the URL attributes, whose interpolated value is checked for its scheme.
	HtmlURL = set(`action archive background cite classid codebase data formaction href icon longdesc
		manifest poster profile src usemap xlink:href`)
	// HtmlSrcset are the attributes that hold a list of URLs.
	HtmlSrcset = set("srcset imagesrcset")
)
View Source
var (
	ErrCancelled = errors.New("cancelled")
	ErrTimeout   = errors.New("timeout")
	ErrInterrupt = errors.New("interrupt")
)

The reasons a Context is done, as context causes; Reason names them.

View Source
var (
	OkTag      = NewTag("Ok", RecordTag, []string{"value"})
	ErrTag     = NewTag("Err", RecordTag, []string{"error"})
	ErrorTag   = NewTag("Error", RecordTag, []string{"message"})
	EntryTag   = NewTag("Entry", RecordTag, []string{"key", "value"})
	IndexedTag = NewTag("Indexed", RecordTag, []string{"index", "value"})
)

The prelude's record types (section 11).

View Source
var EmptyHtml = &Html{}

EmptyHtml is the empty Html, the value of <></>.

View Source
var ErrClosed = errors.New("the channel is closed")

ErrClosed is the error of a send on a closed channel, or of a second close.

View Source
var ErrOnceLeft = errors.New("the function of the Once was left without returning a value")

ErrOnceLeft is what later calls of a Once get when its function was left without a value and without a panic: by a return unwinding through it from a for body, or by Test.skip.

View Source
var ErrTicker = errors.New("a ticker's channel only receives")

ErrTicker is the error of a send on a ticker's channel, or of closing one: only the ticker sends, and the channel is never closed, as Go's ticker channel is receive-only.

View Source
var RegexPatternTag = NewTag("Regex.Pattern", RegexTag, nil)

RegexPatternTag is the tag of Regex.Pattern, which is tests.

Functions

func Compare

func Compare(op string, a, b Value) (bool, error)

Compare applies < <= > >=.

func Deep

func Deep(depth int) bool

Deep reports whether a walk of a container depth levels down continues on a fresh goroutine, which it does every stackChunk levels, so that ==, rendering and Json.stringify of a value nested a million deep need no single Go stack deeper than the Go runtime allows (section 9: the interpreter never crashes).

func Describe

func Describe(v Value) string

Describe names a value's kind, with its tag for a tagged value or a record.

func Equal

func Equal(a, b Value) bool

Equal is == (section 12): structural, never panics, and finite on cyclic values. It never shortcuts on identity, so a container holding NaN is unequal even to itself.

func FormatFloat

func FormatFloat(f float64, bits int) string

FormatFloat renders a float as section 11 says: the shortest decimal that reads back to the same value, with .0 when integral, and in JavaScript's exponent form, 1e+21 or 1.5e-7, when the magnitude is at or above 1e21 or below 1e-6. bits is 32 for a float32.

func Hash

func Hash(v Value) uint64

Hash agrees with Equal: equal values hash alike. It walks a bounded prefix of a container, so it terminates on cyclic values.

func HtmlAttrChar

func HtmlAttrChar(c byte) bool

HtmlAttrChar reports whether c may continue an attribute name.

func HtmlAttrName

func HtmlAttrName(s string) bool

HtmlAttrName reports whether s is an attribute name: an ASCII letter or _, then ASCII letters, digits, -, _, :, and ..

func HtmlCheckSrcset

func HtmlCheckSrcset(v string) string

HtmlCheckSrcset checks each comma-separated candidate of a srcset value: its URL, up to the first white space, by HtmlCheckURL, keeping the descriptors and the separators as written.

func HtmlCheckURL

func HtmlCheckURL(u string) string

HtmlCheckURL returns u when it is relative or its scheme is http, https, mailto, or tel, and HtmlInvalidURL otherwise. It reads u as the URL standard does: leading and trailing U+0000 to U+0020 removed, and every tab and line break removed.

func HtmlCodeAttr

func HtmlCodeAttr(lower string) bool

HtmlCodeAttr reports whether the attribute name, in lower case, runs code, so that it takes only literal text: every name that starts with on, style, and srcdoc.

func NormalizeRegexSource

func NormalizeRegexSource(source string) string

NormalizeRegexSource removes the backslash before a / in source, since RE2 reads \/ and / alike and a literal needs the backslash only to keep the / from ending it; writes a line break, escaped or not, as \n or \r and an empty source as (?:), which RE2 reads the same, so that a pattern renders as a literal that reads back to a pattern == to it. Every other escape, \\ included, is kept as written, and so is the text of a \Q...\E span (copySpan).

func OnFreshStack

func OnFreshStack(f func())

OnFreshStack runs f on a fresh goroutine and waits for it. A panic in f is raised again in the caller. Callers build f only once Deep says so, which keeps the closure off the common path. Anything f shares with the caller, such as the set of enclosing containers that ends a walk of a cycle, can no longer live on the stack, so hot walks take that set from a sync.Pool.

func ReasonOf

func ReasonOf(ctx context.Context) string

ReasonOf names why a Go context is done, as Reason does, for the run's own context too. A program's timeout carries ErrTimeout as its cause, so Go's own deadline error can only be the host's context expiring, which is the host ending the run: cancelled, as section 9 says.

func RegexFlags

func RegexFlags(flags string) (string, error)

RegexFlags validates a flag string and returns it sorted: each of i, m and s at most once, in that order. The error for one of JavaScript's other flags names the Ant way.

func RegexLiteral

func RegexLiteral(source, flags string) string

RegexLiteral writes a source and flags as a literal that reads back to them: every / of the source escaped, a line break as \n or \r, and an empty source as (?:), as JavaScript has it. Inside a \Q...\E span, where an escape would stand for itself, the span is closed before such a character and reopened after it: \E\/\Q, \E\n\Q, or \E\r\Q, which copySpan reads back.

func Render

func Render(v Value) string

Render is String.from (section 11): the rendering print, println and string interpolation use.

func RenderHtml

func RenderHtml(h *Html) string

RenderHtml is String.from of an Html value: its markup.

func RenderQuoted

func RenderQuoted(v Value) string

RenderQuoted renders v as it would appear inside a container: strings quoted with escapes.

func Text

func Text(s string) string

Text returns s as a string Ant can hold: s itself when it is UTF-8, and otherwise s with each maximal subpart of an ill-formed sequence replaced by U+FFFD, the practice Unicode recommends in chapter 3 and the WHATWG Encoding standard follows (section 11, String). Every text that reaches a program from outside it passes through here.

Types

type Ancestors

type Ancestors map[any]bool

Ancestors holds the containers a walk is inside, the enclosing ones of the value at hand, as a set, so that a deep value is walked in linear time and a cyclic one ends: rendering writes ... where Enter fails, and Json.stringify panics.

func (Ancestors) Enter

func (a Ancestors) Enter(v any) bool

Enter adds v, or reports false when v is already being walked: a cycle.

func (Ancestors) Leave

func (a Ancestors) Leave(v any)

Leave removes v once its walk is done.

type Array

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

Array is a dense, growable sequence. Reads and element stores go through an immutable header behind an atomic pointer; push and pop take the mutex and publish a new header. A concurrent push or pop leaves a reader the state before or after it, never a corrupted structure.

func NewArray

func NewArray(elems []Value) *Array

NewArray creates an array holding elems.

func (*Array) Get

func (a *Array) Get(i int) (Value, bool)

Get reads the element at i, or reports false when i is out of range.

func (*Array) Insert

func (a *Array) Insert(i int, v Value) bool

Insert stores v at i and shifts the elements from i on up by one, or reports false when i is outside 0 ..= Len(). The elements go into a fresh slice, so a reader of the old header sees the array as it was.

func (*Array) Len

func (a *Array) Len() int

Len is the current length.

func (*Array) Pop

func (a *Array) Pop() (Value, bool)

Pop removes and returns the last element, or reports false when the array is empty.

func (*Array) Push

func (a *Array) Push(v Value)

Push appends v.

func (*Array) Remove

func (a *Array) Remove(i int) (Value, bool)

Remove removes and returns the element at i, shifting the rest down by one, or reports false when i is out of range. As Insert, it publishes a fresh slice.

func (*Array) Set

func (a *Array) Set(i int, v Value) bool

Set stores v at i, or reports false when i is out of range.

func (*Array) Values

func (a *Array) Values() []Value

Values copies the elements out, from one consistent header.

type Atomic

type Atomic struct {
	Slot Slot
}

Atomic is a shared slot whose operations form one total order.

func NewAtomic

func NewAtomic(v Value) *Atomic

NewAtomic creates an Atomic holding v.

func (*Atomic) SyncName

func (a *Atomic) SyncName() string

SyncName returns "Atomic".

type Bytes

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

Bytes is a mutable, growable sequence of bytes, shared by reference as an array is: Bytes of section 11. The storage sits behind an atomic pointer and the length in an atomic word, so that a push into spare capacity publishes nothing but the new length. Growth copies into larger storage and publishes it before the length passes the old capacity, so a reader that loads the length and then the storage always finds the storage covering that length. Functions that change the length take the mutex; reads and stores of a byte take nothing.

func CopyBytes added in v0.2.0

func CopyBytes(b []byte) *Bytes

CopyBytes makes Bytes holding a copy of b.

func NewBytes added in v0.2.0

func NewBytes(b []byte) *Bytes

NewBytes makes Bytes holding b, adopting b's array: the caller gives it up.

func (*Bytes) Append added in v0.2.0

func (x *Bytes) Append(src []byte)

Append appends src. src may be a view of x itself: growth leaves it on the old storage, and without growth it ends where the new bytes begin.

func (*Bytes) Get added in v0.2.0

func (x *Bytes) Get(i int) (byte, bool)

Get reads the byte at i, or reports false when i is out of range.

func (*Bytes) Len added in v0.2.0

func (x *Bytes) Len() int

Len is the current length.

func (*Bytes) Pop added in v0.2.0

func (x *Bytes) Pop() (byte, bool)

Pop removes and returns the last byte, or reports false when x is empty.

func (*Bytes) Push added in v0.2.0

func (x *Bytes) Push(c byte)

Push appends c.

func (*Bytes) Set added in v0.2.0

func (x *Bytes) Set(i int, c byte) bool

Set stores c at i, or reports false when i is out of range.

func (*Bytes) Snapshot added in v0.2.0

func (x *Bytes) Snapshot() []byte

Snapshot is a copy of the live bytes.

func (*Bytes) Truncate added in v0.2.0

func (x *Bytes) Truncate(n int) bool

Truncate keeps the first n bytes, or reports false when n is outside 0 ..= length. The storage stays for reuse; growth overwrites each byte it makes visible again.

func (*Bytes) View added in v0.2.0

func (x *Bytes) View() []byte

View is the live bytes, sharing the storage. A caller only reads it and does not keep it past the call it serves; a concurrent change is a data race, which leaves it some bytes that were stored.

type Callable

type Callable interface {
	FuncName() string
}

Callable is implemented by every function value. The interpreter defines the concrete function types; the value package needs only the name.

type Chan

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

Chan is a Channel[T] of section 9: a Go channel of values beside a closed signal, a second channel closed under the mutex. The channel of values is never closed, so a sender blocked in it is ended by the signal, not by the runtime's panic for a send on a closed channel, which the race detector would report as a race; a receiver that sees the signal drains what is buffered before it answers that the channel is closed. The orderings of section 9 are the Go channels' own.

A ticker's channel carries the ticker's context, and a tick taken once that context is done is discarded, as Go's Ticker.Stop discards a stale one: a receive that begins after the context ends gets no tick, whichever way it ended, since the ticker's own goroutine can always have one in flight.

func NewChan

func NewChan(capacity int) *Chan

NewChan creates a channel; a capacity of zero is a rendezvous.

func NewTickerChan

func NewTickerChan(ctx context.Context) *Chan

NewTickerChan creates a ticker's channel, holding one tick, that stops with ctx.

func (*Chan) Close

func (c *Chan) Close() error

Close closes the channel; ErrClosed when it is closed already.

func (*Chan) Closed

func (c *Chan) Closed() <-chan struct{}

Closed is the signal, closed once Close has been called, for a select over several.

func (*Chan) IsClosed

func (c *Chan) IsClosed() bool

IsClosed reports whether Close has been called.

func (*Chan) IsTicker

func (c *Chan) IsTicker() bool

IsTicker reports whether the channel is a ticker's.

func (*Chan) Len

func (c *Chan) Len() int

Len is the number of values buffered now; none for a stopped ticker, whose tick is stale.

func (*Chan) Raw

func (c *Chan) Raw() chan Value

Raw is the Go channel of values, for a select over several; it is never closed.

func (*Chan) Receive

func (c *Chan) Receive(ctx context.Context) (v Value, ok, gaveUp bool)

Receive takes the next value. ok is false when the channel is closed and drained, and gaveUp is true when ctx ended first, or was done already. A stale tick is discarded and the wait goes on.

func (*Chan) Send

func (c *Chan) Send(ctx context.Context, v Value) (sent bool, err error)

Send delivers v to a receiver or buffers it, unless ctx is done first, which reports false; a context done already gives up at once. It is ErrClosed on a closed channel, including one closed while the send waited.

func (*Chan) Stopped

func (c *Chan) Stopped() bool

Stopped reports whether the channel is a ticker's whose context is done, so a tick taken from it is stale.

func (*Chan) SyncName

func (c *Chan) SyncName() string

SyncName returns "Channel".

type Cond

type Cond struct {
	M *Mutex
	// contains filtered or unexported fields
}

Cond is a condition variable over a Mutex.

func NewCond

func NewCond(m *Mutex) *Cond

NewCond creates a Cond over m.

func (*Cond) Broadcast

func (c *Cond) Broadcast()

Broadcast wakes every waiter.

func (*Cond) Signal

func (c *Cond) Signal()

Signal wakes one waiter.

func (*Cond) SyncName

func (c *Cond) SyncName() string

SyncName returns "Cond".

func (*Cond) Wait

func (c *Cond) Wait() error

Wait releases the mutex, waits for a signal, and reacquires the mutex. It is an error when the mutex is not locked.

type Constructor

type Constructor struct {
	Tag *Tag
}

Constructor is the function value a named primitive type binds: it builds Tagged values and carries the type's functions as fields.

func (*Constructor) FuncName

func (c *Constructor) FuncName() string

FuncName returns the type's name.

type Context

type Context struct {
	Ctx context.Context
	// contains filtered or unexported fields
}

Context is a Context of section 9: done once, by a call, a deadline or its parent, with a reason. It wraps a Go context whose cause is the reason, so every blocking call selects on Ctx.Done and reads Reason.

func NewContext

func NewContext(parent context.Context, timeout time.Duration) *Context

NewContext makes a child of parent that is done when parent is, when timeout passes if it is positive, or when Cancel is called. The timeout layer sits on the parent and the cancel layer on it, so that the deadline passing cancels both and unregisters both from the parent; the other way round the outer layer would stay in the parent until Cancel, which a program that lets its timeouts expire never calls.

func (*Context) Cancel

func (c *Context) Cancel(cause error)

Cancel makes the context done with cause, unless it is done already.

func (*Context) Done

func (c *Context) Done() bool

Done reports whether the context is done.

func (*Context) Reason

func (c *Context) Reason() string

Reason names why the context is done, or "" while it runs: cancelled, timeout or interrupt, a parent's reason, and cancelled for the host ending the run.

func (*Context) SyncName

func (c *Context) SyncName() string

SyncName returns "Context".

type Declaration

type Declaration struct {
	Key  any
	Name string
}

Declaration is a named type's declaration as a value, Reflect.Decl (section 11, Reflect). Key identifies the declaration, so two are == when they come from one declaration whatever the type arguments, and Name is the declared name it renders as.

type Html

type Html struct {
	Nodes []HtmlNode
}

Html is the value of an HTML expression: Html of section 11, an immutable list of nodes in normal form, where no two text nodes are adjacent and no text node is empty. Since a value is built from finished values and never changed, it holds no cycle.

func UnsafeHtml

func UnsafeHtml(s string) *Html

UnsafeHtml is Html.unsafe: s as one raw node, or the empty Html for an empty s.

type HtmlAttr

type HtmlAttr struct {
	Name, Value string
}

HtmlAttr is an attribute that is present; a boolean attribute that is on has the empty value.

type HtmlBuilder

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

HtmlBuilder collects nodes in normal form.

func (*HtmlBuilder) Html

func (b *HtmlBuilder) Html() *Html

Html returns the value built.

func (*HtmlBuilder) Node

func (b *HtmlBuilder) Node(n HtmlNode)

Node appends one node, joining a text node to one before it.

func (*HtmlBuilder) Splice

func (b *HtmlBuilder) Splice(h *Html)

Splice appends the nodes of h.

func (*HtmlBuilder) Text

func (b *HtmlBuilder) Text(s string)

Text appends a text node, joining it to a text node before it; an empty one adds nothing.

type HtmlNode

type HtmlNode struct {
	Kind     HtmlNodeKind
	Name     string
	Attrs    []HtmlAttr
	Children *Html
	Text     string
}

HtmlNode is an element, a text node, or a raw node. An element has a Name, its Attrs in their final order, and Children; a text node's decoded text and a raw node's markup are in Text.

type HtmlNodeKind

type HtmlNodeKind uint8

HtmlNodeKind is the kind of an Html node.

const (
	HtmlElement HtmlNodeKind = iota
	HtmlText
	HtmlRaw
)

type KeyValue

type KeyValue struct {
	Key, Value Value
}

KeyValue is one entry of a map snapshot.

type Kind

type Kind int

Kind classifies a value (section 12, Values).

const (
	KindInvalid Kind = iota
	KindInt8
	KindInt16
	KindInt32
	KindInt64
	KindUint8
	KindUint16
	KindUint32
	KindUint64
	KindFloat32
	KindFloat64
	KindBool
	KindString
	KindNull
	KindVoid
	KindArray
	KindMap
	KindSet
	KindRecord
	KindTagged
	KindFunc
	KindTag
	KindSync
	KindTime
	KindRegex
	KindBytes
	KindHtml
	KindType      // a type as a value (section 4, Types as values)
	KindDecl      // a type declaration as a value, Reflect.Decl
	KindReflected // a value with a type it belongs to, Reflect.Value
)

func KindByName

func KindByName(name string) (Kind, bool)

KindByName maps a prelude kind name, including int and byte, to its kind.

func KindOf

func KindOf(v Value) Kind

KindOf returns the kind of v.

func (Kind) Bits

func (k Kind) Bits() int

Bits is the width of an integer kind.

func (Kind) IsFloat

func (k Kind) IsFloat() bool

IsFloat reports whether k is a float kind.

func (Kind) IsInteger

func (k Kind) IsInteger() bool

IsInteger reports whether k is one of the eight integer kinds.

func (Kind) IsNumber

func (k Kind) IsNumber() bool

IsNumber reports whether k is one of the ten numeric kinds.

func (Kind) IsPrimitive

func (k Kind) IsPrimitive() bool

IsPrimitive reports whether k is one of the twelve primitive kinds a named type may wrap.

func (Kind) IsSigned

func (k Kind) IsSigned() bool

IsSigned reports whether k is a signed integer kind.

func (Kind) String

func (k Kind) String() string

type Map

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

Map is a hash map keyed by == that keeps insertion order (section 4). Reads hold its lock shared and mutations hold it exclusively. Entries carry a sequence number in insertion order, which a for loop uses as its cursor, so compaction never disturbs an iteration. Keys are hashed and compared with no lock held, since a key may contain the map itself and hashing or comparing it reads the map; ver counts the changes to the entries' positions, so a mutation can tell that the entry it found is still where it was.

func NewMap

func NewMap() *Map

NewMap creates an empty map.

func (*Map) Clone

func (m *Map) Clone() *Map

Clone is a new map with the entries of m, in its order.

func (*Map) Entries

func (m *Map) Entries() []KeyValue

Entries copies the entries out in insertion order.

func (*Map) Get

func (m *Map) Get(k Value) (Value, bool)

Get returns the value stored under k.

func (*Map) Has

func (m *Map) Has(k Value) bool

Has reports whether k is a key.

func (*Map) Keys

func (m *Map) Keys() []Value

Keys copies the keys out in insertion order.

func (*Map) Len

func (m *Map) Len() int

Len is the number of entries.

func (*Map) Next

func (m *Map) Next(after uint64) (key, value Value, seq uint64, ok bool)

Next returns the first live entry whose sequence number is above after, for iteration by insertion order while the map may change. The cursor to pass next time is the returned seq.

func (*Map) Remove

func (m *Map) Remove(k Value) (Value, bool)

Remove deletes the entry under k and returns its value.

func (*Map) Set

func (m *Map) Set(k, v Value)

Set inserts or replaces the value under k. A replaced entry keeps its position.

func (*Map) SetAll

func (m *Map) SetAll(n *Map)

SetAll sets each entry of n in m, in n's order: a key already in m keeps its position and takes n's value.

func (*Map) Values

func (m *Map) Values() []Value

Values copies the values out in insertion order.

type Mutex

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

Mutex is a mutual exclusion lock that any goroutine may unlock.

func NewMutex

func NewMutex() *Mutex

NewMutex creates an unlocked Mutex.

func (*Mutex) Lock

func (m *Mutex) Lock()

Lock blocks until the mutex is free, then takes it.

func (*Mutex) Locked

func (m *Mutex) Locked() bool

Locked reports whether the mutex is held.

func (*Mutex) SyncName

func (m *Mutex) SyncName() string

SyncName returns "Mutex".

func (*Mutex) TryLock

func (m *Mutex) TryLock() bool

TryLock takes the mutex if it is free and reports whether it did.

func (*Mutex) Unlock

func (m *Mutex) Unlock() error

Unlock releases the mutex; it is an error when the mutex is not locked.

type Once

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

Once runs one function once. If that function panics, every call, waiting or later, gets the same panic.

func NewOnce

func NewOnce() *Once

NewOnce creates a pending Once.

func (*Once) Do

func (o *Once) Do(f func() error) error

Do runs f the first time it is called; later and concurrent calls wait for that run and return the error it returned, which is how a panic in f is shared.

func (*Once) SyncName

func (o *Once) SyncName() string

SyncName returns "Once".

type Record

type Record struct {
	Tag *Tag
	// contains filtered or unexported fields
}

Record is a record value: a tag plus its fields in the tag's order. A module's scope is a record too.

func Entry

func Entry(k, v Value) *Record

Entry builds Entry{ key: k, value: v }.

func Err

func Err(e Value) *Record

Err builds Err{ error: e }.

func ErrorValue

func ErrorValue(msg string) *Record

ErrorValue builds Error{ message: msg }.

func Indexed

func Indexed(i int64, v Value) *Record

Indexed builds Indexed{ index: i, value: v }.

func NewRecord

func NewRecord(tag *Tag, fields []Value) *Record

NewRecord creates a record with the given field values, in the tag's order. A nil entry leaves the field uninitialized.

func Ok

func Ok(v Value) *Record

Ok builds Ok{ value: v }.

func (*Record) Field

func (r *Record) Field(name string) (Value, bool)

Field reads a field by name.

func (*Record) Get

func (r *Record) Get(i int) Value

Get reads the field at position i.

func (*Record) Len

func (r *Record) Len() int

Len is the number of fields.

func (*Record) Set

func (r *Record) Set(i int, v Value)

Set writes the field at position i.

func (*Record) SetField

func (r *Record) SetField(name string, v Value) bool

SetField writes a field by name and reports whether the record has it.

func (*Record) Slot

func (r *Record) Slot(i int) *Slot

Slot returns the field's slot, for sharing a module variable with its importers.

func (*Record) Values

func (r *Record) Values() []Value

Values copies the fields out, in order.

type Reflected

type Reflected struct {
	Type  TypeValue
	Value Value
}

Reflected is a value together with a type it belongs to, Reflect.Value (section 11, Reflect). It is immutable: the library makes a new one for each box. Two are == when their types and values are.

type Regex

type Regex struct {
	Source string         // normalized: no backslash before a /
	Flags  string         // sorted: some of i, m and s, in that order
	Re     *regexp.Regexp // compiled from (?flags)source
}

Regex is a compiled regular expression: a Regex.Pattern of section 11, built from a literal or by Regex.compile. It is immutable and compared by its normalized source and its sorted flags, so it serves as a map key, and its compiled form matches in time linear in the input.

func NewRegex

func NewRegex(source, flags string) (*Regex, error)

NewRegex compiles source with flags into a pattern. The source is normalized and the flags sorted, so a literal and Regex.compile build equal values from one expression. An error names the construct a JavaScript programmer will meet: lookaround, a backreference, or \u.

func (*Regex) String

func (r *Regex) String() string

String renders the pattern as a literal that reads back to it.

type RwMutex

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

RwMutex is a reader-writer lock. A writer waiting in WriteLock keeps new readers out, as in Go, so readers cannot starve it.

func NewRwMutex

func NewRwMutex() *RwMutex

NewRwMutex creates an unlocked RwMutex.

func (*RwMutex) ReadLock

func (m *RwMutex) ReadLock()

ReadLock takes one shared hold, waiting while a writer holds the lock or waits for it.

func (*RwMutex) ReadUnlock

func (m *RwMutex) ReadUnlock() error

ReadUnlock releases one shared hold.

func (*RwMutex) SyncName

func (m *RwMutex) SyncName() string

SyncName returns "RwMutex".

func (*RwMutex) WriteLock

func (m *RwMutex) WriteLock()

WriteLock takes the exclusive lock.

func (*RwMutex) WriteUnlock

func (m *RwMutex) WriteUnlock() error

WriteUnlock releases the exclusive lock.

type Set

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

Set is a hash set keyed by == that keeps insertion order (section 4): a map whose values are all void, so it shares the map's lock, hashing, and iteration cursor.

func NewSet

func NewSet() *Set

NewSet creates an empty set.

func (*Set) Add

func (s *Set) Add(x Value) bool

Add inserts x and reports whether it was new. A member already there keeps its position.

func (*Set) AddAll

func (s *Set) AddAll(t *Set)

AddAll adds each member of t to s, in t's order.

func (*Set) Clone

func (s *Set) Clone() *Set

Clone is a new set with the members of s, in its order.

func (*Set) Has

func (s *Set) Has(x Value) bool

Has reports whether x is a member.

func (*Set) Len

func (s *Set) Len() int

Len is the number of members.

func (*Set) Next

func (s *Set) Next(after uint64) (x Value, seq uint64, ok bool)

Next returns the first member whose sequence number is above after, as Map.Next does.

func (*Set) Remove

func (s *Set) Remove(x Value) bool

Remove deletes x and reports whether it was a member.

func (*Set) Values

func (s *Set) Values() []Value

Values copies the members out in insertion order.

type Slot

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

Slot is a one-word shared location holding a Value. A store publishes an immutable cell; a read copies the value out of the cell it finds. Racy stores and loads never tear.

func (*Slot) CompareAndSwap

func (s *Slot) CompareAndSwap(expected, v Value) bool

CompareAndSwap stores v when the slot holds a value equal (by ==) to expected, and reports whether it did. It is lock-free: every store publishes a fresh cell, so the cell pointer identifies the version the comparison saw.

func (*Slot) Load

func (s *Slot) Load() Value

Load returns the slot's value, or Uninitialized when nothing was stored.

func (*Slot) Modify

func (s *Slot) Modify(f func(old Value) (Value, error)) (Value, error)

Modify replaces the slot's value with f(old) atomically and returns the new value. f may be called more than once when stores race; when f returns an error nothing is stored.

func (*Slot) Store

func (s *Slot) Store(v Value)

Store sets the slot's value.

type Sync

type Sync interface {
	SyncName() string
}

Sync is implemented by the sync objects.

type Tag

type Tag struct {
	Name   string
	Kind   TagKind
	Fields []string
	Base   Kind // PrimitiveTag: the base kind
	// Defaults is what the interpreter fills an omitted field of a record literal from, set
	// before the tag is bound and opaque to this package; nil when no field declares a default.
	Defaults any
	// Body is the declaration the tag came from, with the scope it was declared in, which a
	// type expression resolves (section 4, Types as values). It is opaque to this package, and
	// nil for a tag the library made until the runtime attaches its prelude declaration.
	Body any
	// Fixed holds the fields of a module record bound by let, which no assignment may change;
	// nil for any other record.
	Fixed map[string]bool
	// contains filtered or unexported fields
}

Tag is the run-time identity of a named type: what a type declaration binds. A record tag lists its field names in declaration order. Every tag carries the functions declared on its type as fields (section 6).

func NewPrimitiveTag

func NewPrimitiveTag(name string, base Kind) *Tag

NewPrimitiveTag creates the tag of a named primitive type over base.

func NewTag

func NewTag(name string, kind TagKind, fields []string) *Tag

NewTag creates a tag. fields is used for record tags only.

func (*Tag) FieldIndex

func (t *Tag) FieldIndex(name string) (int, bool)

FieldIndex returns the position of a field of a record tag.

func (*Tag) Func

func (t *Tag) Func(name string) (Value, bool)

Func returns a function declared on the type.

func (*Tag) Funcs

func (t *Tag) Funcs() map[string]Value

Funcs lists the functions declared on the type.

func (*Tag) SetFunc

func (t *Tag) SetFunc(name string, fn Value)

SetFunc attaches a function declared on the type. It is called while loading, before any goroutine can read the tag.

type TagKind

type TagKind int

TagKind says what a type declaration bound its name to.

const (
	RecordTag    TagKind = iota // a record type: literals and is use it
	AliasTag                    // an alias: neither literals nor is accept it
	PrimitiveTag                // a named primitive type: its Constructor carries it
	SyncTag                     // Mutex and the other sync types: a namespace for their functions
	TimeTag                     // a time type of stdlib.md: is tests a time value's type by its name
	RegexTag                    // Regex.Pattern: is tests for a pattern
)

type Tagged

type Tagged struct {
	Tag     *Tag
	Payload Value
}

Tagged is a value of a named primitive type: a primitive payload carrying the type's tag.

type Time

type Time interface {
	TimeType() string // the name of its type's tag, such as "Time.Instant"
	Key() string      // a canonical form of the fields == compares
	String() string
}

Time is implemented by the time values of stdlib.md's Time namespace: immutable, compared by value, rendered as their RFC 9557 string or, for a zone, its identifier. Two time values are equal when they have the same type and the same key, which names the fields == compares.

type TypeValue

type TypeValue interface {
	EqualType(other TypeValue) bool
	HashType() uint64
	String() string
}

A TypeValue is a type as a value (section 4, Types as values), the value of a type expression type(T). The runtime implements it over the checker's types, which this package cannot name. Two are == when they denote the same type, and one renders as the type.

type Value

type Value = any

Value is any Ant value.

var Null Value = nullType{}

Null is the value null.

var Uninitialized Value = uninitType{}

Uninitialized marks a slot whose initializer has not run; reading it is a panic.

var Void Value = voidType{}

Void is the value void.

func Binary

func Binary(op string, a, b Value) (Value, error)

Binary applies an arithmetic operator: + - * / %.

func Convert

func Convert(to Kind, v Value) (Value, error)

Convert applies one of the twelve conversion functions (section 12). A tagged argument is unwrapped first.

func Neg

func Neg(a Value) (Value, error)

Neg is unary minus.

func TextIn

func TextIn(v Value) Value

TextIn returns v with Text applied to every string in it: v itself, the elements of arrays, the keys and values of maps, the members of sets, the fields of records, and the payloads of tagged primitives. Containers change in place, keeping their order; a map or a set whose keys become equal keeps the last. It is how a value a Go host hands to a program becomes one that holds only scalar values.

type WaitGroup

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

WaitGroup counts goroutines to wait for. A channel is closed when the counter reaches zero and replaced at the next add from zero, so a wait with a context is a select that leaks nothing when it gives up.

func NewWaitGroup

func NewWaitGroup() *WaitGroup

NewWaitGroup creates a WaitGroup at zero.

func (*WaitGroup) Add

func (w *WaitGroup) Add(n int64) error

Add changes the counter by n; an error when it would go negative.

func (*WaitGroup) Done

func (w *WaitGroup) Done() error

Done decrements the counter; an error when it is already zero.

func (*WaitGroup) SyncName

func (w *WaitGroup) SyncName() string

SyncName returns "WaitGroup".

func (*WaitGroup) Wait

func (w *WaitGroup) Wait()

Wait blocks until the counter is zero.

func (*WaitGroup) Zero

func (w *WaitGroup) Zero() <-chan struct{}

Zero returns a channel that is closed once the counter reaches zero. A counter at zero gives a closed channel.

Jump to

Keyboard shortcuts

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