ast

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 16 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

Example (AddAComment)

Add a comment to a document, and leave everything else as it was written.

A comment set where the document wrote none is laid out by the slot it goes in: the entry's head comment above it, the value's comment at the end of its line. Renderer.VerbatimFile writes the rest byte for byte.

package main

import (
	"fmt"
	"os"

	"github.com/go-openapi/go-yaml/ast"
	"github.com/go-openapi/go-yaml/parser"
	"github.com/go-openapi/go-yaml/token"
)

func main() {
	src := []byte(`# Service settings.
name: my-service
port: 8080   # the listener
debug: false
`)
	file, err := parser.ParseBytes(src, parser.WithComments())
	if err != nil {
		fmt.Println(err)

		return
	}

	comment := func(text string) *ast.CommentGroupNode {
		return ast.CommentGroup([]*token.Token{token.Comment(text, "#"+text, token.Position{})})
	}

	debug := ast.Lookup(file.Docs[0].Body, "debug")
	if err := debug.SetHeadComment(comment(" Turn on for local runs only.")); err != nil {
		fmt.Println(err)
	}
	if err := debug.Value.SetComment(comment(" off in production")); err != nil {
		fmt.Println(err)
	}

	if err := ast.NewRenderer(ast.WithSource(src)).VerbatimFile(os.Stdout, file); err != nil {
		fmt.Println(err)
	}

}
Output:
# Service settings.
name: my-service
port: 8080   # the listener
# Turn on for local runs only.
debug: false # off in production
Example (BuildADocument)

Build a configuration file from nothing.

ast.Text quotes a string whose text would read back as something else, so the version below stays a string and the port stays a number.

package main

import (
	"fmt"

	"github.com/go-openapi/go-yaml/ast"
	"github.com/go-openapi/go-yaml/token"
)

func main() {
	config := ast.Map(
		ast.Entry("name", ast.Text("my-service")),
		ast.Entry("version", ast.Text("8080")),
		ast.Entry("port", ast.Integer(token.New("8080", "8080", token.Position{}))),
		ast.Entry("debug", ast.Bool(token.New("false", "false", token.Position{}))),
		ast.Entry("tags", ast.Seq(ast.Text("web"), ast.Text("api"))),
		ast.Entry("database", ast.Map(
			ast.Entry("host", ast.Text("localhost")),
			ast.Entry("port", ast.Integer(token.New("5432", "5432", token.Position{}))),
		)),
	)

	fmt.Println(ast.NewRenderer().String(config))

}
Output:
name: my-service
version: "8080"
port: 8080
debug: false
tags:
- web
- api
database:
  host: localhost
  port: 5432
Example (LookupThroughAMerge)

Read a key a "<<" brings in, and one an alias stands for.

ast.Lookup reads what a mapping itself writes, through the anchor, tag or alias in front of it. ast.LookupMerged reads the merged mappings too, and the merge type gives the mapping's own keys precedence, so "host" below is the one development writes and not the one defaults holds.

package main

import (
	"fmt"

	"github.com/go-openapi/go-yaml/ast"
	"github.com/go-openapi/go-yaml/parser"
)

func main() {
	src := []byte(`defaults: &defaults
  adapter: postgres
  host: localhost
  pool: 5
development:
  <<: *defaults
  database: dev_db
  host: 127.0.0.1
production: *defaults
`)
	file, err := parser.ParseBytes(src, parser.WithMergeKeys())
	if err != nil {
		fmt.Println(err)

		return
	}
	root := file.Docs[0].Body

	development := ast.Lookup(root, "development").Value
	for _, key := range []string{"host", "adapter", "absent"} {
		fmt.Printf("development.%-7s own %-9v merged %v\n", key,
			held(ast.Lookup(development, key)), held(ast.LookupMerged(development, key)))
	}

	// production is an alias, and Lookup follows it to the mapping its anchor names.
	fmt.Println("production.adapter", held(ast.Lookup(ast.Lookup(root, "production").Value, "adapter")))

}

// held is the value an entry holds, for an example that prints what a lookup found.
func held(entry *ast.MappingValueNode) string {
	if entry == nil {
		return "<none>"
	}

	return entry.Value.String()
}
Output:
development.host    own 127.0.0.1 merged 127.0.0.1
development.adapter own <none>    merged postgres
development.absent  own <none>    merged <none>
production.adapter postgres
Example (ResolveACustomTag)

Resolve a custom tag: GitLab CI's !reference names another part of the document by its keys, and a reference in a sequence is replaced by the values of the sequence it names.

The tag stays on the node as the document wrote it, and TagNode.URI names it. Replacing one value with several is SequenceNode.Insert then SequenceNode.Remove, and a node moved from another place in the document is written as nothing there, so the values are copied with ast.Clone.

package main

import (
	"fmt"
	"os"
	"slices"

	"github.com/go-openapi/go-yaml/ast"
	"github.com/go-openapi/go-yaml/parser"
)

func main() {
	src := []byte(`.setup:
  script:
    - echo setup
    - echo more
test:
  script:
    - !reference [.setup, script]
    - echo test
`)
	file, err := parser.ParseBytes(src)
	if err != nil {
		fmt.Println(err)

		return
	}
	root := file.Docs[0].Body

	for _, node := range ast.Filter(ast.TagType, root) {
		tag, _ := node.(*ast.TagNode)
		if tag.URI != "!reference" {
			continue
		}

		target := root
		for _, step := range tag.Value.(*ast.SequenceNode).Values {
			name, _ := ast.KeyName(step)
			entry := ast.Lookup(target, name)
			if entry == nil {
				break
			}
			target = entry.Value
		}
		named, _ := target.(*ast.SequenceNode)
		parent, _ := ast.Parent(root, tag).(*ast.SequenceNode)
		if named == nil || parent == nil {
			continue
		}

		at := slices.Index(parent.Values, ast.Node(tag))
		copies := make([]ast.Node, 0, len(named.Values))
		for _, referenced := range named.Values {
			copies = append(copies, ast.Clone(referenced))
		}
		if err := parent.Insert(at, copies...); err != nil {
			fmt.Println(err)

			return
		}
		if err := parent.Remove(at + len(copies)); err != nil {
			fmt.Println(err)

			return
		}
	}

	if err := ast.NewRenderer(ast.WithSource(src)).VerbatimFile(os.Stdout, file); err != nil {
		fmt.Println(err)
	}

}
Output:
.setup:
  script:
    - echo setup
    - echo more
test:
  script:
    - echo setup
    - echo more
    - echo test
Example (StripComments)

Strip every comment from a document, and leave everything else as it was written.

ast.Filter finds every comment group, and CommentGroupNode.Remove marks one for Renderer.VerbatimFile to leave out. Setting a comment field to nil instead loses the record of which bytes to skip, and the text comes back.

package main

import (
	"fmt"
	"os"

	"github.com/go-openapi/go-yaml/ast"
	"github.com/go-openapi/go-yaml/parser"
)

func main() {
	src := []byte(`# Service settings.
name: my-service   # who we are
# Flags follow.
flags:
  - fast   # really
  - safe
# The end.
`)
	file, err := parser.ParseBytes(src, parser.WithComments())
	if err != nil {
		fmt.Println(err)

		return
	}

	for _, node := range ast.FilterFile(ast.CommentType, file) {
		if group, ok := node.(*ast.CommentGroupNode); ok {
			group.Remove()
		}
	}

	if err := ast.NewRenderer(ast.WithSource(src)).VerbatimFile(os.Stdout, file); err != nil {
		fmt.Println(err)
	}

}
Output:
name: my-service
flags:
  - fast
  - safe

Index

Examples

Constants

View Source
const DefaultIndent = 2

DefaultIndent is the number of spaces one level of nesting adds.

Variables

View Source
var (
	ErrInvalidTokenType  = errors.New("invalid token type")
	ErrInvalidAnchorName = errors.New("invalid anchor name")
	ErrInvalidAliasName  = errors.New("invalid alias name")
)
View Source
var ErrInsert = errors.New("cannot write an inserted node")

ErrInsert is returned by Renderer.Verbatim and Renderer.VerbatimFile when a node a caller put into a parsed tree cannot be written where it was put.

View Source
var ErrMove = errors.New("cannot write a node moved from where the document holds it")

ErrMove is returned by Renderer.Verbatim and Renderer.VerbatimFile when the tree holds nodes of the document in a different order from the one the document wrote them in: two entries or two documents swapped, an entry moved into a later collection, or one node put in a second place.

Use Clone to put a copy of the node in its new place. A copy has no place in the source, so the renderer lays it out from the tree, as it does an inserted node: its comments come along, but its spacing and quoting are the renderer's, not the document's.

View Source
var ErrNotInSource = errors.New("the tree holds a token past the end of the source it is rendered from")

ErrNotInSource is returned by Renderer.Verbatim and Renderer.VerbatimFile, before anything is written, when the tree holds a token whose offsets reach past the end of the source given to WithSource: the wrong source, or a node taken from another parse. Put a Clone of such a node in the tree.

View Source
var ErrRemove = errors.New("cannot leave out a removed node")

ErrRemove is returned by Renderer.Verbatim and Renderer.VerbatimFile when a node taken out of the tree shared a line with one the tree still holds -- an entry of a flow collection -- so that no line can be left out for it.

View Source
var ErrStreamOrder = errors.New("a stream call that does not fit the document written so far")

ErrStreamOrder reports a call to a Stream that does not fit the document written so far: a scalar where a mapping expects a key, an Stream.End with nothing open, or a Stream.Close with a collection still open.

Functions

func BlockSource

func BlockSource(src string, header, content *token.Token) string

BlockSource is the block a folded scalar was written as: src from the end of its header token to the end of its content token, so that the indentation of the first content line stands at the front of it. A parser fills LiteralNode.Source with it.

Nothing for a literal scalar, whose value is its content exactly, and nothing where either offset does not address its token -- a window on some other part of the document is worse than no source at all.

func CanonicalKeyName

func CanonicalKeyName(name string, kind token.KeyKind) string

CanonicalKeyName returns the name two keys are compared by, given the name and kind KeyName or TaggedKeyName returned.

It differs from the name only for a timestamp, which it writes as its instant in UTC: yaml.org/type/timestamp.html gives that as the canonical form, and 3.2.1.3 compares scalars by their canonical forms. So "2001-12-14" and "2001-12-14 00:00:00" are one key, and so is one instant written at "-05:00" and in UTC.

Compared by the text, two spellings passed the duplicate check and then met in the decoder as one time.Time, which kept the second value and dropped the first with nothing reported. The decoder's own == is no help: it compares a time.Time's *time.Location and not its offset, so "+00:00" and "Z" are two keys to a Go map.

func ComparedKeyName

func ComparedKeyName(n Node, alias KeyAlias) (string, token.KeyKind, bool)

ComparedKeyName is ScalarKeyName in the form two keys are compared by, which CanonicalKeyName gives.

Use it to compare two keys. KeyName gives the same string except for a timestamp, which this one writes as its instant in UTC.

func IsNull

func IsNull(n Node) bool

IsNull reports whether n is the null node: written as one, under an anchor, or under a "!!null" tag. "~", "&a" alone, "!!null ~" and "!!null" alone are all null, as is a nil n. An anchor names a node and does not change it, and the tag names the type the node already has.

func KeyIdentity

func KeyIdentity(n Node) string

KeyIdentity writes what a mapping key resolves to, so that two keys the document spelled differently come out the same where 3.2.1.1 makes them one key.

The text a document wrote is not the identity. "[a]", "[ a ]", "[a,]" and '["a"]' are four spellings of one sequence holding one string, and naming a key by its own characters reads them as four keys. Naming it by its first token is worse: every sequence key becomes "[", every block scalar key "|-", and each collides with every other.

A scalar's identity is its type and that type's canonical spelling, which is token.KeyName's rule -- "7" and "007" are one integer and so one key, where "1" and "1.0" are an integer and a float and so two. A collection's is its kind and the identities of what it holds, in order.

It reads the built node, so it can only be asked once the node is built: a key is a run of tokens more often than not, and the parser has none of its children while it is still cutting them.

The empty string is no identity at all, which Unnamed reports. An alias whose anchor the parse could not fill is the case that reaches it.

func KeyIdentityWithAnchors

func KeyIdentityWithAnchors(n Node, anchors AnchorIdentity) string

KeyIdentityWithAnchors is KeyIdentity with an alias named from anchors instead of left unnamed.

