tags

package
v0.4.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 10 Imported by: 0 modules, 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 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

Examples

Constants

View Source
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
)
View Source
const FileName = "tags.yaml"

FileName is the default tag registry file name at a project root.

View Source
const MaxQueryDepth = 16

MaxQueryDepth is the maximum nesting depth allowed for a tag query.

View Source
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

func Encode(r *Registry) ([]byte, error)

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

func EncodeQueryDoc(q *QueryDoc) ([]byte, error)

EncodeQueryDoc validates q and writes it as canonical two-space YAML that ParseQueryDoc reads back unchanged.

func MatchesName

func MatchesName(held, query string) bool

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

func ParentName(name string) string

ParentName returns the immediate parent of name (everything before the last '.'), or "" when name has no '.'.

func ValidName

func ValidName(name string) bool

ValidName reports whether name is a valid dotted gameplay tag: 1 to MaxDepth dot-separated segments (at most MaxNameLength bytes total), each starting with an ASCII letter followed by ASCII letters, digits, '_' or '-'.

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

func NewContainer(reg *Registry) *Container

NewContainer returns an empty Container bound to reg.

func (*Container) Add

func (c *Container) Add(tag Tag)

Add increments the reference count of tag by 1. An invalid tag or a tag from a different Registry is ignored.

func (*Container) AddCount

func (c *Container) AddCount(tag Tag, n int)

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) Clone

func (c *Container) Clone() *Container

Clone returns a deep copy of c.

func (*Container) Count

func (c *Container) Count(tag Tag) int

Count returns the current reference count of tag in c, or 0 if not present.

func (*Container) Has

func (c *Container) Has(tag Tag) bool

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

func (c *Container) HasAll(tags ...Tag) bool

HasAll reports whether c matches every tag in tags (using Has). It returns true when tags is empty.

func (*Container) HasAny

func (c *Container) HasAny(tags ...Tag) bool

HasAny reports whether c matches at least one tag in tags (using Has). It returns false when tags is empty.

func (*Container) HasExact

func (c *Container) HasExact(tag Tag) bool

HasExact reports whether c holds tag itself (ignoring descendants).

func (*Container) Len

func (c *Container) Len() int

Len returns the number of distinct tags currently held in c.

func (*Container) Registry

func (c *Container) Registry() *Registry

Registry returns the Registry c is bound to, or nil when unbound.

func (*Container) Remove

func (c *Container) Remove(tag Tag)

Remove decrements the reference count of tag by 1, removing tag when its count reaches 0.

func (*Container) RemoveAll

func (c *Container) RemoveAll(tag Tag)

RemoveAll removes tag regardless of its current reference count.

func (*Container) Tags

func (c *Container) Tags() []Tag

Tags returns the tags currently held in c in sorted ID order.

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

func (q Query) Match(c *Container) bool

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

func ParseQueryDoc(data []byte) (*QueryDoc, error)

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

func (q QueryDoc) MarshalYAML() (any, error)

MarshalYAML encodes q deterministically in fixed key order (all, any, none).

func (*QueryDoc) UnmarshalYAML

func (q *QueryDoc) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML decodes a QueryDoc strictly from a YAML mapping node, refusing unknown or duplicate keys, non-sequence lists and excessive nesting depth.

func (*QueryDoc) Validate

func (q *QueryDoc) Validate() error

Validate checks q's structure, nesting depth and tag name syntax.

func (*QueryDoc) WalkTags

func (q *QueryDoc) WalkTags(fn func(fieldPath, tag string))

WalkTags visits every tag name referenced in q (including inside nested queries) in deterministic order, passing each tag's loaderr field path (such as "all[1].any[0]").

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

func NestedTerm(q QueryDoc) QueryTerm

NestedTerm returns a QueryTerm matching the nested query q.

func TagTerm

func TagTerm(name string) QueryTerm

TagTerm returns a QueryTerm matching the named tag.

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

func Parse(data []byte) (*Registry, error)

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

func (r *Registry) All() []Tag

All returns all interned tags in r (declared tags and implied parents) in deterministic DFS pre-order.

func (*Registry) CompileQuery

func (r *Registry) CompileQuery(doc *QueryDoc) (Query, error)

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

func (r *Registry) Has(name string) bool

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

func (r *Registry) HasDeclared(name string) bool

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

func (r *Registry) Lookup(name string) (Tag, bool)

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

func (r *Registry) MustLookup(name string) Tag

MustLookup resolves name in r and panics if it is not registered.

func (*Registry) Nearest

func (r *Registry) Nearest(name string) (string, bool)

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

func (r *Registry) ParseQuery(data []byte) (Query, error)

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.

func (*Registry) TagByID

func (r *Registry) TagByID(id uint32) (Tag, bool)

TagByID returns the Tag with the given interned ID, or (Tag{}, false) if out of range.

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

func (t Tag) Description() string

Description returns the declared description of t, or "" for an implied parent or invalid Tag.

func (Tag) ID

func (t Tag) ID() uint32

ID returns t's compact 1-based interned ID within its Registry, or 0 for an invalid Tag.

func (Tag) Matches

func (t Tag) Matches(parent Tag) bool

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) Name

func (t Tag) Name() string

Name returns t's dotted tag name, or "" for an invalid Tag.

func (Tag) Parent

func (t Tag) Parent() Tag

Parent returns t's immediate parent Tag, or the zero Tag when t is a top-level segment or invalid.

func (Tag) String

func (t Tag) String() string

String returns t's dotted tag name, or "" for an invalid Tag.

func (Tag) Valid

func (t Tag) Valid() bool

Valid reports whether t is a resolved tag belonging to a Registry.

Jump to

Keyboard shortcuts

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