Documentation
¶
Overview ¶
Package tags is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package tags holds gameplay tags: dotted hierarchical names such as status.debuff.stun that abilities, AI, items, cards and UI share as one vocabulary.
A Registry declares the tags a game uses in a versioned YAML file (typically tags.yaml) read with Parse and written with Encode; parent prefixes of declared tags are implied automatically. Each tag resolves once at load into a small interned Tag ID. A Container holds an entity's active tags in a sorted set with per-tag reference counts, and a Query evaluates nestable all/any/none rules with parent matching and zero heap allocations.
Index ¶
- Constants
- func Encode(r *Registry) ([]byte, error)
- func EncodeQueryDoc(q *QueryDoc) ([]byte, error)
- func MatchesName(held, query string) bool
- func ParentName(name string) string
- func ValidName(name string) bool
- type Container
- func (c *Container) Add(tag Tag)
- func (c *Container) AddCount(tag Tag, n int)
- func (c *Container) Clear()
- func (c *Container) Clone() *Container
- func (c *Container) Count(tag Tag) int
- func (c *Container) Has(tag Tag) bool
- func (c *Container) HasAll(tags ...Tag) bool
- func (c *Container) HasAny(tags ...Tag) bool
- func (c *Container) HasExact(tag Tag) bool
- func (c *Container) Len() int
- func (c *Container) Registry() *Registry
- func (c *Container) Remove(tag Tag)
- func (c *Container) RemoveAll(tag Tag)
- func (c *Container) Tags() []Tag
- type Definition
- type Query
- type QueryDoc
- type QueryTerm
- type Registry
- func (r *Registry) All() []Tag
- func (r *Registry) CompileQuery(doc *QueryDoc) (Query, error)
- func (r *Registry) Has(name string) bool
- func (r *Registry) HasDeclared(name string) bool
- func (r *Registry) Lookup(name string) (Tag, bool)
- func (r *Registry) MustLookup(name string) Tag
- func (r *Registry) Nearest(name string) (string, bool)
- func (r *Registry) ParseQuery(data []byte) (Query, error)
- func (r *Registry) TagByID(id uint32) (Tag, bool)
- type Tag
Examples ¶
Constants ¶
const ( // MaxTags is the maximum number of declared tags a Registry may hold. MaxTags = 65535 // MaxNameLength is the maximum byte length of a gameplay tag name. MaxNameLength = tagmatch.MaxNameLength // MaxDepth is the maximum number of dot-separated segments in a gameplay tag name. MaxDepth = tagmatch.MaxDepth )
const FileName = "tags.yaml"
FileName is the default tag registry file name at a project root.
const MaxQueryDepth = 16
MaxQueryDepth is the maximum nesting depth allowed for a tag query.
const Version = 1
Version is the version of the tag registry file schema this package reads and writes.
Variables ¶
This section is empty.
Functions ¶
func Encode ¶
Encode validates r as Parse does and writes it as canonical YAML, two-space indented with the declared tags sorted by name, which Parse reads back unchanged. Implied parent prefixes are not written unless they were explicitly declared.
func EncodeQueryDoc ¶
EncodeQueryDoc validates q and writes it as canonical two-space YAML that ParseQueryDoc reads back unchanged.
func MatchesName ¶
MatchesName reports whether held matches query under gameplay-tag hierarchy: held equals query, or held is a descendant of query (starts with query followed by '.'). Both held and query must be non-empty.
func ParentName ¶
ParentName returns the immediate parent of name (everything before the last '.'), or "" when name has no '.'.
Types ¶
type Container ¶
type Container struct {
// contains filtered or unexported fields
}
Container holds the active gameplay tags of one entity in a sorted set, with a reference count for each tag so multiple sources (effects, items, states) granting the same tag do not remove each other's grant.
A zero Container is ready to use and binds to the Registry of the first Tag added to it, or can be created bound to a Registry with NewContainer. All query methods (Has, HasExact, HasAny, HasAll, Count) run in O(log n) per tag with zero heap allocations.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/tags"
)
func main() {
reg, err := tags.NewRegistry(tags.Definition{Name: "status.debuff.stun"})
if err != nil {
fmt.Println(err)
return
}
stun := reg.MustLookup("status.debuff.stun")
debuff := reg.MustLookup("status.debuff")
c := tags.NewContainer(reg)
// Two effects stun the entity, so the tag holds two references.
c.Add(stun)
c.Add(stun)
// Has matches parents; HasExact matches only the tag itself.
fmt.Println(c.Has(debuff), c.HasExact(debuff))
c.Remove(stun)
fmt.Println("after one removal:", c.HasExact(stun))
c.Remove(stun)
fmt.Println("after two removals:", c.HasExact(stun), c.Len())
}
Output: true false after one removal: true after two removals: false 0
func NewContainer ¶
NewContainer returns an empty Container bound to reg.
func (*Container) Add ¶
Add increments the reference count of tag by 1. An invalid tag or a tag from a different Registry is ignored.
func (*Container) AddCount ¶
AddCount increments the reference count of tag by n when n > 0. An invalid tag, non-positive n, or a tag from a different Registry is ignored.
func (*Container) Clear ¶
func (c *Container) Clear()
Clear removes every tag from c while keeping its backing slice capacity.
func (*Container) Count ¶
Count returns the current reference count of tag in c, or 0 if not present.
func (*Container) Has ¶
Has reports whether c holds tag or any descendant of tag: holding status.debuff.stun matches status.debuff and status, because a child tag implies its parents, while holding only status.debuff does not match status.debuff.stun.
func (*Container) HasAll ¶
HasAll reports whether c matches every tag in tags (using Has). It returns true when tags is empty.
func (*Container) HasAny ¶
HasAny reports whether c matches at least one tag in tags (using Has). It returns false when tags is empty.
func (*Container) Remove ¶
Remove decrements the reference count of tag by 1, removing tag when its count reaches 0.
type Definition ¶
type Definition struct {
// Name is the tag: dot-separated segments, each a letter followed by letters, digits, '_' or '-'. Each segment names a child of the tag before it.
Name string `yaml:"name"`
// Description, optional, says what the tag means.
Description string `yaml:"description,omitempty"`
}
Definition declares one tag of a registry.
type Query ¶
type Query struct {
// All are tags the container must all match (using Container.Has).
All []Tag
// Any are tags of which the container must match at least one (together with AnyNested);
// when both Any and AnyNested are empty, no condition is imposed.
Any []Tag
// None are tags the container must match none of.
None []Tag
// AllNested are nested queries that must all match.
AllNested []Query
// AnyNested are nested queries of which at least one (or one tag in Any) must match.
AnyNested []Query
// NoneNested are nested queries that must none of them match.
NoneNested []Query
}
Query is a compiled, nestable gameplay tag query holding interned Tag IDs.
Build a Query in Go with Tag values from a Registry or compile YAML with Registry.ParseQuery or Registry.CompileQuery. Match evaluates the query against a Container with parent matching and zero heap allocations.
func (Query) Match ¶
Match reports whether c satisfies q (every entry in All and AllNested matches, at least one entry in Any or AnyNested matches when either is non-empty, and no entry in None or NoneNested matches). Match performs zero heap allocations.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/tags"
)
func main() {
reg, err := tags.NewRegistry(
tags.Definition{Name: "ability.fire"},
tags.Definition{Name: "ability.ice"},
tags.Definition{Name: "status.debuff.stun"},
tags.Definition{Name: "status.immune.stun"},
)
if err != nil {
fmt.Println(err)
return
}
q, err := reg.ParseQuery([]byte(`all:
- ability
- any: [ability.ice, status.debuff]
none:
- status.immune
`))
if err != nil {
fmt.Println(err)
return
}
c := tags.NewContainer(reg)
c.Add(reg.MustLookup("ability.fire"))
c.Add(reg.MustLookup("status.debuff.stun"))
fmt.Println(q.Match(c))
// Gaining an immunity rules the entity out.
c.Add(reg.MustLookup("status.immune.stun"))
fmt.Println(q.Match(c))
}
Output: true false
type QueryDoc ¶
type QueryDoc struct {
// All are tags or nested queries that must all match.
All []QueryTerm `yaml:"all,omitempty"`
// Any are tags or nested queries of which at least one must match; empty imposes no condition.
Any []QueryTerm `yaml:"any,omitempty"`
// None are tags or nested queries that must none of them match.
None []QueryTerm `yaml:"none,omitempty"`
}
QueryDoc is the authored YAML representation of a gameplay tag query:
all: - status.debuff - any: [ability.fire, ability.ice] none: - status.immune.stun
Each element of all, any and none is either a dotted tag name string or a nested QueryDoc mapping. Compile a QueryDoc against a Registry with Registry.CompileQuery to obtain an allocation-free Query.
func ParseQueryDoc ¶
ParseQueryDoc decodes a strict YAML tag query document and validates its structure, nesting depth and tag name syntax. Unknown fields, duplicate keys, non-string/non-mapping terms and trailing YAML documents are refused with a *loaderr.Error.
func (QueryDoc) MarshalYAML ¶
MarshalYAML encodes q deterministically in fixed key order (all, any, none).
func (*QueryDoc) UnmarshalYAML ¶
UnmarshalYAML decodes a QueryDoc strictly from a YAML mapping node, refusing unknown or duplicate keys, non-sequence lists and excessive nesting depth.
type QueryTerm ¶
type QueryTerm struct {
// Tag is a dotted gameplay tag name when Query is nil.
Tag string
// Query is a nested tag query when Tag is empty.
Query *QueryDoc
}
QueryTerm is one element of a QueryDoc's All, Any or None list: either a tag name string or a nested QueryDoc.
func NestedTerm ¶
NestedTerm returns a QueryTerm matching the nested query q.
type Registry ¶
type Registry struct {
// Version is the schema version; it must equal Version.
Version int `yaml:"version"`
// Tags are the declared tags, each name once. Encode writes them sorted by name.
Tags []Definition `yaml:"tags"`
// contains filtered or unexported fields
}
Registry is the root of a versioned YAML tag registry file: the tags a game declares and their implied parent prefixes, indexed into compact interned Tag IDs.
Build a Registry with Parse or NewRegistry. A compiled Registry is immutable and safe for concurrent reads.
func NewRegistry ¶
func NewRegistry(defs ...Definition) (*Registry, error)
NewRegistry validates defs and returns a compiled version 1 Registry holding copies of defs in sorted name order, with all implied parent prefixes interned.
func Parse ¶
Parse decodes a YAML tag registry, validates it, and compiles its interned tag index (including implied parent prefixes). Unknown fields, trailing YAML documents, a missing or unsupported version, and invalid or duplicate tag names are refused with a *loaderr.Error that names the line and a fix.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/tags"
)
func main() {
reg, err := tags.Parse([]byte(`version: 1
tags:
- name: status.debuff.stun
- name: ability.fire
`))
if err != nil {
fmt.Println(err)
return
}
// Parents of declared tags are implied; HasDeclared checks explicit entries only.
fmt.Println(reg.Has("ability.fire"), reg.Has("ability"), reg.HasDeclared("ability"))
// Encode writes only declared tags, sorted by name.
out, err := tags.Encode(reg)
if err != nil {
fmt.Println(err)
return
}
fmt.Print(string(out))
}
Output: true true false version: 1 tags: - name: ability.fire - name: status.debuff.stun
func (*Registry) All ¶
All returns all interned tags in r (declared tags and implied parents) in deterministic DFS pre-order.
func (*Registry) CompileQuery ¶
CompileQuery resolves every tag in doc against r (accepting both declared tags and implied parent prefixes) and returns a compiled Query. Any undeclared tag is refused with a *loaderr.Error naming its field path and a nearest-name suggestion when one exists.
func (*Registry) Has ¶
Has reports whether r knows name: either explicitly declared in r.Tags or an implied parent prefix of a declared tag. A nil registry knows none.
func (*Registry) HasDeclared ¶
HasDeclared reports whether r explicitly declares name in r.Tags (not merely as an implied parent prefix). A nil registry declares none.
func (*Registry) Lookup ¶
Lookup resolves name to its interned Tag in r. It matches both explicitly declared tags and implied parent prefixes (for example, "status.debuff" when "status.debuff.stun" is declared). A nil or uncompiled registry resolves nothing.
func (*Registry) MustLookup ¶
MustLookup resolves name in r and panics if it is not registered.
func (*Registry) Nearest ¶
Nearest suggests the closest registered tag name (declared or implied parent) to name, returning ("", false) when r is empty or no tag is close enough to be a plausible typo.
func (*Registry) ParseQuery ¶
ParseQuery parses YAML as a strict QueryDoc and compiles it against r, returning a *loaderr.Error with the offending line, column, field path and suggestion on error.
type Tag ¶
type Tag struct {
// contains filtered or unexported fields
}
Tag is a small interned gameplay tag ID resolved from a Registry at load time.
Two Tag values from the same Registry are equal if and only if they name the same tag. A zero Tag is invalid (Valid reports false). Parent/descendant checks compare two integer bounds in O(1) time with zero allocations.
func (Tag) Description ¶
Description returns the declared description of t, or "" for an implied parent or invalid Tag.
func (Tag) ID ¶
ID returns t's compact 1-based interned ID within its Registry, or 0 for an invalid Tag.
func (Tag) Matches ¶
Matches reports whether t equals parent or is a descendant of parent in the same Registry. For example, status.debuff.stun matches status.debuff and status, while status.debuff does not match status.debuff.stun.
func (Tag) Parent ¶
Parent returns t's immediate parent Tag, or the zero Tag when t is a top-level segment or invalid.