⚠️ It never reads AliasNode.Target, and neither does KeyIdentity. Following it expands the alias graph into the identity string, and an alias graph is exponential in the document's length: nine anchors each naming the one before it nine times is 200 bytes of YAML and 9^9 expansions, which built a **3.7 GB string in 9.7 seconds** before this took the target out. maxIdentityDepth is no guard, since the depth there is 9 and the width does the damage.

So an alias costs one map lookup whatever it names. anchors may be nil, and then an alias contributes nothing and the key goes unnamed, which a caller reads with Unnamed.

func KeyName

func KeyName(n Node) (string, token.KeyKind)

KeyName is the name a mapping key is identified by, and the type it resolved to.

⚠️ It checks "is this the same key?", not "how is this key written". Two keys with one name are one key, and 3.2.1.1 makes that an error. Nothing here renders a document: for the characters a key is written with, call the node's String, or build a Renderer with NewRenderer.

Three callers read it, and two of the three read a different form:

  • the parser's duplicate check compares keys, so it reads ComparedKeyName, which folds this name through CanonicalKeyName. The two differ only for a timestamp, which compares as its instant in UTC.
  • codec names a Go map entry or a JSON member by this name and not the compared one, so a timestamp key keeps the zone the document wrote it in.
  • KeyIdentity names the keys this one leaves unnamed, which are the collections.

token.KeyName holds the rule for a scalar's own spelling -- "7" and "007" are one integer written two ways, "1" and "1.0" are an integer and a float -- and documents why it sits in token instead of in any one caller. This is the other half: the walk from the node a document wrote down to the scalar that rule applies to.

It looks through everything that stands in front of a key without being the key. An explicit "?" and an anchor name the node and carry no type. A tag sets the type, so KeyName resolves it instead of stripping it: "!!float 1" is the float 1.0 and is named "1.0", where stripping the tag would read the token "1" and name it after an integer. A block scalar is a string whatever it spells, and its own token is the "|-" header.

The empty string under token.KeyOther means no name, and the caller has to handle it itself:

  • a sequence or a mapping, which has no scalar spelling at all. Compare those with KeyIdentity.

An alias is named as the node its anchor named, through AliasNode.Target.

The three callers share this walk so that none of them drops a step: a codec that leaves out the tag and the alias keys "!!float 1.0: x" as "1" -- a float in the integers' namespace, where an entry keyed "1" then displaces it.

func Merge

func Merge(dst Node, src Node) error

Merge merge document, map, sequence node.

func OrderedMapOf

func OrderedMapOf(n Node) (seq *SequenceNode, entries []Node, ok bool)

OrderedMapOf reads the ordered map an "!!omap" tag on n names.

n carries the tag, directly or under anchors, and the tag stands on a sequence, directly or through anchors and aliases, whose elements are each a mapping holding one key. OrderedMapOf returns that sequence and, for each of its elements, the node holding the element's entry: the MappingValueNode of a mapping written with one entry, or the MappingNode itself where the mapping holds a "<<" or repeats its one key. ok is false where n carries no "!!omap" tag, the tag stands on nothing, or the shape is not the one the tag names.

A mapping that writes its one key twice, "{a: 1, a: 2}", is one key and a repeat: the reader rejects the repeat as it rejects one in any mapping, or reads the last value under an option allowing repeats. A mapping holding a "<<" counts its keys once the merge is read, which this does not do: "{<<: {a: 0}, a: 1}" is one entry and "{<<: {a: 0, b: 1}}" two, so the reader counts them as it reads.

The tag names a kind, and a node of another kind is a document that parses but that a reader builds no value from: "!!omap [1, 2]" parses, and OrderedMapOf returns false for it.

func ScalarKeyName

func ScalarKeyName(n Node, alias KeyAlias) (string, token.KeyKind, bool)

ScalarKeyName names the scalar a mapping key stands for, and its type. It is the one walk from a key node to its name: KeyName, KeyIdentity and the parser's duplicate check all read it, so a rule for one kind of key applies to all three.

It names a key to tell it from another, not to write it out. See KeyName.

It looks through an explicit "?", an anchor and a tag that names no type. A tag that names one sets the key's type, through TaggedKeyName. A quoted key is named by what its escapes resolved to, a block scalar by its string and not its "|-" header, and an alias by alias, which may be nil.

It reports false for a collection, which KeyIdentity names from what it holds, and for an alias that the alias function does not resolve.

func TaggedKeyName

func TaggedKeyName(n *TagNode) (string, token.KeyKind, bool)

TaggedKeyName names a key from the tag standing on it, for the tags that name one of the types a key is told apart by. It reports false where the tag names no such type, and the caller then names TagNode.Value instead: a tag the schema does not resolve, one naming a kind -- !!seq, !!map -- or one the application declared.

The empty node under a tag the schema does not resolve is the exception: "!a : x" names the empty string, as the decoder reads it. Its node is the null the parser builds for an empty node, and naming that node would name the key "null".

Three walks reach a tagged key and all three must agree, or one names a key that another does not: KeyName, KeyIdentity, and the parser's duplicate check, which keeps a walk of its own because it resolves an alias through the anchors it has recorded and not through AliasNode.Target. They read this rather than each carrying the switch. Three copies of it named "!!int 0x10" the string "0x10" where "0x10" alone named the integer 16, so the two spellings passed the duplicate check and then collided in the decoder, which dropped the first value.

func Unnamed

func Unnamed(identity string) bool

Unnamed reports whether KeyIdentity gave up on a node.

func Walk

func Walk(v Visitor, node Node)

Walk traverses an AST in depth-first order: it calls v.Visit(node), and where the visitor it returns is not nil, walks each child of node with that visitor.

A nil node and a nil child are passed over, so a document with no body is walked without a call for it.

The children include every comment group the node holds -- the head comment, the line comment, a mapping's or a sequence's foot and start comment, a document's start and end comment -- each visited once, in the order they stand in the document. Walk does not look inside a comment group, and it does not follow AliasNode.Target.

Types

type AliasNode

type AliasNode struct {
	BaseNode

	Start *token.Token
	Value Node
	// Target is the node the alias names, which the parser fills as it reads
	// the alias. Read it to expand an alias without collecting anchors of your
	// own; the parser resolves the name where the alias stands, so two aliases
	// of one name written either side of a redefined anchor point at the two
	// nodes and not both at the last.
	//
	// It is nil for an alias built by hand and for one the encoder writes,
	// neither of which went through a parse.
	//
	// ⚠️ Target may reach back to a node the alias stands inside: "&x [ *x ]"
	// is a document, and YAML's representation is a graph. Expand it with a
	// guard, as [github.com/go-openapi/go-yaml.Decoder] does -- it rejects a
	// cycle, because a Go value built by walking has nowhere to put one.
	//
	// Nothing follows Target on its own: [Walk] does not, and neither does the
	// renderer, which writes an alias as the "*name" it was written as.
	Target Node
}

AliasNode is an alias, "*name", to an anchored node.

func Alias

func Alias(tk *token.Token) *AliasNode

func (*AliasNode) Bytes

func (n *AliasNode) Bytes() []byte

Bytes returns AliasNode.Text as bytes, without copying it.

func (*AliasNode) Clone

func (n *AliasNode) Clone() *AliasNode

func (*AliasNode) GetToken

func (n *AliasNode) GetToken() *token.Token

GetToken returns n.Start, the "*name".

func (*AliasNode) GetValue

func (n *AliasNode) GetValue() any

func (*AliasNode) IsMergeKey

func (n *AliasNode) IsMergeKey() bool

IsMergeKey returns false.

func (*AliasNode) SetName

func (n *AliasNode) SetName(name string) error

func (*AliasNode) String

func (n *AliasNode) String() string

String returns "*name".

func (*AliasNode) Text

func (n *AliasNode) Text() string

Text returns the text of the node the alias names, as AliasNode.GetValue does.

func (*AliasNode) Type

func (n *AliasNode) Type() NodeType

Type returns AliasType.

type AnchorIdentity

type AnchorIdentity func(name string) (string, bool)

AnchorIdentity returns the identity of the node an anchor names, looked up by the anchor's name, and reports whether it holds one.

It names an alias without reading AliasNode.Target. A caller that holds the anchors -- the parser does, and records each identity as the anchor closes -- returns the identity in constant time, from a string it already holds.

type AnchorNode

type AnchorNode struct {
	BaseNode

	Start *token.Token
	Name  Node
	Value Node
}

AnchorNode is an anchor, "&name", on the node it names.

func Anchor

func Anchor(tk *token.Token) *AnchorNode

func (*AnchorNode) Bytes

func (n *AnchorNode) Bytes() []byte

Bytes returns AnchorNode.Text as bytes, without copying it.

func (*AnchorNode) Clone

func (n *AnchorNode) Clone() *AnchorNode

func (*AnchorNode) GetToken

func (n *AnchorNode) GetToken() *token.Token

GetToken returns n.Start, the "&name".

func (*AnchorNode) GetValue

func (n *AnchorNode) GetValue() any

func (*AnchorNode) IsMergeKey

func (n *AnchorNode) IsMergeKey() bool

IsMergeKey returns whether the anchored node is a merge key.

func (*AnchorNode) SetName

func (n *AnchorNode) SetName(name string) error

func (*AnchorNode) String

func (n *AnchorNode) String() string

String renders "&name" and the anchored node.

func (*AnchorNode) Text

func (n *AnchorNode) Text() string

Text returns the text of the node the anchor names, as AnchorNode.GetValue does.

func (*AnchorNode) Type

func (n *AnchorNode) Type() NodeType

Type returns AnchorType.

type Arena

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

Arena hands out nodes from blocks rather than one allocation each.

A parser building a tree of N nodes costs N/size allocations rather than N. The nodes are addressed by pointer as they are anywhere else, so a node from an arena is an Node like any other and nothing downstream can tell.

Two things follow from a block being one heap object. A node stays valid for as long as anything points at it, whatever happens to the arena -- the arena is a source of nodes, not their owner. And a block is freed only when nothing points into it, so holding one node of a document holds the block it came from, up to 512 nodes. That is the trade: a tree lives and dies together, and a caller keeping one node out of a large tree keeps more than it asked for.

The zero Arena is ready to use and allocates blocks of minNodeBlock. Use NewArena to size them for a document.

func NewArena

func NewArena(n int) *Arena

NewArena returns an arena whose blocks are sized for a document of n tokens.

A block holds n/4 nodes, since roughly one token in four becomes a node of any one type. The size is capped both ways: a long document takes more blocks instead of one huge one, and a short document does not pay for a block it will use a tenth of.

func (*Arena) Bool

func (a *Arena) Bool(tk *token.Token) *BoolNode

Bool returns a BoolNode for tk, as Bool does.

func (*Arena) Commit

func (a *Arena) Commit()

Commit pins every node handed out so far, so that no mark still outstanding rewinds past it.

A walk hands the cells of an entry out again once the entry has gone over, so its frontier stays flat. An anchored node has to outlive that: an alias names it later in the document, and AliasNode.Target points at the cell. Without this the cell is handed out again and the alias reads whatever was built there next -- "a: &x {k: 1}" over one filler line over "b: *x" read back as "{b: 0}".

It raises the outstanding marks instead of dropping them, so the walk still rewinds everything built after the anchor. Commit keeps alive the anchored subtree, plus whatever the entry holding it built before it.

func (*Arena) Float

func (a *Arena) Float(tk *token.Token) *FloatNode

Float returns a FloatNode for tk, as Float does.

func (*Arena) Integer

func (a *Arena) Integer(tk *token.Token) *IntegerNode

Integer returns an IntegerNode for tk, as Integer does.

func (*Arena) Mapping

func (a *Arena) Mapping(tk *token.Token, isFlowStyle bool, values []*MappingValueNode) *MappingNode

Mapping returns a MappingNode for tk holding values, as Mapping does.

values is copied, and the copy is held to its own length: a caller appending to the mapping's Values takes an allocation of its own rather than writing over another mapping's entries.

func (*Arena) MappingRun

func (a *Arena) MappingRun(values []*MappingValueNode) []*MappingValueNode

MappingRun returns a copy of values that no later call writes over, for a mapping whose entries were gathered before the node above them was built.

Arena.Mapping takes its entries when the node is made. A parse that makes the node first, so that a walk is handed it before its entries, fills them in with this.

func (*Arena) MappingValue

func (a *Arena) MappingValue(tk *token.Token, key MapKeyNode, value Node) *MappingValueNode

MappingValue returns a MappingValueNode for tk, as MappingValue does.

func (*Arena) Mark

func (a *Arena) Mark() Mark

Mark records where the arena stands.

A walk takes one as it enters a node and gives it back as it leaves, which makes the arena a stack: the nodes of a subtree are handed out again for the subtree that follows it. A walk holds at once the nodes along its own depth, not the whole document, so a document of any size is read from a handful of chunks.

