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
- Variables
- func Compare(op string, a, b Value) (bool, error)
- func Deep(depth int) bool
- func Describe(v Value) string
- func Equal(a, b Value) bool
- func FormatFloat(f float64, bits int) string
- func Hash(v Value) uint64
- func HtmlAttrChar(c byte) bool
- func HtmlAttrName(s string) bool
- func HtmlCheckSrcset(v string) string
- func HtmlCheckURL(u string) string
- func HtmlCodeAttr(lower string) bool
- func NormalizeRegexSource(source string) string
- func OnFreshStack(f func())
- func ReasonOf(ctx context.Context) string
- func RegexFlags(flags string) (string, error)
- func RegexLiteral(source, flags string) string
- func Render(v Value) string
- func RenderHtml(h *Html) string
- func RenderQuoted(v Value) string
- func Text(s string) string
- type Ancestors
- type Array
- type Atomic
- type Bytes
- func (x *Bytes) Append(src []byte)
- func (x *Bytes) Get(i int) (byte, bool)
- func (x *Bytes) Len() int
- func (x *Bytes) Pop() (byte, bool)
- func (x *Bytes) Push(c byte)
- func (x *Bytes) Set(i int, c byte) bool
- func (x *Bytes) Snapshot() []byte
- func (x *Bytes) Truncate(n int) bool
- func (x *Bytes) View() []byte
- type Callable
- type Chan
- func (c *Chan) Close() error
- func (c *Chan) Closed() <-chan struct{}
- func (c *Chan) IsClosed() bool
- func (c *Chan) IsTicker() bool
- func (c *Chan) Len() int
- func (c *Chan) Raw() chan Value
- func (c *Chan) Receive(ctx context.Context) (v Value, ok, gaveUp bool)
- func (c *Chan) Send(ctx context.Context, v Value) (sent bool, err error)
- func (c *Chan) Stopped() bool
- func (c *Chan) SyncName() string
- type Cond
- type Constructor
- type Context
- type Declaration
- type Html
- type HtmlAttr
- type HtmlBuilder
- type HtmlNode
- type HtmlNodeKind
- type KeyValue
- type Kind
- type Map
- func (m *Map) Clone() *Map
- func (m *Map) Entries() []KeyValue
- func (m *Map) Get(k Value) (Value, bool)
- func (m *Map) Has(k Value) bool
- func (m *Map) Keys() []Value
- func (m *Map) Len() int
- func (m *Map) Next(after uint64) (key, value Value, seq uint64, ok bool)
- func (m *Map) Remove(k Value) (Value, bool)
- func (m *Map) Set(k, v Value)
- func (m *Map) SetAll(n *Map)
- func (m *Map) Values() []Value
- type Mutex
- type Once
- type Record
- type Reflected
- type Regex
- type RwMutex
- type Set
- type Slot
- type Sync
- type Tag
- type TagKind
- type Tagged
- type Time
- type TypeValue
- type Value
- type WaitGroup
Constants ¶
const HtmlInvalidURL = "about:invalid#ant"
HtmlInvalidURL replaces a URL whose scheme is not safe.
Variables ¶
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") )
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.
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).
var EmptyHtml = &Html{}
EmptyHtml is the empty Html, the value of <></>.
var ErrClosed = errors.New("the channel is closed")
ErrClosed is the error of a send on a closed channel, or of a second close.
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.
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.
var RegexPatternTag = NewTag("Regex.Pattern", RegexTag, nil)
RegexPatternTag is the tag of Regex.Pattern, which is tests.
Functions ¶
func Deep ¶
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 Equal ¶
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 ¶
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 ¶
Hash agrees with Equal: equal values hash alike. It walks a bounded prefix of a container, so it terminates on cyclic values.
func HtmlAttrChar ¶
HtmlAttrChar reports whether c may continue an attribute name.
func HtmlAttrName ¶
HtmlAttrName reports whether s is an attribute name: an ASCII letter or _, then ASCII letters, digits, -, _, :, and ..
func HtmlCheckSrcset ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Render is String.from (section 11): the rendering print, println and string interpolation use.
func RenderHtml ¶
RenderHtml is String.from of an Html value: its markup.
func RenderQuoted ¶
RenderQuoted renders v as it would appear inside a container: strings quoted with escapes.
func Text ¶
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 ¶
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.
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 (*Array) Insert ¶
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) Pop ¶
Pop removes and returns the last element, or reports false when the array is empty.
func (*Array) Remove ¶
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.
type Atomic ¶
type Atomic struct {
Slot Slot
}
Atomic is a shared slot whose operations form one total order.
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 NewBytes ¶ added in v0.2.0
NewBytes makes Bytes holding b, adopting b's array: the caller gives it up.
func (*Bytes) Append ¶ added in v0.2.0
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
Get reads the byte at i, or reports false when i is out of range.
func (*Bytes) Pop ¶ added in v0.2.0
Pop removes and returns the last byte, or reports false when x is empty.
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 NewTickerChan ¶
NewTickerChan creates a ticker's channel, holding one tick, that stops with ctx.
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) Len ¶
Len is the number of values buffered now; none for a stopped ticker, whose tick is stale.
func (*Chan) Receive ¶
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 ¶
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.
type Cond ¶
type Cond struct {
M *Mutex
// contains filtered or unexported fields
}
Cond is a condition variable over a Mutex.
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 ¶
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 ¶
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.
type Declaration ¶
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 ¶
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) Node ¶
func (b *HtmlBuilder) Node(n HtmlNode)
Node appends one node, joining a text node to one before it.
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 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 ¶
KindByName maps a prelude kind name, including int and byte, to its kind.
func (Kind) IsPrimitive ¶
IsPrimitive reports whether k is one of the twelve primitive kinds a named type may wrap.
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 (*Map) Next ¶
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.
type Mutex ¶
type Mutex struct {
// contains filtered or unexported fields
}
Mutex is a mutual exclusion lock that any goroutine may unlock.
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.
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 NewRecord ¶
NewRecord creates a record with the given field values, in the tag's order. A nil entry leaves the field uninitialized.
type Reflected ¶
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.
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 (*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 ¶
ReadUnlock releases one shared hold.
func (*RwMutex) WriteUnlock ¶
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 (*Set) Add ¶
Add inserts x and reports whether it was new. A member already there keeps its position.
func (*Set) Next ¶
Next returns the first member whose sequence number is above after, as Map.Next does.
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 ¶
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.
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 ¶
NewPrimitiveTag creates the tag of a named primitive type over base.
func (*Tag) FieldIndex ¶
FieldIndex returns the position of a field of a record 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 ¶
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 ¶
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 Convert ¶
Convert applies one of the twelve conversion functions (section 12). A tagged argument is unwrapped first.
func TextIn ¶
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.