func (*Arena) Null

func (a *Arena) Null(tk *token.Token) *NullNode

Null returns a NullNode for tk, as Null does.

func (*Arena) Pop

func (a *Arena) Pop()

Pop hands out again every node taken since the matching Arena.Push.

⚠️ It carries Arena.Rewind's warning: every node handed out since the push is dead the moment this returns.

func (*Arena) Push

func (a *Arena) Push()

Push records where the arena stands, for a later Arena.Pop.

func (*Arena) Reset

func (a *Arena) Reset()

Reset hands every cell out again from the start of each block, as Arena.ResetWithSize does, and sizes the blocks allocated from now on as the zero Arena does.

func (*Arena) ResetWithSize

func (a *Arena) ResetWithSize(n int)

ResetWithSize hands every cell out again from the start of each block, and sizes the blocks allocated from now on for a document of n tokens, as NewArena does.

Every node the arena handed out before the reset is invalid afterwards: the next node takes its cell. The mapping runs are not recycled, and the next run takes the rest of the block in hand.

func (*Arena) Rewind

func (a *Arena) Rewind(m Mark)

Rewind hands out again every node taken since m.

⚠️ Every node handed out since m is dead the moment this returns, and the cells are written over by what comes next. Call it only when nothing points at them -- github.com/go-openapi/go-yaml/parser.Parser.Walk rewinds to what it marked on Enter once Leave has returned, and a parse that gathers a tree never rewinds at all.

The mapping runs are not rewound: a walk builds none, since a collection walking keeps no entries.

func (*Arena) Sequence

func (a *Arena) Sequence(tk *token.Token, isFlowStyle bool) *SequenceNode

Sequence returns a SequenceNode for tk, as Sequence does.

func (*Arena) SequenceEntry

func (a *Arena) SequenceEntry(start *token.Token, value Node, headComment *CommentGroupNode) *SequenceEntryNode

SequenceEntry returns a SequenceEntryNode for start, as SequenceEntry does.

func (*Arena) String

func (a *Arena) String(tk *token.Token) *StringNode

String returns a StringNode for tk, as String does.

type BaseNode

type BaseNode struct {
	Comment *CommentGroupNode
	// HeadComment holds the comments above the node, on lines of their own. It
	// may hold several: a run of comment lines above one node is one group.
	//
	// Comment is the node's other one and does not mean the same thing for
	// every node. On a MappingNode or a SequenceNode it is the head comment and
	// the renderer writes it above; on an AnchorNode or a TagNode it is the
	// comment written beside the property, which Renderer.withOwnComment puts
	// back at the end of that line; on a bare scalar it is whatever was
	// attached last. So a node outside a mapping or sequence entry had one
	// field for two comments and the second write took the first: "# c1" over
	// "831 # c2" rendered "831 # c1" with the property comment gone, and
	// "# c1" over "&a q # c2" rendered both onto one line, which the scanner
	// reads back as a single comment.
	//
	// This means one thing everywhere, and [Renderer] writes it above whatever
	// the node is.
	HeadComment *CommentGroupNode
	// contains filtered or unexported fields
}

func (*BaseNode) GetComment

func (n *BaseNode) GetComment() *CommentGroupNode

GetComment returns the comment after the node, on its line.

func (*BaseNode) GetHeadComment

func (n *BaseNode) GetHeadComment() *CommentGroupNode

GetHeadComment returns what stands above the node. See BaseNode.HeadComment.

func (*BaseNode) GetPath

func (n *BaseNode) GetPath() string

GetPath returns the node's YAML Path, such as "$.a[0]", or "" for a nil node.

func (*BaseNode) GetPathNode

func (n *BaseNode) GetPathNode() *PathNode

GetPathNode returns the step of the path trie this node ends.

func (*BaseNode) SetComment

func (n *BaseNode) SetComment(node *CommentGroupNode) error

SetComment sets the comment after the node, on its line.

func (*BaseNode) SetHeadComment

func (n *BaseNode) SetHeadComment(node *CommentGroupNode) error

SetHeadComment records what stands above the node.

func (*BaseNode) SetPathNode

func (n *BaseNode) SetPathNode(p *PathNode)

SetPathNode records the step of the path trie this node ends.

type BoolNode

type BoolNode struct {
	BaseNode

	Token *token.Token
	Value bool
}

BoolNode is a boolean scalar, such as true or False.

func Bool

func Bool(tk *token.Token) *BoolNode

Bool returns a BoolNode for tk, holding the value tk spells.

func (*BoolNode) Bytes

func (n *BoolNode) Bytes() []byte

Bytes returns BoolNode.Text as bytes, without copying it.

func (*BoolNode) Clone

func (n *BoolNode) Clone() *BoolNode

func (*BoolNode) Fill

func (n *BoolNode) Fill(tk *token.Token)

Fill makes n the node Bool builds for tk, reusing n. It clears everything else n held, comments included.

func (*BoolNode) GetToken

func (n *BoolNode) GetToken() *token.Token

GetToken returns n.Token, the scalar as the document wrote it.

func (*BoolNode) GetValue

func (n *BoolNode) GetValue() any

GetValue returns the bool.

func (*BoolNode) IsMergeKey

func (n *BoolNode) IsMergeKey() bool

IsMergeKey returns false.

func (*BoolNode) String

func (n *BoolNode) String() string

String returns the boolean as the document wrote it, with its comment.

func (*BoolNode) Text

func (n *BoolNode) Text() string

Text returns the bool as the document wrote it, in the case it wrote it in.

func (*BoolNode) Type

func (n *BoolNode) Type() NodeType

Type returns BoolType.

type CommentGroupNode

type CommentGroupNode struct {
	BaseNode

	Comments []*CommentNode
}

CommentGroupNode holds the comments on one place of a node: the lines above it, or the comment after it.

func CommentGroup

func CommentGroup(comments []*token.Token) *CommentGroupNode

func TakeComment

func TakeComment(n Node) *CommentGroupNode

TakeComment hands over the comment standing on n and clears the slot, without recording the comment as removed from the document.

It is for a parse building a tree, where a comment read from the document is being put on the node it belongs to. To edit a parsed tree, use CommentNode.Replace or CommentNode.Remove instead: those keep the token that records which bytes of the source the comment stands on, and this drops it.

func (*CommentGroupNode) Blank

func (n *CommentGroupNode) Blank() bool

Blank reports whether n writes nothing: it is absent, holds no comment, or every comment in it has been removed.

A renderer calls Blank instead of testing the group against nil, or a group emptied by CommentNode.Remove leaves the space that was to stand in front of it.

func (*CommentGroupNode) Clone

func (n *CommentGroupNode) Clone() *CommentGroupNode

func (*CommentGroupNode) GetToken

func (n *CommentGroupNode) GetToken() *token.Token

GetToken returns the token of the first comment not removed, or nil.

func (*CommentGroupNode) Remove

func (n *CommentGroupNode) Remove()

Remove records that nothing in the group is written.

func (*CommentGroupNode) Replace

func (n *CommentGroupNode) Replace(text string) error

Replace records that the group renders as one comment reading "# " + text.

It is CommentNode.Replace on a group holding one comment, and a group holds one comment nearly everywhere: a run of comment lines above one node is the exception. It rejects a group holding several instead of guessing which one the caller meant.

func (*CommentGroupNode) SetComment

func (n *CommentGroupNode) SetComment(*CommentGroupNode) error

SetComment rejects a comment on a comment.

A group holds comments; it does not carry one. The parser puts a group where a node would stand for a document that holds nothing else -- "# c" over "..." -- and there is no line of its own for a second comment to close.

func (*CommentGroupNode) String

func (n *CommentGroupNode) String() string

String returns the comments not removed, one per line.

func (*CommentGroupNode) Type

func (n *CommentGroupNode) Type() NodeType

Type returns CommentType.

func (*CommentGroupNode) Visible

func (n *CommentGroupNode) Visible() []*CommentNode

Visible hands over the comments of n that are still written, in the order they stand. A comment CommentNode.Remove took out is skipped.

type CommentNode

type CommentNode struct {
	BaseNode

	Token *token.Token
	// contains filtered or unexported fields
}

CommentNode is one comment line, "# text".

func Comment

func Comment(tk *token.Token) *CommentNode

Comment returns a CommentNode for tk.

func (*CommentNode) Clone

func (n *CommentNode) Clone() *CommentNode

func (*CommentNode) GetToken

func (n *CommentNode) GetToken() *token.Token

GetToken returns n.Token, the comment as the document wrote it.

func (*CommentNode) Remove

func (n *CommentNode) Remove()

Remove records that n is not written at all.

The comment stays in the tree so that Renderer.VerbatimFile can find the bytes of the source to leave out. Setting the node's comment field to nil instead loses that and the old text comes back.

func (*CommentNode) Removed

func (n *CommentNode) Removed() bool

Removed reports whether n has been removed by CommentNode.Remove.

func (*CommentNode) Replace

func (n *CommentNode) Replace(text string) error

Replace records that n renders as "# " + text instead of what the document wrote.

text is the comment without its "#": CommentNode.String adds one, as it does for a parsed comment, whose token holds the text after the "#" as well. A line break in text would end the comment and put the rest of it into the document as content, so it is rejected here rather than at rendering time.

func (*CommentNode) String

func (n *CommentNode) String() string

String returns "#" and CommentNode.Text, or "" for a removed comment.

func (*CommentNode) Text

func (n *CommentNode) Text() string

Text returns the text n renders as, without the "#": the replacement where one was set, and the document's own words otherwise.

func (*CommentNode) Type

func (n *CommentNode) Type() NodeType

Type returns CommentType.

type DirectiveNode

type DirectiveNode struct {
	BaseNode

	// Start is '%' token.
	Start *token.Token
	// Name is directive name e.g.) "YAML" or "TAG".
	Name Node
	// Values is directive values e.g.) "1.2" or "!!" and "tag:clarkevans.com,2002:app/".
	Values []Node
}

DirectiveNode is a directive, such as "%YAML 1.2", above a document.

func Directive

func Directive(tk *token.Token) *DirectiveNode

func (*DirectiveNode) Clone

func (n *DirectiveNode) Clone() *DirectiveNode

func (*DirectiveNode) GetToken

func (n *DirectiveNode) GetToken() *token.Token

GetToken returns n.Start, the "%".

func (*DirectiveNode) String

func (n *DirectiveNode) String() string

String returns the directive line.

func (*DirectiveNode) Type

func (n *DirectiveNode) Type() NodeType

Type returns DirectiveType.

type DocumentNode

type DocumentNode struct {
	BaseNode

	Start *token.Token // position of DocumentHeader ( `---` )
	End   *token.Token // position of DocumentEnd ( `...` )
	Body  Node
	// StartComment is the comment closing the "---" line, and EndComment the
	// one closing the "..." line. Both are the marker's own: a comment written
	// *above* a "---" introduces the document and reaches its body, and a
	// comment on the body's last line is the body's.
	//
	// They are named rather than taken from the inherited BaseNode.Comment
	// because a document may carry both at once -- "--- # a" over a body over
	// "... # b" -- and one slot holds one of them. Nothing claimed either
	// before, so "--- # c1" rendered as "---" and the comment was read and
	// dropped.
	StartComment *CommentGroupNode
	EndComment   *CommentGroupNode
	// FootComment holds the comments written after the body, where the body has
	// no slot of its own for them: a scalar, a block scalar or a flow collection
	// at the root. "x" over "# note" holds "# note" here, and the renderer writes
	// it below the body, before any "...". A block mapping or sequence keeps the
	// comments after it in its own FootComment.
	//
	// They went to the body's own comment before, the slot of a comment on its
	// line, so "x" over "# note" rendered as "x # note", and "|" over "  text"
	// over "# note" as "| # note" over "  text".
	FootComment *CommentGroupNode
	// Anchors holds the node each anchor of this document names, under the
	// anchor's name. The parser fills it as it reads, so a caller walking the
	// tree as it is built sees the anchors that stand before it; it is nil for
	// a document that declares none.
	//
	// An anchor belongs to the document it was written in, so each document of
	// a stream carries its own. Where a name is declared twice the last
	// declaration is the one kept here -- read [AliasNode.Target] to expand a
	// particular alias, which names the declaration that stood before it.
	Anchors map[string]Node
	// Schema is the resolution the document's plain scalars were read against:
	// the version its "%YAML" line declares, or the parser's WithYAMLVersion
	// where it declares none. The zero value is [token.Schema12].
	//
	// A node carries no version of its own, so a reader that renders part of
	// the document for another parse reads it here: under 1.1, "yes" is true
	// and "<<" merges, and a fragment parsed again under 1.2 reads neither.
	Schema token.Schema
}

DocumentNode is one document of a stream: its "---", its body and its "...".

func Document

func Document(tk *token.Token, body Node) *DocumentNode

func (*DocumentNode) Clone

func (d *DocumentNode) Clone() *DocumentNode

func (*DocumentNode) GetToken

func (d *DocumentNode) GetToken() *token.Token

GetToken returns token instance.

It returns nil for a document with no content, such as the one an empty source produces: an empty document has no token to point at.

func (*DocumentNode) HoldsValue

func (d *DocumentNode) HoldsValue() bool

HoldsValue reports whether d denotes a value: any document but one of directives alone or of comments alone.

A document of directives opens their scope and denotes no value, and a source holding only comments is not a document at all. Everything else is one, including a tag or an anchor standing on nothing: "!!null" and "&a" denote null exactly as "~" does.

func (*DocumentNode) IsEmpty

func (d *DocumentNode) IsEmpty() bool

IsEmpty reports whether d holds no node and is a document all the same.

"---" opens a document and "..." closes one, so a document written with either marker exists whatever stands between them: "---\n...\n" holds the empty node, which is null. A run of comments carries no marker and is no document at all -- l-yaml-stream puts those in a document prefix -- so "# c\n" is not an empty document.

func (*DocumentNode) String

func (d *DocumentNode) String() string

String renders the document with the default Renderer.

func (*DocumentNode) Type

func (d *DocumentNode) Type() NodeType

Type returns DocumentType.

type DuplicateKey

type DuplicateKey struct {
	// Name is the key as its type spells it, and two keys with one Name are the
	// same key: token.KeyName writes an integer in decimal whatever base the
	// document used.
	Name string
	// At is the position of the repeat and FirstAt the position where the key
	// was first written, so an error can name both.
	At, FirstAt token.Position
	// NameOnly marks two keys that YAML holds distinct but that share a name:
	// "1" and "\"1\"" are an integer and a string, and both are named "1". A
	// reader that keys its entries by value, such as an any or a MapSlice,
	// holds both and reads no repeat; one that keys them by name, such as a
	// struct, a map[string]T or JSON, holds one. Every parse records one. See
	// [DuplicateKey.Repeats].
	NameOnly bool
	// JSONNameOnly marks a NameOnly repeat recorded by a parse under
	// parser.WithJSONCompatible, which requires a document JSON can hold.
	// Every reader rejects it, with ErrNotJSON.
	JSONNameOnly bool
	// Allowed marks a repeat the parse was told to allow, with
	// parser.WithAllowDuplicateMapKey. A load keeps one of the entries instead
	// of rejecting the document: a decoder filling a map keeps the last, a
	// converter writing JSON keeps the first.
	Allowed bool
	// Index is the position in the sequence of the "!!omap" entry that repeats
	// the key, for a repeat recorded on [SequenceNode.Duplicates]. It is 0 on a
	// mapping's record.
	Index int
}

DuplicateKey is one entry of a mapping whose key the mapping already held.

YAML 1.2.2 §3.2.1.1: two keys are equal when they resolve to the same node, so "7" and "007" are one key written twice while "1" and "1.0" are two. The parser records the repeats it finds and rejects none of them; whoever loads the document handles them, so a linter can read a document that a decoder rejects.

func FirstRefused

func FirstRefused(dups []DuplicateKey, byName bool) (DuplicateKey, bool)

FirstRefused returns the first of dups that a reader keying its entries by name, byName, or by value has to refuse: a repeat for that reader, which the parse did not allow.

func (DuplicateKey) Repeats

func (d DuplicateKey) Repeats(byName bool) bool

Repeats reports whether d repeats a key for a reader that keys its entries by name, byName, or by value. A repeat by name alone is one only for the first, unless the parse was asked for a document JSON can hold.

type File

type File struct {
	Name string
	Docs []*DocumentNode
	// contains filtered or unexported fields
}

File holds the documents of one YAML stream, in order.

func (*File) Read

func (f *File) Read(p []byte) (int, error)

Read renders the file and reads the text out, so that a parsed document may be handed to anything taking an io.Reader.

The text is taken once, at the first Read, and the documents are not looked at again until it runs out: a node changed while a read is running does not change what is left to read. Reading to io.EOF starts the next read from the top of the file as it stands then.

func (*File) String

func (f *File) String() string

String returns every document as text.

type FloatNode

type FloatNode struct {
	BaseNode

	Token *token.Token
}

FloatNode is a floating-point scalar, such as 1.5 or 6.02e23.

func Float

func Float(tk *token.Token) *FloatNode

Float returns a FloatNode for tk.

func (*FloatNode) Bytes

func (n *FloatNode) Bytes() []byte

Bytes returns FloatNode.Text as bytes, without copying it.

func (*FloatNode) Clone

func (n *FloatNode) Clone() *FloatNode

func (*FloatNode) Fill

func (n *FloatNode) Fill(tk *token.Token)

Fill makes n the node Float builds for tk, reusing n. It clears everything else n held, comments included.

func (*FloatNode) GetToken

func (n *FloatNode) GetToken() *token.Token

GetToken returns n.Token, the scalar as the document wrote it.

func (*FloatNode) GetValue

func (n *FloatNode) GetValue() any

GetValue reads the float and returns it as a float64, as a big.Float where the number reaches past what a float64 holds, or 0 where the text is not a float after all. A float whose decimal exponent is past ±1000 is an infinity of its sign, or zero: see token.FloatPastRange.

The parser types the scalar without converting it, so the conversion happens here, each time it is asked for. Use FloatNode.Text to read the number as the document wrote it.

func (*FloatNode) IsMergeKey

func (n *FloatNode) IsMergeKey() bool

IsMergeKey returns false.

func (*FloatNode) String

func (n *FloatNode) String() string

String returns the number as the document wrote it, with its comment.

func (*FloatNode) Text

func (n *FloatNode) Text() string

Text returns the float as the document wrote it.

func (*FloatNode) Type

func (n *FloatNode) Type() NodeType

Type returns FloatType.

type InfinityNode

type InfinityNode struct {
	BaseNode

	Token *token.Token
	Value float64
}

InfinityNode is an infinity: ".inf", "+.inf" or "-.inf", in any of the spellings Infinity accepts.

func Infinity

func Infinity(tk *token.Token) *InfinityNode

Infinity create node for .inf or -.inf value.

The 1.2 core schema's float production is `[-+]? ( \.inf | \.Inf | \.INF )`, so a "+" spells the same value the bare form does. Reading the sign instead of matching all nine spellings keeps this in step with the scanner's reservedInfKeywords, which lists them.

func (*InfinityNode) Bytes

func (n *InfinityNode) Bytes() []byte

Bytes returns InfinityNode.Text as bytes, without copying it.

func (*InfinityNode) Clone

func (n *InfinityNode) Clone() *InfinityNode

func (*InfinityNode) Fill

func (n *InfinityNode) Fill(tk *token.Token)

Fill makes n the node Infinity builds for tk, reusing n. It clears everything else n held, comments included.

func (*InfinityNode) GetToken

func (n *InfinityNode) GetToken() *token.Token

GetToken returns n.Token, the scalar as the document wrote it.

func (*InfinityNode) GetValue

func (n *InfinityNode) GetValue() any

GetValue returns math.Inf(0) or math.Inf(-1).

func (*InfinityNode) IsMergeKey

func (n *InfinityNode) IsMergeKey() bool

IsMergeKey returns false.

func (*InfinityNode) String

func (n *InfinityNode) String() string

String returns the infinity as the document wrote it, with its comment.

func (*InfinityNode) Text

func (n *InfinityNode) Text() string

Text returns the infinity as the document wrote it: ".inf" or "-.inf", in the case it wrote it in.

func (*InfinityNode) Type

func (n *InfinityNode) Type() NodeType

Type returns InfinityType.

type IntegerNode

type IntegerNode struct {
	BaseNode

	Token *token.Token
}

IntegerNode is an integer scalar, such as 42, 0x2a or 0o52.

func Integer

func Integer(tk *token.Token) *IntegerNode

Integer returns an IntegerNode for tk.

func (*IntegerNode) Bytes

func (n *IntegerNode) Bytes() []byte

Bytes returns IntegerNode.Text as bytes, without copying it.

func (*IntegerNode) Clone

func (n *IntegerNode) Clone() *IntegerNode

func (*IntegerNode) Fill

func (n *IntegerNode) Fill(tk *token.Token)

Fill makes n the node Integer builds for tk, reusing n. It clears everything else n held, comments included.

func (*IntegerNode) GetToken

func (n *IntegerNode) GetToken() *token.Token

GetToken returns n.Token, the scalar as the document wrote it.

func (*IntegerNode) GetValue

func (n *IntegerNode) GetValue() any

GetValue reads the integer and returns it as an int64 where the document wrote a sign, as a uint64 where it did not, and as a big.Int where neither holds it. It returns nil where the text is not an integer after all.

The parser types the scalar without converting it, so the conversion happens here, each time it is asked for. Use IntegerNode.Text to read the digits as the document wrote them.

func (*IntegerNode) IsMergeKey

func (n *IntegerNode) IsMergeKey() bool

IsMergeKey returns false.

func (*IntegerNode) String

func (n *IntegerNode) String() string

String returns the integer as the document wrote it, with its comment.

func (*IntegerNode) Text

func (n *IntegerNode) Text() string

Text returns the integer's digits as the document wrote them, with the base prefix and any '_' separators still in place.

func (*IntegerNode) Type

func (n *IntegerNode) Type() NodeType

Type returns IntegerType.

type InvalidMergeTypeError

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

func (*InvalidMergeTypeError) Error

func (e *InvalidMergeTypeError) Error() string

type KeyAlias

type KeyAlias func(*AliasNode) (string, token.KeyKind, bool)

KeyAlias names the key an alias stands for, and reports false where it cannot.

Each reader of a key resolves an alias its own way: KeyName through AliasNode.Target, the parser through the identities its anchors recorded, which a walk still holds once the anchored node is gone.

type LiteralNode

type LiteralNode struct {
	BaseNode

	Start *token.Token
	Value *StringNode
	// Source is the block as the document wrote it, indicators excluded: the
	// bytes from the end of Start to the end of Value, so the indentation of
	// the first content line is part of it.
	//
	// The parser fills it for a folded scalar and leaves it empty for a literal
	// one. Folding rewrites the line structure -- "a\nb" comes back as "a b" --
	// so a folded scalar can only be written out again from the text it was
	// read from; a literal scalar's value is its content exactly and needs no
	// source. A node built by hand rather than parsed has none either, and
	// renders as a literal.
	Source string
}

LiteralNode is a block scalar, literal ("|") or folded (">").

func Literal

func Literal(tk *token.Token) *LiteralNode

func (*LiteralNode) Bytes

func (n *LiteralNode) Bytes() []byte

Bytes returns LiteralNode.Text as bytes, without copying it.

func (*LiteralNode) Clone

func (n *LiteralNode) Clone() *LiteralNode

func (*LiteralNode) GetToken

func (n *LiteralNode) GetToken() *token.Token

GetToken returns n.Start, the block's header.

func (*LiteralNode) GetValue

func (n *LiteralNode) GetValue() any

GetValue returns the block scalar's content, folded and chomped as its header sets: "|" over " x" over " y" is "x\ny\n". Use LiteralNode.String for the block as it is written, header included.

func (*LiteralNode) IsMergeKey

func (n *LiteralNode) IsMergeKey() bool

IsMergeKey returns false.

func (*LiteralNode) String

func (n *LiteralNode) String() string

String returns the block scalar as written: its header, then its content.

func (*LiteralNode) Text

func (n *LiteralNode) Text() string

Text returns the block scalar's content, folded and chomped, or nothing where it has none.

func (*LiteralNode) Type

func (n *LiteralNode) Type() NodeType

Type returns LiteralType.

type MapKeyNode

type MapKeyNode interface {
	Node
	IsMergeKey() bool
	// contains filtered or unexported methods
}

MapKeyNode is a node that can stand as a mapping key.

type MapNode

type MapNode interface {
	// MapRange yields the key and the value of each entry, in order.
	MapRange() iter.Seq2[MapKeyNode, Node]
	// Entries yields each entry, in order. Use it where the entry's comments or its ':' token matter.
	Entries() iter.Seq[*MappingValueNode]
	// Len returns the number of entries.
	Len() int
}

MapNode is a node holding mapping entries: a MappingNode, a MappingValueNode or a SequenceMergeValueNode.

type MappingKeyNode

type MappingKeyNode struct {
	BaseNode

	Start *token.Token
	Value Node
}

MappingKeyNode is an explicit key: "?" and the key written after it.

func MappingKey

func MappingKey(tk *token.Token) *MappingKeyNode

MappingKey returns a MappingKeyNode for tk, a "?". Set its Value to the key.

func (*MappingKeyNode) Clone

func (n *MappingKeyNode) Clone() *MappingKeyNode

func (*MappingKeyNode) GetToken

func (n *MappingKeyNode) GetToken() *token.Token

GetToken returns n.Start, the "?".

func (*MappingKeyNode) IsMergeKey

func (n *MappingKeyNode) IsMergeKey() bool

IsMergeKey returns whether the key after the "?" is a merge key.

func (*MappingKeyNode) String

func (n *MappingKeyNode) String() string

String renders "? " and the key.

func (*MappingKeyNode) Type

func (n *MappingKeyNode) Type() NodeType

Type returns MappingKeyType.

type MappingNode

type MappingNode struct {
	BaseNode

	// Start is the '{' of a flow mapping, and the first entry's ':' of a block mapping: "a: 1" starts at column 2.
	// A block mapping whose first entry has no ':', as "? a", starts at its key's first token.
	//
	// A walk hands a block mapping to [github.com/go-openapi/go-yaml/parser.Visitor] Enter before its first entry is
	// read, so Start then holds the first token of that entry: the key, or the '?' of an explicit one. The parse sets
	// the ':' once the entry is read, and Leave sees it. Record the position at Enter to keep the one the reader sees
	// the mapping begin at.
	Start       *token.Token
	End         *token.Token
	IsFlowStyle bool
	// Duplicates holds the entries whose key the mapping already held, in the
	// order they were written, and those whose key it held by name alone, marked
	// [DuplicateKey.NameOnly]. It is nil for a mapping that repeats none, which
	// is nearly every mapping of nearly every document, so a document without
	// duplicates carries nothing for them.
	//
	// Where the parse was told to allow them with
	// [github.com/go-openapi/go-yaml/parser.WithAllowDuplicateMapKey], the
	// repeats are recorded all the same, each marked [DuplicateKey.Allowed], so
	// every load can tell which entry repeats and keep one.
	Duplicates []DuplicateKey
	Values     []*MappingValueNode
	// TrailingComma is the ',' after the last entry of a flow mapping, as in "{a: 1, }", or nil. The ',' before
	// every other entry is its [MappingValueNode.CollectEntry].
	TrailingComma *token.Token
	FootComment   *CommentGroupNode
	// StartComment is the comment closing the line the '{' stands on, as in
	// "{ # why\n  a: 1 }". Comment holds the one after the '}' instead, so a
	// flow mapping written with both keeps both.
	//
	// A block mapping opens on its first key and never fills this.
	StartComment *CommentGroupNode
}

MappingNode is a mapping, block or flow ("{a: 1}"), holding its entries in document order.

func Map

func Map(entries ...*MappingValueNode) *MappingNode

Map builds a block mapping of entries. Call MappingNode.SetIsFlowStyle for "{a: 1}".

func Mapping

func Mapping(tk *token.Token, isFlowStyle bool, values ...*MappingValueNode) *MappingNode

Mapping returns a MappingNode starting at tk and holding values.

func (*MappingNode) Clone

func (n *MappingNode) Clone() *MappingNode

func (*MappingNode) Entries

func (n *MappingNode) Entries() iter.Seq[*MappingValueNode]

Entries yields each entry of n, in order.

func (*MappingNode) GetToken

func (n *MappingNode) GetToken() *token.Token

GetToken returns n.Start: "{" for a flow mapping, the first key's token for a block one.

func (*MappingNode) IsMergeKey

func (n *MappingNode) IsMergeKey() bool

IsMergeKey returns whether it is a MergeKey node.

A collection is never one: "<<" is a scalar.

func (*MappingNode) Len

func (n *MappingNode) Len() int

Len returns the number of entries of n.

func (*MappingNode) MapRange

func (n *MappingNode) MapRange() iter.Seq2[MapKeyNode, Node]

MapRange yields the key and the value of each entry of n, in order.

func (*MappingNode) Merge

func (n *MappingNode) Merge(target *MappingNode)

Merge adds the entries of target to n. An entry whose key String matches one of n takes that entry's value instead.

func (*MappingNode) SetIsFlowStyle

func (n *MappingNode) SetIsFlowStyle(isFlow bool)

SetIsFlowStyle sets IsFlowStyle on n and on every entry under it.

func (*MappingNode) String

func (n *MappingNode) String() string

String renders the mapping values to text.

func (*MappingNode) Type

func (n *MappingNode) Type() NodeType

Type returns MappingType.

type MappingValueNode

type MappingValueNode struct {
	BaseNode

	// Start is the ':' token. An entry written with no ':', a flow key alone as in "{a}" or an explicit key with
	// nothing after it, holds its key's first token instead, so that the entry still has a position.
	Start        *token.Token
	CollectEntry *token.Token // collect entry token ','.
	Key          MapKeyNode
	Value        Node
	// LineComment is the comment written on the entry's own ':' line, where
	// that line carries nothing else: "? k" over ": # c".
	//
	// An entry written the short way has nowhere to put such a comment but the
	// value, since "a: # c" over "  v" writes the comment on the key's line --
	// and that works, because the value node's own slot is free. An entry
	// written the long way has a ':' on a line of its own, and the comment
	// there is neither the key's nor the value's: on the value it becomes a
	// head comment and collides with one written under the ':', and on
	// BaseNode.Comment it collides with one written above the '?'.
	//
	// ⚠️ [SequenceEntryNode] names HeadComment and reads its *line* comment
	// through the inherited accessor; this type does the reverse, naming the
	// line comment and reading its head one through BaseNode.Comment. The two
	// are consistent in having two slots and inconsistent in which one is
	// named. Renaming BaseNode.Comment reaches every node type, so the
	// asymmetry stands rather than being worth that.
	LineComment *CommentGroupNode
	FootComment *CommentGroupNode
	IsFlowStyle bool
}

MappingValueNode is one entry of a mapping: a key, its ":" and its value.

func Entry

func Entry(name string, value Node) *MappingValueNode

Entry builds a mapping entry with the string key name, quoted as Text quotes it.

Use MappingValue for a key that is not a plain string: an integer, a "?" key, a collection.

func Lookup

func Lookup(node Node, name string) *MappingValueNode

Lookup returns the entry of node whose key is name, and nil where node holds no such key.

node is a mapping, or an anchor, a tag or an alias standing on one: a value read from a document carries whatever the document wrote in front of it, and an alias is followed through AliasNode.Target.

Keys are compared by KeyName, so a quoted key matches its text and "1" and 1 are one name. A "<<" brings keys in from elsewhere and Lookup does not read them; use LookupMerged for that.

func LookupIn

func LookupIn(mapping MapNode, name string) *MappingValueNode

LookupIn is Lookup over a mapping already in hand, such as one of MergeEntry.Sources.

func LookupMerged

func LookupMerged(node Node, name string) *MappingValueNode

LookupMerged returns the entry of node whose key is name, reading the mappings a "<<" brings in where node itself does not write the key.

The mapping's own keys win, and among the merged ones an earlier "<<" beats a later one, which is what the merge type requires. A merged mapping may merge in turn, and is read the same way.

func MappingValue

func MappingValue(tk *token.Token, key MapKeyNode, value Node) *MappingValueNode

MappingValue returns a MappingValueNode for key and value, with tk as its ":".

func (*MappingValueNode) Clone

func (n *MappingValueNode) Clone() *MappingValueNode

func (*MappingValueNode) Entries

func (n *MappingValueNode) Entries() iter.Seq[*MappingValueNode]

Entries yields n, as its only entry.

func (*MappingValueNode) GetToken

func (n *MappingValueNode) GetToken() *token.Token

GetToken returns n.Start, the ":".

func (*MappingValueNode) Len

func (n *MappingValueNode) Len() int

Len returns 1: n is a single entry.

func (*MappingValueNode) MapRange

func (n *MappingValueNode) MapRange() iter.Seq2[MapKeyNode, Node]

MapRange yields the key and the value of n, as its only entry.

func (*MappingValueNode) Replace

func (n *MappingValueNode) Replace(value Node) error

Replace sets value as the entry's value. It returns nil.

func (*MappingValueNode) SetIsFlowStyle

func (n *MappingValueNode) SetIsFlowStyle(isFlow bool)

SetIsFlowStyle sets IsFlowStyle on n and on every collection in its value, under an anchor or a tag too.

func (*MappingValueNode) String

func (n *MappingValueNode) String() string

String returns the entry as text: key, ":" and value.

func (*MappingValueNode) Type

func (n *MappingValueNode) Type() NodeType

Type returns MappingValueType.

type Mark

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

Mark records an arena's position, taken by Arena.Mark and given back to Arena.Rewind.

type MergeEntry

type MergeEntry struct {
	// Verdict is one of [NotAMerge], [Folds] and [Refused].
	Verdict Verdict
	// Sources are the mappings to fold, in the order they win: an earlier
	// mapping of a "<<" sequence beats a later one. It is nil unless Verdict is
	// [Folds].
	Sources []MapNode
	// Offender is the node a "<<" cannot fold, and is nil unless Verdict is
	// [Refused].
	//
	// Offender holds the node instead of an error because each caller words the
	// failure differently -- the parser reports a position, the decoder reports
	// a Go type it cannot fill -- and errors imports ast, so ast cannot import
	// errors.
	Offender Node
}

MergeEntry records what one "<<" entry contributes to the mapping holding it.

It is not named Merge: Merge already folds one tree into another, which is a different operation on the same word.

func MergeOf

func MergeOf(entry *MappingValueNode) MergeEntry

MergeOf reads what a mapping entry contributes to the mapping holding it.

It accepts every entry, not only a "<<", and returns NotAMerge for an ordinary key. A caller calls it once per entry and switches on the verdict, instead of testing the key and then working out what the test implied.

It takes no schema. The parser settles which spellings of "<<" merge, by building a MergeKeyNode or an ordinary key. Checking again here would repeat that choice with less context, since a tag handle is expanded by the parser and a node does not carry the version it was read under.

MergeOf does not apply precedence either. The merge type gives a mapping's own keys precedence over the ones a "<<" brings in, which is a rule about the mapping and not about the entry, so a caller reads its own entries first and writes a merged key only where none stands. MergeEntry.Sources is ordered so that reading them in turn and keeping the first writer gives the earlier-wins rule for free.

type MergeKeyNode

type MergeKeyNode struct {
	BaseNode

	Token *token.Token
}

MergeKeyNode is the "<<" key of a merge.

func MergeKey

func MergeKey(tk *token.Token) *MergeKeyNode

MergeKey returns a MergeKeyNode for tk, a "<<".

func (*MergeKeyNode) Bytes

func (n *MergeKeyNode) Bytes() []byte

Bytes returns MergeKeyNode.Text as bytes, without copying it.

func (*MergeKeyNode) Clone

func (n *MergeKeyNode) Clone() *MergeKeyNode

func (*MergeKeyNode) GetToken

func (n *MergeKeyNode) GetToken() *token.Token

GetToken returns n.Token, the scalar as the document wrote it.

func (*MergeKeyNode) GetValue

func (n *MergeKeyNode) GetValue() any

GetValue returns the key's text, "<<".

func (*MergeKeyNode) IsMergeKey

func (n *MergeKeyNode) IsMergeKey() bool

IsMergeKey returns true.

func (*MergeKeyNode) String

func (n *MergeKeyNode) String() string

String returns "<<".

func (*MergeKeyNode) Text

func (n *MergeKeyNode) Text() string

Text returns "<<".

func (*MergeKeyNode) Type

func (n *MergeKeyNode) Type() NodeType

Type returns MergeKeyType.

type NanNode

type NanNode struct {
	BaseNode

	Token *token.Token
}

NanNode is a not-a-number: ".nan", ".NaN" or ".NAN".

func Nan

func Nan(tk *token.Token) *NanNode

Nan returns a NanNode for tk.

func (*NanNode) Bytes

func (n *NanNode) Bytes() []byte

Bytes returns NanNode.Text as bytes, without copying it.

func (*NanNode) Clone

func (n *NanNode) Clone() *NanNode

func (*NanNode) Fill

func (n *NanNode) Fill(tk *token.Token)

Fill makes n the node Nan builds for tk, reusing n. It clears everything else n held, comments included.

func (*NanNode) GetToken

func (n *NanNode) GetToken() *token.Token

GetToken returns n.Token, the scalar as the document wrote it.

func (*NanNode) GetValue

func (n *NanNode) GetValue() any

GetValue returns math.NaN().

func (*NanNode) IsMergeKey

func (n *NanNode) IsMergeKey() bool

IsMergeKey returns false.

func (*NanNode) String

func (n *NanNode) String() string

String returns the value as the document wrote it, with its comment.

func (*NanNode) Text

func (n *NanNode) Text() string

Text returns the not-a-number as the document wrote it, in the case it wrote it in.

func (*NanNode) Type

func (n *NanNode) Type() NodeType

Type returns NanType.

type Node

type Node interface {
	// String node to text
	String() string
	// GetToken returns token instance
	GetToken() *token.Token
	// Type returns type of node
	Type() NodeType
	// SetComment set comment token to node
	SetComment(comment *CommentGroupNode) error
	// Comment returns comment token instance
	GetComment() *CommentGroupNode
	// GetPath returns YAMLPath for the current node
	GetPath() string
	// GetPathNode returns the step of the path trie this node ends
	GetPathNode() *PathNode
	// SetPathNode records the step of the path trie this node ends
	SetPathNode(path *PathNode)
}

Node is any node of the tree a parse builds.

func Clone

func Clone(n Node) Node

Clone returns a copy of n that the document does not hold.

Use it to put a parsed node somewhere else in the tree. A node read from a document is written back by copying the bytes it was read from, and that copy runs forward through the document once, so a node is written once and where the document wrote it. A node reached from a second place has no source ahead of the copy and is written as nothing; a node moved leaves its bytes where they were. A clone claims no source, so Renderer.Verbatim lays it out where it was put, the way it does a node built by hand.

The copy owns its own tokens and comments. Two things are carried as they are, being references to nodes the clone does not own: AliasNode.Target and DocumentNode.Anchors. The path Node.GetPath returns is dropped, since it names where the original stood and not where the copy is going: GetPath returns "" on every node of the copy. Use Node.SetPathNode to give a copy a path.

func Filter

func Filter(typ NodeType, node Node) []Node

Filter returns a list of nodes that match the given type.

func FilterFile

func FilterFile(typ NodeType, file *File) []Node

FilterFile returns a list of nodes that match the given type.

func Parent

func Parent(root, child Node) Node

Parent returns the node under root that holds child, and nil where no node under root holds it.

child is matched by identity, so hand back the node itself and not a copy or another node spelling the same text. Parent(root, root) returns root.

Use Parent where a document names one of its own parts and the caller has to put that part where the reference stands: GitLab CI's "!reference" is the worked case, in this package's examples. The reference is found anywhere in the document, so the caller needs the sequence or mapping it was written in before it can splice, and only a search from the root finds that.

Two things this costs. Parent descends the tree from root on every call, so resolving N references costs N descents. And the whole tree has to stand at once: a visitor driven by parser.Walk holds only what it cloned at Leave, because the parse reuses the node cells behind it, so there is no root to search from. Parse the document into a tree for this.

Comments are not searched. Nothing inside a CommentGroupNode is reached, and a SequenceNode is descended by its Values and not its Entries.

func Unwrap

func Unwrap(n Node) Node

Unwrap returns the node n stands for, past the anchors and tags written on it, the "?" of an explicit key, and an alias's target. It returns nil where the chain ends on nothing: "&a" alone, "? " alone, an alias with no target.

Use it to ask what kind of node a property names: "&a !!map {k: v}" unwraps to the mapping. A tag's type is lost on the way, so a question about the type goes to TagNode.Resolve first.

A chain longer than 64 properties and aliases returns nil. An alias is followed, so a chain can be a cycle: "&a *a" names itself.

type NodeType

type NodeType int

NodeType names the kind of a Node, as its Type method returns it.

const (
	// UnknownNodeType type identifier for default.
	UnknownNodeType NodeType = iota
	// DocumentType type identifier for document node.
	DocumentType
	// NullType type identifier for null node.
	NullType
	// BoolType type identifier for boolean node.
	BoolType
	// IntegerType type identifier for integer node.
	IntegerType
	// FloatType type identifier for float node.
	FloatType
	// InfinityType type identifier for infinity node.
	InfinityType
	// NanType type identifier for nan node.
	NanType
	// StringType type identifier for string node.
	StringType
	// MergeKeyType type identifier for merge key node.
	MergeKeyType
	// LiteralType type identifier for literal node.
	LiteralType
	// MappingType type identifier for mapping node.
	MappingType
	// MappingKeyType type identifier for mapping key node.
	MappingKeyType
	// MappingValueType type identifier for mapping value node.
	MappingValueType
	// SequenceType type identifier for sequence node.
	SequenceType
	// SequenceEntryType type identifier for sequence entry node.
	SequenceEntryType
	// AnchorType type identifier for anchor node.
	AnchorType
	// AliasType type identifier for alias node.
	AliasType
	// DirectiveType type identifier for directive node.
	DirectiveType
	// TagType type identifier for tag node.
	TagType
	// CommentType type identifier for comment node.
	CommentType
	// CommentGroupType type identifier for comment group node.
	CommentGroupType
)

func (NodeType) String

func (t NodeType) String() string

String returns the type's Go name, such as "Mapping".

func (NodeType) YAMLName

func (t NodeType) YAMLName() string

YAMLName returns the YAML structure name of the node type, based on https://yaml.org/spec/1.2/spec.html

type NullNode

type NullNode struct {
	BaseNode

	Token *token.Token
}

NullNode is a null: "null", "~", "Null", "NULL", or nothing at all where a value is due.

func Null

func Null(tk *token.Token) *NullNode

Null returns a NullNode for tk.

func (*NullNode) Bytes

func (n *NullNode) Bytes() []byte

Bytes returns NullNode.Text as bytes, without copying it: nil where the document left the value out.

func (*NullNode) Clone

func (n *NullNode) Clone() *NullNode

func (*NullNode) Fill

func (n *NullNode) Fill(tk *token.Token)

Fill makes n the node Null builds for tk, reusing n. It clears everything else n held, comments included.

func (*NullNode) GetToken

func (n *NullNode) GetToken() *token.Token

GetToken returns n.Token, the scalar as the document wrote it.

func (*NullNode) GetValue

func (n *NullNode) GetValue() any

GetValue returns nil.

func (*NullNode) IsMergeKey

func (n *NullNode) IsMergeKey() bool

IsMergeKey returns false.

func (*NullNode) SetComment

func (n *NullNode) SetComment(node *CommentGroupNode) error

SetComment records a comment on n, and rejects a comment of a caller's own on a null the document did not write.

An implicit null stands for a node that is not in the source: the value of "a:" with nothing after it, the entry of a bare "-". A comment the parser hangs there is a comment the document did write -- "k: # note" holds the note on the null -- and it is copied back from the bytes it was read from. One a caller adds has no bytes and nowhere to go: Renderer.Verbatim would lay the null out as though it had been inserted, so "- " over "- 1" would come back with an entry that was never there, reading [nil nil 1] where the document holds [nil 1].

A null a caller built, and one the document spells out, both take a comment: SetComment rejects only an implicit one, and only for a comment with no source of its own.

func (*NullNode) String

func (n *NullNode) String() string

String returns the null as the document spelled it.

func (*NullNode) Text

func (n *NullNode) Text() string

Text returns the null as it was written: "null", "~", or nothing at all where the document left the value out.

The scanner gives the token of a value left out the text "null", which Text does not return.

func (*NullNode) Type

func (n *NullNode) Type() NodeType

Type returns NullType.

type PathNode

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

PathNode is one step of a node's YAMLPath, pointing at the step above it.

Every node under one mapping key shares that key's PathNode, and a nested key gets a new one pointing at it, so a document's paths form a trie of 32-byte steps rather than one string for every node. On a 544 KB OpenAPI specification that is 454 KB against 2.37 MB.

BaseNode.GetPath renders a node's steps when asked and does not keep the result, so a caller reading the same path repeatedly should hold on to it. github.com/go-openapi/go-yaml/parser.Parser.Parse records these unless github.com/go-openapi/go-yaml/parser.WithOmitNodePaths is passed, and github.com/go-openapi/go-yaml/parser.Parser.Walk only under github.com/go-openapi/go-yaml/parser.WithNodePaths.

func (*PathNode) Index

func (p *PathNode) Index(parent *PathNode, idx uint)

Index makes p the step into a sequence at idx, below parent.

idx is held as an int32. A sequence long enough to overflow one cannot be held in memory to begin with.

func (*PathNode) Key

func (p *PathNode) Key(parent *PathNode, key string)

Key makes p the step into a mapping under key, below parent.

func (*PathNode) Literal

func (p *PathNode) Literal(path string)

Literal makes p a whole path, written out as path.

func (*PathNode) String

func (p *PathNode) String() string

String renders the path ending at this step.

type RenderOption

type RenderOption func(*Renderer)

RenderOption configures a Renderer.

func WithAliasTargets

func WithAliasTargets(anchors map[string]Node) RenderOption

WithAliasTargets renders each alias as the node its anchor names, taking the nodes from anchors keyed by anchor name and otherwise from AliasNode.Target, which the parser fills. Without this option an alias renders as the reference it was written as, "*name", which is also what an alias with neither falls back to.

Pass an empty map to resolve from the tree alone. The map is for a tree built by hand, and for anchors that came from somewhere else: the decoder passes the ones it has collected so that a custom UnmarshalYAML receives the value an alias stands for instead of a reference it has no way to look up.

func WithComments

func WithComments(on bool) RenderOption

WithComments controls whether comments are written. They are, by default.

func WithIndent

func WithIndent(spaces int) RenderOption

WithIndent sets how many spaces one level of nesting adds. Values below one are ignored: YAML block structure needs at least one space to exist.

func WithIndentSequence

func WithIndentSequence(on bool) RenderOption

WithIndentSequence controls whether a block sequence under a mapping key is indented beneath it. It is not, by default, which is the customary YAML layout and what this library has always emitted.

func WithSource

func WithSource(src []byte) RenderOption

WithSource gives a renderer the document a tree was parsed from. Renderer.Verbatim copies that document back out.

Rendering without it lays a tree out by its depth, as every other method here does and as an encoder needs. Rendering with it puts a document back the way it was written.

src must be the document the tree was parsed from. A token records the offsets a scanner cut it at, not which document it came from, so the renderer cannot tell another document's node from this one's. One that reaches past the end of src returns ErrNotInSource. One whose offsets fall inside src is read as this document's text, and the copy passes over it: the edit is lost and no error says so. Put a Clone of a node from another parse in the tree instead: a copy carries no offsets, and the renderer lays it out from the tree.

func WithTransform

func WithTransform(fn TransformFunc) RenderOption

WithTransform hands each stretch of a rendering to fn instead of writing it.

⚠️ It applies to Renderer.Verbatim and Renderer.VerbatimFile. The depth-driven renderer builds its text before it places any of it, so there is no stretch to hand over.

type Renderer

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

Renderer turns an AST back into YAML text.

It is a type, not a String method, so that callers can configure it and drive it -- the encoder uses this same renderer instead of building a tree and then shifting every token's column to fake indentation.

Indentation comes from depth in the tree, not from the positions recorded when the document was read. Those positions describe where a node was, which stops being true the moment anything is edited, and re-reading text laid out from stale positions produced a document that drifted a little further on every cycle. Rendering here reaches a fixed point after one pass.

func NewRenderer

func NewRenderer(opts ...RenderOption) *Renderer

NewRenderer returns a Renderer with two-space indentation and comments on.

func (*Renderer) File

func (r *Renderer) File(n *File) string

File renders a whole file. It is separate from String because *File is not a Node -- it holds documents and is not one.

func (*Renderer) Render

func (r *Renderer) Render(w io.Writer, n Node) error

Render writes n to w.

func (*Renderer) Stream

func (r *Renderer) Stream(w io.Writer) *Stream

Stream returns a Stream writing one document to w with r's settings.

func (*Renderer) String

func (r *Renderer) String(n Node) string

String renders n and returns the text.

The result is relative to nothing: the node's own first line carries no indentation, and everything nested under it is indented from there. A caller placing the result somewhere indented adds that indentation itself.

The first line starts in column 0, so a plain scalar there opening with "---" or "..." comes out quoted, as it does at the top of a document: written plain, it reads back as a document marker.

func (*Renderer) Verbatim

func (r *Renderer) Verbatim(w io.Writer, n Node) error

Verbatim writes n as the document it was parsed from wrote it, laying out any node the source does not reach.

It needs WithSource. A node a caller inserted into a parsed tree is written by Renderer.Render's rules and placed with its neighbours' indentation, so a document keeps its own layout everywhere it was not touched.

A caller may also assign over a node the document holds: MappingValueNode.Key, MappingValueNode.Value and DocumentNode.Body are written in place of what was there. Assigning to MappingNode.Values[i] or SequenceNode.Values[i] removes the entry that was there and inserts the new one in its place, the lines of the old one going with it.

A comment the parser attached to the node being replaced goes with it.

"a: 1 # note" holds the note on the value, so replacing the value drops
it; set it on the node being put in to keep it.

Comments are edited in place. A comment the document wrote is changed with CommentNode.Replace and taken out with CommentNode.Remove, both of which keep the token recording which bytes of the source it stands on; assigning another group over it throws that away, and Node.SetComment rejects it. Setting a comment where the document wrote none adds one, written above the node or at the end of its line by the slot it was put in.

An added comment is never dropped silently. Node.SetComment rejects a slot that can hold nothing: a null standing for a node the document does not hold, and a CommentGroupNode, which holds comments and carries none of its own.

Where the node's line has no room for one -- it ends on a comment already, or a scalar written across two lines runs through the end of it -- the comment goes above the node instead: "a: 1 # old" with a comment set on the key comes back as "# c" over "a: 1 # old". A group of more than one line set beside a block scalar goes above the line its header stands on, since the line below is content: "k: |" with "# c" and "# d" comes back as "# c" over "# d" over "k: |". Only where it can go neither place, the node beginning partway along a line, does this return an error naming it. So a tree that parsed cleanly can fail to render once a caller has added a comment to it; Renderer.Render lays the same tree out by depth and places the comment.

A node taken out of the tree is left out: removing a mapping entry, a sequence entry or a document drops its lines, the comments above it with them. The copy runs forward once, in the document's order, so it cannot write the nodes in another: a tree holding them in a different order returns ErrMove, and a node removed from inside a line -- an entry of a flow collection -- returns ErrRemove.

On an error, how much was written to w is not defined. The copy hands each stretch to w as it reaches it, so ErrMove, ErrRemove and ErrInsert stop partway through a document that is already partly written. Render into a buffer and copy it on success where a caller needs all or nothing.

Renderer.Render does not copy the source: it lays a whole tree out by its depth, as an encoder needs and as a tree with no source requires.

func (*Renderer) VerbatimFile

func (r *Renderer) VerbatimFile(w io.Writer, f *File) error

VerbatimFile writes a whole file back as it was read, the text around its documents included.

On an error, how much was written to w is not defined, as in Renderer.Verbatim.

type Resolution

type Resolution struct {
	// Tag is the type the tag names. It is "" where Verdict is TagUnresolved.
	Tag token.ReservedTagKeyword
	// Verdict records whether the node under the tag has the type the tag names.
	Verdict TagVerdict
	// Text holds the characters of the scalar under the tag, before the schema
	// read anything into them: "!!str 0x10" carries "0x10" and not "16". It is ""
	// where the node is not a scalar.
	Text string
	// Schema is the scalar schema the document is read under, from
	// [TagNode.Schema]. Read it with
	// [github.com/go-openapi/go-yaml/token.IntegerBase] or
	// [github.com/go-openapi/go-yaml/token.FloatBase] to take Text's digits in
	// the base the document wrote them in: "017" is octal under %YAML 1.1 and
	// decimal without it.
	//
	// Do not read Text under one fixed schema. Three consumers did and
	// disagreed: under 1.1 "!!int 0b101" decoded to 5 and ToJSON wrote 0.
	Schema token.Schema
	// Lax reports whether the document was read with
	// [github.com/go-openapi/go-yaml/parser.WithLaxTags]. A consumer that finds
	// TagValueMismatch and can fall back reads Text as a string instead of
	// rejecting the document; a kind mismatch is an error whatever Lax holds,
	// since no text stands in for a sequence.
	Lax bool
	// Empty reports whether the tag has no text under it: the document left the
	// node out as in "k: !!int", or wrote an empty scalar. Such a node takes the
	// tag's own default instead of failing to read.
	//
	// Both spellings land here because the parser writes the missing node two
	// ways -- handNull builds a null where the document ends, and
	// newTagDefaultScalarValueNode builds the tag's default value where it does
	// not -- and a caller reading a tagged node should not have to tell them
	// apart.
	Empty bool
}

Resolution holds the result of TagNode.Resolve for a tag and the node it stands on.

type ScalarNode

type ScalarNode interface {
	MapKeyNode
	GetValue() any
	// Text returns the scalar as text, unconverted: the digits of a number as
	// the document wrote them, a quoted string with its quotes and escapes
	// resolved, a block scalar folded and chomped. Text leaves the conversion of
	// a number to the caller.
	Text() string
	// Bytes returns Text as bytes, without copying it. See [token.TextBytes]
	// for what a caller may do with them.
	Bytes() []byte
}

ScalarNode is a node with one value, as ScalarNode.GetValue returns it.

type SequenceEntryNode

type SequenceEntryNode struct {
	BaseNode

	HeadComment *CommentGroupNode // head comment.
	LineComment *CommentGroupNode // line comment e.g.) - # comment.
	Start       *token.Token      // entry token.
	Value       Node              // value node.
}

SequenceEntryNode is one entry of a block sequence: its "-" and the value after it.

func SequenceEntry

func SequenceEntry(start *token.Token, value Node, headComment *CommentGroupNode) *SequenceEntryNode

SequenceEntry returns a SequenceEntryNode for the "-" start, its value and the comments above it.

func (*SequenceEntryNode) Clone

func (*SequenceEntryNode) GetComment

func (n *SequenceEntryNode) GetComment() *CommentGroupNode

GetComment returns the comment on the "-" line.

func (*SequenceEntryNode) GetToken

func (n *SequenceEntryNode) GetToken() *token.Token

GetToken returns n.Start, the "-".

func (*SequenceEntryNode) SetComment

func (n *SequenceEntryNode) SetComment(cm *CommentGroupNode) error

SetComment sets the comment on the "-" line. It returns nil.

func (*SequenceEntryNode) String

func (n *SequenceEntryNode) String() string

String renders the entry as a block sequence of one: "- " and its value, with the comment above the entry and the one on its "-" line.

func (*SequenceEntryNode) Type

func (n *SequenceEntryNode) Type() NodeType

Type returns SequenceEntryType.

type SequenceMergeValueNode

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

SequenceMergeValueNode ranges over the mappings of a merge sequence ("<<: [*a, *b]") as one MapNode.

func SequenceMergeValue

func SequenceMergeValue(values ...MapNode) *SequenceMergeValueNode

SequenceMergeValue returns a SequenceMergeValueNode over values.

func (*SequenceMergeValueNode) Entries

Entries yields each entry of every mapping, in order.

func (*SequenceMergeValueNode) Len

func (n *SequenceMergeValueNode) Len() int

Len returns the number of entries of every mapping.

func (*SequenceMergeValueNode) MapRange

MapRange yields the key and the value of each entry of every mapping, in order.

type SequenceNode

type SequenceNode struct {
	BaseNode

	Start             *token.Token
	End               *token.Token
	IsFlowStyle       bool
	Values            []Node
	ValueHeadComments []*CommentGroupNode
	Entries           []*SequenceEntryNode
	// Commas holds, for a flow sequence, the ',' written before each value, read by index as Values is: nil for the
	// first value and for a value a caller put in, and short of Values where values were appended. The parse fills
	// it with or without [github.com/go-openapi/go-yaml/parser.WithComments], which Entries needs.
	Commas []*token.Token
	// TrailingComma is the ',' after the last value of a flow sequence, as in "[a, ]", or nil.
	TrailingComma *token.Token
	FootComment   *CommentGroupNode
	// StartComment is the comment closing the line the '[' stands on, as in
	// "[ # why\n  a ]". Comment holds the one after the ']' instead, so a flow
	// sequence written with both keeps both.
	//
	// A block sequence opens on the '-' of its first entry, where a comment
	// belongs to that entry, and never fills this.
	StartComment *CommentGroupNode
	// Duplicates holds, for the sequence an "!!omap" tag stands on, the entries
	// whose key an earlier entry already wrote, in the order they were written.
	// [DuplicateKey.Index] names the entry. It is nil for every other sequence.
	//
	// The YAML 1.1 type repository holds an ordered map's keys to being unique
	// as it holds a mapping's, and each entry is a mapping of its own, so a
	// repeat across entries shows on no [MappingNode.Duplicates].
	Duplicates []DuplicateKey
}

SequenceNode is a sequence, block or flow ("[a, b]").

func Seq

func Seq(values ...Node) *SequenceNode

Seq builds a block sequence of values. Call SequenceNode.SetIsFlowStyle for "[a, b]".

func Sequence

func Sequence(tk *token.Token, isFlowStyle bool) *SequenceNode

Sequence returns an empty SequenceNode starting at tk.

func (*SequenceNode) ArrayRange

func (n *SequenceNode) ArrayRange() iter.Seq[Node]

ArrayRange yields each value of n, in order.

func (*SequenceNode) Clone

func (n *SequenceNode) Clone() *SequenceNode

func (*SequenceNode) GetToken

func (n *SequenceNode) GetToken() *token.Token

GetToken returns n.Start: "[" for a flow sequence, the first "-" for a block one.

func (*SequenceNode) Insert

func (n *SequenceNode) Insert(idx int, values ...Node) error

Insert puts values into the sequence before the value standing at idx, and appends them where idx is len(Values). It returns an error where idx is outside [0, len(Values)], and does nothing where no value is passed.

A parsed sequence carries Entries and ValueHeadComments beside Values, one per value and read by index, so Insert grows those too and leaves a nil for each inserted node: nothing wrote it in the source, and Renderer lays it out from the tree. Both stay empty where the parse left them empty, as they are for a sequence built with Seq.

An inserted node has no place in the source, so Renderer.Verbatim returns ErrMove for a node taken from elsewhere in the document. Pass Clone of it.

func (*SequenceNode) IsMergeKey

func (n *SequenceNode) IsMergeKey() bool

IsMergeKey returns whether it is a MergeKey node.

A collection is never one: "<<" is a scalar.

func (*SequenceNode) Len

func (n *SequenceNode) Len() int

Len returns the number of values of n.

func (*SequenceNode) Merge

func (n *SequenceNode) Merge(target *SequenceNode)

Merge appends the values of target to n.

The head comments of target go with its values. Where only one side holds any, the other side's values get none, and where neither does, n keeps none.

func (*SequenceNode) Remove

func (n *SequenceNode) Remove(idx int) error

Remove takes the value standing at idx out of the sequence, and returns an error where idx is outside it.

The entry it was written as and the head comment above it go with it, so what the document wrote for that value is gone and the values after it keep their own. Remove and SequenceNode.Insert are how a caller splices: put the new values in at idx, then remove the old one from idx+len(values).

func (*SequenceNode) Replace

func (n *SequenceNode) Replace(idx int, value Node) error

Replace puts value where the value at idx stands, and returns an error where idx is outside the sequence.

The value replaced is the only thing that changes: the entry it was written as and the head comment above it stay where they are, so a document renders with its layout and its comments and the new value in place. Use Clone for a value taken from elsewhere in the same document, for which Renderer.Verbatim otherwise returns ErrMove.

func (*SequenceNode) SetIsFlowStyle

func (n *SequenceNode) SetIsFlowStyle(isFlow bool)

SetIsFlowStyle sets IsFlowStyle on n and on every collection under it, under an anchor or a tag too.

func (*SequenceNode) String

func (n *SequenceNode) String() string

String renders the sequence to text.

func (*SequenceNode) Type

func (n *SequenceNode) Type() NodeType

Type returns SequenceType.

type Stream

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

Stream writes one document in block style as its caller hands it over, a collection boundary or a scalar at a time, and keeps nothing behind what it has written.

It writes what Renderer.Render writes for the same document built as a tree, every collection in block style and no comments, with the Renderer's WithIndent and WithIndentSequence. A key past 1,024 characters is written as an explicit "? " key, as the Renderer writes it. Each scalar goes through the Renderer's own scalar path, so the node sets its style: plain, quoted, or a "|" block.

Call Stream.BeginMapping or Stream.BeginSequence to open a collection, Stream.Key then Stream.Value or a Begin call for each entry of a mapping, Stream.Value or a Begin call for each entry of a sequence, and Stream.End to close the collection. A document whose node is a scalar is a single Stream.Value. Then call Stream.Close, which ends the last line.

A key must be a scalar. A collection written as a key returns ErrStreamOrder.

An empty collection is written "{}" or "[]", on the line of its key or its "- ". The stream writes a collection's key or "- " when the first entry arrives, which is the one event of lookahead that decision takes.

The stream keeps a node only until it has written it, so a caller may refill a node for the next call, as an encoder does with one scalar node per kind. Stream.Value is done with its node when it returns. Stream.Key keeps its node until the entry it opens is written: by the next Value, or, when a Begin call follows, by that collection's first entry or its End. A caller that reuses key nodes needs one per open collection.

No blank line is written between entries. The Renderer keeps one the author left, read off the tokens of the entry and of its "- ", and a collection handed over as a Begin call has neither.

func (*Stream) BeginMapping

func (s *Stream) BeginMapping() error

BeginMapping opens a mapping: the document's node, the value of the key just handed over, or a sequence entry.

func (*Stream) BeginSequence

func (s *Stream) BeginSequence() error

BeginSequence opens a sequence: the document's node, the value of the key just handed over, or a sequence entry.

func (*Stream) Close

func (s *Stream) Close() error

Close ends the document's last line, and returns ErrStreamOrder when the document is not complete.

func (*Stream) End

func (s *Stream) End() error

End closes the innermost collection.

func (*Stream) Key

func (s *Stream) Key(key Node) error

Key hands over the key of the next entry of the innermost mapping. Its value follows, as a Stream.Value or a collection.

func (*Stream) Value

func (s *Stream) Value(n Node) error

Value writes a node whole: the value of the key just handed over, the next entry of the innermost sequence, or the document's own node.

The node is usually a scalar. It may also be a subtree the stream takes no events for, such as an anchor, an alias, a tag or a flow collection: Value writes it as Renderer.Render writes the same subtree in place, in its own style.

type StringNode

type StringNode struct {
	BaseNode

	Token *token.Token
	Value string
}

StringNode is a string scalar: plain, single-quoted or double-quoted.

func String

func String(tk *token.Token) *StringNode

String returns a StringNode for tk.

func Text

func Text(s string) *StringNode

Text builds a string node holding s, quoting it where its text would read back as something else.

A node stands on the token it was built with, and a renderer writes that token's text: "8080" under String renders 8080 and reads back as an integer, and "a: b" renders a line no reader accepts. The quoting rule is token.IsNeedQuoted's.

func (*StringNode) Bytes

func (n *StringNode) Bytes() []byte

Bytes returns StringNode.Text as bytes, without copying it.

func (*StringNode) Clone

func (n *StringNode) Clone() *StringNode

func (*StringNode) Fill

func (n *StringNode) Fill(tk *token.Token)

Fill makes n the node String builds for tk, reusing n. It clears everything else n held, comments included.

func (*StringNode) GetToken

func (n *StringNode) GetToken() *token.Token

GetToken returns n.Token, the scalar as the document wrote it.

func (*StringNode) GetValue

func (n *StringNode) GetValue() any

GetValue returns the string, with its quotes removed and its escapes read.

func (*StringNode) IsMergeKey

func (n *StringNode) IsMergeKey() bool

IsMergeKey returns false: a quoted "<<", or one under a tag, is a StringNode and not a merge key.

func (*StringNode) String

func (n *StringNode) String() string

String string value to text with quote or literal header if required

A node built rather than parsed carries no token, and there is nothing then to say it was quoted or where it stood: it comes out as its plain value.

A plain value opening with "---" or "..." comes out single-quoted: the text starts in column 0, where written plain it reads back as a document marker.

func (*StringNode) Text

func (n *StringNode) Text() string

Text returns the string, with its quotes and escapes resolved.

func (*StringNode) Type

func (n *StringNode) Type() NodeType

Type returns StringType.

type TagNode

type TagNode struct {
	BaseNode

	Start *token.Token
	Value Node
	// URI is the tag this node carries, expanded from the shorthand the
	// document wrote: "!!int" and "!<tag:yaml.org,2002:int>" both give
	// tag:yaml.org,2002:int, and "!thing" gives "!thing", since the primary
	// handle expands to "!". A "%TAG" directive changes what a handle expands
	// to, so read this instead of Start to find which tag the node carries.
	URI string
	// Schema is the scalar schema the document is read under, which sets the
	// spellings the tag's type accepts: "017" is octal under %YAML 1.1 and
	// decimal without it, and "0b101" is an integer under the first and no
	// number at all under the second.
	//
	// The scanner types a plain scalar under this already, so for one the
	// token already holds the type. A quoted or block scalar it never sniffs --
	// the quotes make it a string when nothing else types it -- and a tag does
	// type it, so its text is read under this instead. Both spellings of the
	// same content then resolve alike, as §3.3.2 requires: the
	// "!" non-specific tag is given only to a node *lacking* an explicit tag,
	// so `!!int "017"` and `!!int 017` are one node and cannot differ.
	//
	// It is stamped on the node for the same reason LaxTags is: a subtree
	// handed to a consumer carries how to read it.
	Schema token.Schema
	// LaxTags records that the document was read with
	// [github.com/go-openapi/go-yaml/parser.WithLaxTags], so a consumer that
	// can fall back to the text should, where it would otherwise reject a tag
	// naming a type its scalar is not. [TagNode.Resolve] reports it as
	// [Resolution.Lax].
	//
	// It is stamped on the node instead of kept beside the document, so that a
	// node handed over on its own -- as DecodeFromNode and
	// expressions.Path.Read receive one -- carries the policy it was read under.
	LaxTags bool
	// Implicit records that the parse built this tag and the document did not write it.
	//
	// YAML 1.1 resolves types 1.2's core schema leaves out, and a timestamp is
	// one: under a "%YAML 1.1" directive, or
	// [github.com/go-openapi/go-yaml/parser.WithYAMLVersion] at 1.1,
	// "a: 2001-12-14" resolves to tag:yaml.org,2002:timestamp where under 1.2
	// it is the string. The tag records which type the scalar resolved to,
	// where the document wrote nothing.
	//
	// A renderer writing the document back leaves an implicit tag off, since
	// the source holds none; one reformatting to explicit tags writes it. A
	// consumer reading types -- the decoder, ToJSON -- reads URI and does not
	// care which way it arrived.
	Implicit bool
}

TagNode is a tag, such as "!!str", on the node it types.

func Tag

func Tag(tk *token.Token) *TagNode

func (*TagNode) Bytes

func (n *TagNode) Bytes() []byte

Bytes returns TagNode.Text as bytes, without copying it.

func (*TagNode) Clone

func (n *TagNode) Clone() *TagNode

func (*TagNode) GetToken

func (n *TagNode) GetToken() *token.Token

GetToken returns n.Start, the tag as written.

func (*TagNode) GetValue

func (n *TagNode) GetValue() any

func (*TagNode) IsMergeKey

func (n *TagNode) IsMergeKey() bool

IsMergeKey returns true for "!!merge", and otherwise whether the tagged node is a merge key.

func (*TagNode) Resolve

func (n *TagNode) Resolve() Resolution

Resolve checks the tag against the node under it and returns the result.

Read it to decide whether a tagged node can be loaded at all, and read Resolution.Text for the characters the scalar was written with. Resolve builds no Go value or JSON from those characters; each consumer does: the decoder builds a time.Time where the JSON converter writes the date as it was written, and both take the same verdict on whether the date is a date.

It reads the node and holds nothing, so it costs the same on a tree built by hand as on one that came from a parse.

func (*TagNode) String

func (n *TagNode) String() string

String renders the tag and the tagged node.

func (*TagNode) Text

func (n *TagNode) Text() string

Text returns the text of the tagged scalar, or nothing where what is tagged is a collection.

func (*TagNode) Type

func (n *TagNode) Type() NodeType

Type returns TagType.

type TagVerdict

type TagVerdict uint8

TagVerdict records whether a tag applies to the node it stands on.

YAML 1.2.2 §3.1.2 builds a representation from the serialization, and a node whose tag the processor cannot apply has no representation to build. The specification calls the remainder a partial representation and leaves open what a processor returns to the caller, so this library sets the outcome of "!!int abc". TagNode.Resolve sets it once, and every consumer reads its result instead of working it out again: the decoder and the JSON converter each had their own tag switch, and they disagreed about "!!timestamp" and "!!binary".

const (
	// TagResolved is a tag naming a type, on a node that is one.
	TagResolved TagVerdict = iota
	// TagUnresolved is a tag this library has no rule for: a local tag such as
	// "!Ref", a foreign one written "!<tag:example.com,2000:x>", or a
	// "tag:yaml.org,2002:" name the type repository does not define. The node
	// is read by its kind alone and the tag is the application's to interpret.
	//
	// §6.9.1 hands a local tag to the application, so this is not a failure and
	// the strictest reading still accepts it.
	TagUnresolved
	// TagValueMismatch is a tag naming a scalar type, on a scalar whose text is
	// not one: "!!bool 7", "!!int abc", "!!timestamp not-a-date".
	TagValueMismatch
	// TagKindMismatch is a tag naming a kind the node is not: "!!seq 5" tags a
	// scalar as a sequence, "!!str [1, 2]" tags a sequence as a scalar.
	TagKindMismatch
)

func (TagVerdict) String

func (v TagVerdict) String() string

type TransformFunc

type TransformFunc func(w io.Writer, s Written) error

TransformFunc writes one stretch of a rendering.

A function that writes s.Text unchanged gives the plain rendering. Writing anything else transforms it: github.com/go-openapi/go-yaml/transform/colorize wraps the text of a node in escapes and passes everything else through.

type Verdict

type Verdict int

Verdict classifies a mapping entry whose key is "<<".

Every reader must tell the three verdicts apart, and tell them apart the same way. Thirteen places asked MapKeyNode.IsMergeKey and each drew its own conclusion from a bare yes: the decoder folded, the converter deferred to the mapping's close, the typed walk gave up on the document, and none of them agreed about a "<<" whose value is not a mapping.

const (
	// NotAMerge marks an entry whose key is an ordinary one.
	//
	// Whether a "<<" is a merge key is settled before a node exists. The
	// scanner recognizes the characters and types them, unconditionally,
	// because it cannot see a "!!merge" standing in front of them -- a "%TAG"
	// line can repoint the secondary handle and the scanner never reads one.
	// The parser holds the directives and the document's version, so the parser
	// chooses the node: a MergeKeyNode where the merge resolves, an ordinary key
	// where it does not. [MergeOf] reads the answer from the node's type.
	NotAMerge Verdict = iota
	// Folds marks an entry that brings in the mappings of [MergeEntry.Sources], earliest
	// first, and contributes no key of its own.
	Folds
	// Refused marks an entry whose value is not a mapping and not a sequence of
	// mappings, so the merge type has nothing to fold. [MergeEntry.Offender] holds the value.
	Refused
)

type Visitor

type Visitor interface {
	Visit(node Node) Visitor
}

Visitor receives each node Walk reaches.

Visit returns the visitor for the node's children: Walk visits each child with it, or skips the children where it is nil. Walk makes no call after a node's children, so a visitor learns that a node is done only from the next call.

type Written

type Written struct {
	// Text is the stretch about to be written.
	Text []byte
	// Node is the node the renderer is writing, or nil for the source standing
	// between two nodes: the indentation, a "---".
	Node Node
	// Token is the token Text was cut from, and nil where Text is not a token:
	// the space before one, or text the renderer laid out for a node the source
	// does not reach.
	Token *token.Token
	// FromSource is true when Text is the document's own bytes. It is false for
	// a node a caller inserted, which the renderer lays out.
	FromSource bool
	// Key is true when the stretch stands inside a mapping's key, not its value.
	// A key and its value are two halves of one entry and no field of the node
	// marks which is which, so the renderer sets Key.
	Key bool
}

Written is one stretch of a rendering, handed to the function WithTransform installed before it goes to the writer.

A rendering is a run of these and nothing else, so a function that writes every Text through changes nothing.

func (Written) Filler

func (s Written) Filler() []byte

Filler returns what Trimmed cut: the spaces and line breaks between this stretch's text and the next.

func (Written) Trimmed

func (s Written) Trimmed() []byte

Trimmed returns Text without the run of spaces and line breaks at its end.

A token's text runs to where the next one starts, so a token the scanner read past carries what followed it. A transform that wraps text -- a colorizer, a marker -- must wrap the token and not the gap after it, or the wrapping runs to the end of the line and past the break.

⚠️ A block scalar's body ends in the line break the document wrote, and this cuts it. Use it to decide what to wrap, not to rebuild the document.

Jump to

Keyboard shortcuts

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