parser

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: 14 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.

README

parser

The parser reads the tokens of the scanner and builds the nodes of package ast, as a tree (Parse) or one node at a time (Walk).

This document is the maintainer's companion: it holds the reasons, the rejected alternatives and the measurements that the code comments leave out. Numbers carry the date they were measured; re-measure before quoting one.

State through the descent

context is passed by value. It is six words: tokenRef, path, the two flow flags packed with depth, arena, lineComments and keyBase. Copying it costs less than the heap allocation and collection a pointer would need.

tokenRef is the one pointer the contexts share, because the position in a run must move for every reader of it. Parser.refs holds one per depth. The parse is depth first, so at most one group is being read at each depth: a document nested N deep costs N references however many groups it holds. They are held by pointer so that growing the slice does not move a reference already handed out.

tokenRef.at runs about five times per token (September 2026). Its slow path, draw, is a separate function so that at stays inlined. idx, cur and held come first in the struct so that the fast path reads one cache line: with held at offset 64, the fast path straddled two.

The descent state that mapping, sequence and the property rules all read (descentState, anchorTable) sits on the Parser and not on context, so no step passes it down.

Siblings are a loop

parseMap reads its entries in a loop over parseMapEntry. It used to recurse once per sibling, building a whole MappingNode at every level and keeping only its Values: a mapping of N keys cost N recursions and slice concatenations summing to O(N²). TestParseScalesLinearlyInWidth (scaling_test.go) holds the cost per entry flat over a 16x range of widths; the recursive version moved it by a factor of nine.

The loop also explains one branch in parseMap: a foot comment goes to the last entry. Under recursion the innermost call held exactly one value, so the attribution came for free; the loop has to choose it to keep it the same.

descentState.entries and seqEntries hold the entries of every open collection, innermost last. Each collection copies its run out once, at its final length. Growing each collection's slice an entry at a time was 96-99% of what runtime.growslice copied during a parse: 1,385K of 1,389K on canada_geometry (September 2026).

A built token stays out of the run

createImplicitNullToken and resolveTimestamp build tokens that the source does not hold. Neither is put into the run: the node built from it is its only reader, and a token in the run would be read again by the descent. There is no insertToken for that reason.

Where a check sits

  • maxNesting caps the depth in the parser, though the parse reads any depth. The decoder builds a Go value by recursion, and [ written 10,000 times is 10 KB. Capping it here stops the walk, the tree decoder and ToJSON at the same level of the same document.
  • Whether << is a merge key depends on the YAML version, and the parser decides it (mergeKeysInForce). The scanner cannot: a %TAG line can repoint the !! handle, and the scanner never reads one.
  • A repeated key is recorded in the key.Ledger, not refused at once. A document that cannot be parsed cannot be linted, rendered or colorized either, so the reader decides (ast.FirstRefused).

Naming a collection key

A collection key gets no name while its entry is read, because it holds nothing yet. recordBuiltKeyOnce names it once the entry is complete. Naming one earlier was tried three ways, and all three were wrong:

  • the first token names every sequence key [ and every block mapping key :;
  • no name at all stops the check, and the walk then folds a repeat's two entries into one and drops the first value;
  • the source text reads [a] and [ a ] as two keys, which the walk folds anyway: the same dropped value.

A collection key has no path either: neither YAMLPath nor JSON Pointer can spell one.

The walk's memory

A walk holds the tokens from the tape's tail to the scanner. readTo sets the tail from the outermost run, not from the token in hand: a descent deep in a document still holds the tokens of every level it is inside, and parseMapEntry reads its key's group again after parsing the value.

holdRun and releaseRun keep the chunk where a construct began, one chunk per open level, so what a walk holds grows with depth, not length. The pair takes a sequence number instead of returning an undo func: a closure escapes, and on citm_catalog those closures came to about 1 MB, 14% of what the conversion allocated (September 2026).

releaseSkipped moves the tail for a node the visitor skipped. Without it, a visitor that skipped the root or stopped the walk held every token to the end of the stream: on 20,000 flat keys that doubled the bytes a walk allocated and multiplied its allocations by 4.6.

The node arena is rewound once a node has been handed over, so a later node takes its cell. Two rules follow:

  • never key a map on a node pointer across a walk. Over 12,597 corpus documents, a map keyed on ast.Node counted 5,226 nodes as handed over twice; transform found 610 of 88,473 pieces carrying a node that had moved. Return ErrKeepNode to keep a node.
  • keepAnchorIdentity records an anchored node when its anchor closes, the last moment the node is whole. Taken later, AliasNode.Target points at a reused cell, and &a [a, b] read back as seq().

Reading one token at a time

reader.fill feeds the grouper one token at a time. The grouping is a state machine, so nothing waits in a batch. The batch version kept a slice of tokens waiting to be grouped, a second slice for the last run's groups, and copied one into the other on every fill. Feeding one token also means the scanner is never read further than the descent asked, so a stage can ask the scanner about the token in hand.

The grouper holds a window back to the start of any flow collection still open, because that collection may yet close and stand as a key. groupingHeld (grouping_test.go) measures it: a block mapping of 50,000 keys holds a handful of tokens, and a flow sequence of 30,000 members holds every token. This is the one hold in a walk that grows with the length of a document.

Documentation

Overview

Package parser reads a YAML stream into an ast.File.

ParseBytes reads a whole stream and returns one ast.DocumentNode per document:

file, err := parser.ParseBytes(src, parser.WithComments())

New returns a Parser with the same options, and Parser.Parse reads a stream with it. Parser.Walk reads a stream without building the tree, and hands each node to a Visitor as the parse reaches it. github.com/go-openapi/go-yaml/codec.ToJSON converts a document to JSON this way.

None of these copies src. The tree keeps slices of it, so do not write to src while the file is in use.

Defaults

A document that names no version with a "%YAML" directive is read under YAML 1.2. Use WithYAMLVersion to change that default, and WithMergeKeys to read a bare "<<" as a merge key under 1.2.

The parser drops comments as it reads. Use WithComments to keep them on the tree.

The parser accepts the superset of YAML that is not JSON. To enforce a parsing of only documents that are compatible with JSON, use WithJSONCompatible. To accept only documents written as JSON, use WithJSONSyntax.

A repeated mapping key does not stop the parse: the parser records it in the Duplicates of the ast.MappingNode, and the decoder rejects the document with github.com/go-openapi/go-yaml/errors.ErrDuplicateKey. Use WithAllowDuplicateMapKey to accept duplicate keys: a decoder keeps the last value, and a converter writing JSON as it reads keeps the first.

Errors

A document that can't parse returns an error that carries the source around the failure. Parser.Parse returns with it an ast.File holding the documents read before the one that failed; Parser.Walk returns none. Match it with errors.Is:

Concurrency

A Parser holds the state of one parse, and is not safe for concurrent use. It reads one stream: call Parser.Reset before passing it the next. Reset reuses the memory of the previous parse, so stop using the file that parse returned. ParseBytes builds a new Parser on every call, so it is safe to call from several goroutines at once.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrKeepNode = errors.New("keep this node whole")

ErrKeepNode tells Parser.Walk to hand the node over whole at its Leave. Return it from Visitor.Enter.

Nothing inside the node is handed over, as for ErrSkipNode, but Leave is called, and the node then holds all its content: a mapping its entries, a sequence its values. Use ast.Clone in Leave to keep it, since the parse reuses its cells and tokens once Leave returns.

The walk holds the node's cells and tokens from Enter until Leave returns, so a kept subtree costs its own size and no more. Keep the nodes you want and skip the rest to read a large document with the memory of its matches.

A scalar and a node with no content are whole already, so ErrKeepNode reads as nil for them. Returned from Visitor.Leave it has no meaning and stops the walk, as any other error does.

View Source
var ErrParserReused = errors.New("parser: Parse or Walk called again without Reset")

ErrParserReused is returned by Parser.Parse and Parser.Walk on a Parser that has already read a stream since New or the last Parser.Reset.

View Source
var ErrSkipNode = errors.New("skip this node's content")

ErrSkipNode tells Parser.Walk not to hand the node's content over. Return it from Visitor.Enter.

Leave is not called for a node whose Enter skipped it, and the parse reads the content all the same: the descent builds the whole document whatever a visitor asks for, and ErrSkipNode stops the handovers below.

Returned from Visitor.Leave it has no meaning and stops the walk, as any other error does.

View Source
var ErrStopWalk = errors.New("stop the walk")

ErrStopWalk stops the walk with no error. Return it from Visitor.Enter or Visitor.Leave.

Nothing more is handed over, not even the Leave of a node already open, and the parse reads no further. Parser.Walk returns a nil error and a file holding the documents read before the one the walk stopped in. Use it where the consumer has what it wants: a document the parse would refuse later in the stream is not read, and so not refused. github.com/go-openapi/go-yaml/codec.JSONTokens.Tokens returns it when the range body breaks.

A visitor that stops by answering ErrSkipNode to everything reads the whole stream, and still receives the Leave of every node it had open.

Functions

func ParseBytes

func ParseBytes(src []byte, opts ...Option) (*ast.File, error)

ParseBytes reads the YAML stream src with a new Parser configured with opts.

src is not copied. The returned ast.File keeps slices of it, so do not write to src while the file is in use. On error the file holds the documents read before the one that failed, as Parser.Parse returns them.

Types

type Closing

type Closing interface {
	Cursor
	// HoldsKey reports whether the mapping being left wrote name as a key itself.
	//
	// It answers for the mapping the Leave is closing, and false for every other node.
	//
	// The name is the one [ast.KeyName] gives, which the parse already computed for its duplicate check:
	// an integer key is named in decimal whatever base the document wrote it in, so "7" and "007" are one
	// name, and a float by its value, so "1" and "1.0" are two.
	//
	// ⚠️ HoldsKey compares the name and not the node, so two keys YAML tells apart may share one:
	// "1: a" and "\"1\": b" resolve to an integer and a string and both answer "1". A writer that names a
	// member once asks this. A reader that compares keys as 3.2.1.1 does reads ast.MappingNode.Duplicates.
	HoldsKey(name string) bool
}

Closing answers what only a node the walk has finished reading can answer. Visitor.Leave receives one, and it answers everything a Cursor does.

type Cursor

type Cursor interface {
	// Depth counts the nodes enclosing the node: collections, and the anchors, tags and "?" keys written on
	// them, each of which adds a level. A document's root is at depth 0.
	//
	// Match a Leave to its Enter on the depth and not on the node: the parse hands its cells out again behind
	// the descent, so two nodes of one document are frequently the same pointer.
	Depth() int
	// In names the node enclosing this one: a mapping, a sequence, or the anchor, tag or "?" written on it.
	//
	// A node under an anchor, a tag or a "?" has that property as In, not the collection around the property.
	// It is [KindNone] for a document's root, which IsRoot reports directly.
	In() Kind
	// IsRoot reports the body of a document, which nothing encloses.
	//
	// The walk hands no DocumentNode over, so a consumer reads this and Document to see the next document begin.
	// Implement [DocumentVisitor] to be told when one ends, which an empty document also does.
	IsRoot() bool
	// IsKey reports that the node is a mapping key, and that its value is the next handover in the same mapping.
	// A key and its value are two handovers of one entry, and nothing on the node tells them apart.
	//
	// It marks the outermost node standing for the key: the "?" of an explicit key, or the anchor or tag
	// written on a key. The node inside arrives with IsKey false and In set to [KindKey], [KindAnchor] or
	// [KindTag], so a consumer that names a key by its content tracks the enclosing key itself.
	// A tagged scalar key is not handed over on its own: "!!str 1: v" hands over the tag, marked a key, then "v".
	IsKey() bool
	// Document indexes the node's document in the Docs of the [ast.File] that [Parser.Walk] returns.
	//
	// An empty document hands over no node, and the count still moves past it:
	// "---" over "---" over "b: 2" hands over one mapping, at Document 1.
	//
	// Each "%YAML" or "%TAG" line counts as a document of its own, ahead of the one it applies to.
	// "%YAML 1.2" over "---" over "a: 1" puts the mapping at Document 1, and two directive lines put it at 2.
	// To find the nth document a reader sees, skip the documents whose node is an [ast.DirectiveNode].
	Document() int
	// Schema returns the schema the node's document resolves plain scalars under: the one its "%YAML" line
	// declares, or the one [WithYAMLVersion] sets where it declares none.
	Schema() token.Schema
}

Cursor answers where the walk stands, for the node being handed to a Visitor.

⚠️ Read it during the call. It reports the walk's own position and moves on to the next node, so a consumer that wants an answer later copies it out.

The walk computes each answer from the nodes it holds open, so a consumer does not keep that stack itself. Leave receives the same answers Enter received for the node.

Where a node stands in the source is not here: read ast.Node.GetToken and its Position. A block mapping's token is its first key until the parse reads that key's ':', and the ':' after that, so the node reports two positions over its own Enter and Leave and the walk adds nothing to that.

type DocumentVisitor

type DocumentVisitor interface {
	Visitor
	LeaveDocument(doc *ast.DocumentNode, n int) error
}

DocumentVisitor is a Visitor that is also told where each document of the stream ends.

Parser.Walk calls LeaveDocument once the parse has read a document: after the Leave of its body, and before the next document opens. It is called for every entry of the Docs of the ast.File that Walk returns, an empty document and one holding only a "%YAML" or "%TAG" directive included, and n is the index Cursor.Document gave the document's nodes.

doc is valid until LeaveDocument returns, as a node is until its Leave returns. Its Body is the node the walk handed over, without its content.

Return ErrStopWalk to end the walk after this document: Walk returns no error and a file ending with doc. Return any other error to stop the walk, as from Leave. LeaveDocument is not called once a visitor has stopped the walk or returned an error.

type Kind

type Kind uint8

Kind names what encloses a node handed to a Visitor: a collection, or the anchor, tag or "?" written on the node.

const (
	// KindNone marks a document's root, which nothing encloses.
	KindNone Kind = iota
	// KindMapping is a mapping. Its entries are keys, each followed by its value.
	KindMapping
	// KindSequence is a sequence. Its entries are values.
	KindSequence
	// KindAnchor is an anchor, which encloses the node it names.
	KindAnchor
	// KindTag is a tag, which encloses the node it types.
	KindTag
	// KindKey is a mapping key written with "?", which encloses the key node.
	KindKey
)

func (Kind) String

func (k Kind) String() string

String returns the kind's name in lower case: "none" for KindNone and for any undefined value.

type Option

type Option func(p *Parser)

Option configures a Parser. Pass options to New or ParseBytes.

func WithAllowDuplicateMapKey

func WithAllowDuplicateMapKey() Option

WithAllowDuplicateMapKey lets a document repeat a mapping key.

The parser records a repeated key in the Duplicates of the ast.MappingNode either way, and by default a load rejects the document with github.com/go-openapi/go-yaml/errors.ErrDuplicateKey. Under this option each repeat is marked ast.DuplicateKey.Allowed and the load keeps one entry: a decoder filling a Go map keeps the last, a converter writing JSON keeps the first. Two keys that share a name and not a node, such as 1 and "1", are marked the same way: see ast.DuplicateKey.NameOnly.

The converter cannot keep the last: github.com/go-openapi/go-yaml/codec.ToJSONTokens hands each token to its caller as the parse reaches it, so the first value has gone by the time the repeat is read. Keeping the last would mean holding back every mapping until it closes.

func WithAnchors

func WithAnchors(anchors map[string]ast.Node) Option

WithAnchors makes anchors declared outside the stream available to its aliases.

The parser resolves an alias against the anchors of its own document, and rejects one that names no anchor with github.com/go-openapi/go-yaml/errors.ErrUnknownAnchor. Pass the ast.DocumentNode.Anchors of the parse that declared them. github.com/go-openapi/go-yaml/codec.Decoder does this for the files given to github.com/go-openapi/go-yaml/codec.ReferenceFiles.

The anchors passed here do not appear in ast.DocumentNode.Anchors, and a document that declares the same name uses its own anchor.

func WithChunkSize

func WithChunkSize(size int) Option

WithChunkSize sets how many tokens one chunk of the token arena holds.

Left unset, the parser sizes chunks from the length of the document with tokenarena.SizeFor.

func WithComments

func WithComments() Option

WithComments keeps a document's comments on the tree.

Without it, the parser drops every comment as it reads the stream.

func WithJSONCompatible

func WithJSONCompatible() Option

WithJSONCompatible rejects a document that has no JSON form.

The parse returns github.com/go-openapi/go-yaml/errors.ErrNotJSON for:

  • a sequence or a mapping used as a mapping key, including through an alias such as "? *x";
  • an infinity or a NaN, for which JSON has no number, unless a tag makes it a string: "!!str .inf" converts to ".inf";
  • a cycle, such as "&x [ *x ]", since JSON writes a tree in full.

Two keys that YAML tells apart and that write one JSON member name, such as the integer 1 and the string "1", are recorded in the Duplicates of the ast.MappingNode with JSONNameOnly set. The decoder rejects them with ErrNotJSON as well.

Everything else converts. A non-string scalar key is quoted, so "1.5: a" is {"1.5":"a"}. An alias to a scalar writes what its anchor wrote, a "<<" merges the mapping it names, and a tag resolves.

github.com/go-openapi/go-yaml/codec.ToJSON parses with this option. Use it to find out whether a document converts before converting it.

func WithJSONSyntax

func WithJSONSyntax() Option

WithJSONSyntax rejects a document not written as JSON (RFC 8259), with github.com/go-openapi/go-yaml/errors.ErrNotJSONSyntax.

JSON is almost all YAML, so the parse reads it as it reads any document, and checks each token against JSON's grammar as the scanner cuts it. "a: b" is YAML and is rejected, and so are a comment, an anchor, a tag, a single quote, a trailing ',', a YAML escape such as "\x41", a number such as "0x1F" or ".5", and a second document.

The source is checked as JSON text: it may hold DEL and code points such as U+FFFF raw in a string, which a YAML stream may not, and no control character other than tab, line feed and carriage return.

Every syntax error the parse returns under this option carries ErrNotJSONSyntax, a document that is not YAML either included. Errors of other kinds keep their kind: a repeated member name is still recorded in the ast.MappingNode's Duplicates, as it is without the option.

This option asks whether a document is written as JSON. WithJSONCompatible asks whether a YAML document has a JSON form. Use both to read JSON and convert it.

func WithLaxTags

func WithLaxTags() Option

WithLaxTags keeps the text of a scalar whose tag does not apply to it, instead of rejecting the document.

The parser records the policy on each ast.TagNode, and ast.TagNode.Resolve applies it, so the decoder, the JSON converter and DecodeFromNode read a document the same way. By default Resolve returns an error naming the text and the tag, as for "!!int abc".

Under WithLaxTags "!!int abc" reads "abc", "!!bool 7" reads "7" and "!!timestamp not-a-date" reads "not-a-date". The tag stays on the node, so a document read under WithLaxTags renders back with its tags.

Two cases stay errors. A tag naming a kind the node is not, such as "!!seq 5", is always rejected. A tag the grammar has no production for, such as "!<>", is rejected by the scanner.

func WithMergeKeys

func WithMergeKeys() Option

WithMergeKeys resolves a bare "<<" as a merge key under every YAML version.

The merge key, tag:yaml.org,2002:merge, is a YAML 1.1 type. Under 1.2 a bare "<<" is an ordinary key spelled "<<", and only "!!merge <<" merges. Documents written for 1.1 tools use the bare spelling.

Reading such a document under YAML11 also changes how plain scalars resolve: "0100" becomes 64, "1_000" becomes 1000, "1:30" becomes 90 and "yes" becomes true. WithMergeKeys changes the merge key alone, and scalars still resolve under the version in force.

func WithNodePaths

func WithNodePaths() Option

WithNodePaths makes Parser.Walk record each node's path in the document, as Parser.Parse does by default, so ast.Node.GetPath answers for the nodes a Visitor receives.

The paths are a trie of ast.PathNode steps, one for every key and sequence element, and the walk keeps them all until the parser is Parser.Reset: on a 3.6 MiB document they take 3.5 MiB, against 0.5 MiB for the walk itself. A visitor that needs only the path of the node in hand can track the keys of the collections it has open instead.

func WithOmitNodePaths

func WithOmitNodePaths() Option

WithOmitNodePaths stops Parser.Parse recording each node's path in the document.

ast.Node.GetPath then returns "". github.com/go-openapi/go-yaml/codec.CommentToMap keys comments by those paths, so its keys are empty too. Use it on a large document whose paths go unread, to save the memory the paths take.

Parser.Walk records no path unless WithNodePaths is passed. Where both are passed, no path is recorded.

func WithOnComplete

func WithOnComplete(fn func(ast.Node)) Option

WithOnComplete calls fn with each node as the parser finishes it.

Nodes arrive in completion order: a node's children come before the node. WithOnComplete is experimental and may change without a deprecation.

func WithTokens

func WithTokens(fn func(token.Token)) Option

WithTokens calls fn for every token the scanner cuts, in the order the document writes them.

The tokens tile the source and the nodes do not, so a consumer that rewrites a document reads these and names them with the nodes Parser.Walk hands over. github.com/go-openapi/go-yaml/transform.Walk is the worked case: without this it scanned the source a second time, which was a tenth of what a transform cost.

fn sees every token, including the comments a parse without WithComments drops, and an invalid token just before the parse refuses the document.

The token is a copy and outlives the call: its Value and Origin are the source's own bytes, which the caller handed in. Nothing here points into the arena the parse recycles.

⚠️ The scanner runs ahead of the descent, so a token reaches fn before the node standing on it reaches a Visitor. The distance is what the grouping holds, which follows the document's depth and the key window and not its length.

func WithYAMLVersion

func WithYAMLVersion(v YAMLVersion) Option

WithYAMLVersion sets the YAML version of a document that names none with a "%YAML" directive.

The version decides how a plain scalar resolves. 1.1 reads "0100" as 64, "1_000" as 1000, "1:30" as 90 and "yes" as true, where 1.2 reads 100 and three strings. The default is YAML12.

A "%YAML" directive sets the version for the document it opens, and the next document goes back to v.

type Parser

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

Parser reads a YAML stream into an ast.File.

Build one with New. A Parser reads one stream: a second call to Parser.Parse or Parser.Walk returns ErrParserReused until Parser.Reset is called. A Parser is not safe for concurrent use.

func New

func New(opts ...Option) *Parser

New returns a Parser configured with opts.

It reads nothing. Pass a stream to Parser.Parse or Parser.Walk.

func (*Parser) DeclaredAnchors

func (p *Parser) DeclaredAnchors() map[string]ast.Node

DeclaredAnchors returns the anchors passed with WithAnchors, or nil when none were.

The map is the caller's own and is not copied, so do not write to it while p reads a stream. An alias the parse resolves to one of these has its ast.AliasNode.Target set to the node. A Visitor on Parser.Walk needs it to answer such an alias: the walk hands over only the stream's own nodes, and a declared anchor is never one of them.

func (*Parser) Parse

func (p *Parser) Parse(src []byte) (*ast.File, error)

Parse reads the YAML stream src and returns its documents as an ast.File.

src is not copied. The file keeps slices of it, so do not write to src while the file is in use.

On error the file holds the documents read before the one that failed, each complete, and the error carries the source around the failure. A stream is a run of independent documents, so a reader can use the ones before the failure: github.com/go-openapi/go-yaml/codec.Decoder decodes them, and returns the error from the document that failed on. The file is nil only when no document was read, as for ErrParserReused.

Parse returns ErrParserReused when p has already read a stream since New or the last Parser.Reset.

func (*Parser) Reset

func (p *Parser) Reset()

Reset prepares p to read another stream with the default settings, as Parser.ResetWithOptions does with no option.

Options given to New or to an earlier reset are dropped.

func (*Parser) ResetWithOptions

func (p *Parser) ResetWithOptions(opts ...Option)

ResetWithOptions prepares p to read another stream, configured with opts as New configures a new Parser.

Options given to New or to an earlier reset are dropped, so pass every option the next stream needs. ResetWithOptions reuses the memory of the previous parse: the next parse refills its tokens, nodes and path steps. Do not use the ast.File that an earlier Parser.Parse or Parser.Walk returned once p has been reset.

func (*Parser) Walk

func (p *Parser) Walk(src []byte, v Visitor) (*ast.File, error)

Walk reads the YAML stream src and hands each node to v as the parse reaches it.

Walk is experimental: its contract may change without a deprecation. Use Parser.Parse for a stable API. The last entry of a block reaches v only once the parse reads the next token that is not a comment.

Walk does not build the tree. A collection keeps none of its entries, so the memory a walk holds grows with the depth of the document and not with its length. The returned ast.File holds the documents without their bodies, which went to v. On error the file is nil.

A node is valid until its Leave returns, as Visitor describes.

Walk records no node path, so ast.Node.GetPath returns "" for the nodes v receives. Pass WithNodePaths to record them, at the cost of a path step for every key and element of the stream.

An anchor is handed over before the node it names and left after it, and Cursor.In answers KindAnchor for that node, so a writer has the anchor open while it writes the node.

A visitor that returns ErrStopWalk stops the walk and the parse, and Walk returns no error.

A visitor that returns an error stops the walk: nothing more is handed over and Walk returns that error. The parse still reads the rest of the stream, so a document it refuses after the visitor gave up is returned as the refusal it is, and the visitor's error is dropped. Keep the error in the visitor to read it back in that case, as every consumer in this module does.

Walk returns ErrParserReused when p has already read a stream since New or the last Parser.Reset.

Example

ExampleParser_Walk reads the image of each service without building the tree.

package main

import (
	"fmt"
	"io"
	"os"
	"strings"

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

const services = `name: shop
services:
  web:
    image: nginx:1.27
    ports: [80, 443]
  db:
    image: postgres:17
    env:
      POSTGRES_DB: shop
      POSTGRES_USER: app
`

// images prints the path and value of every "image" key.
//
// A key and its value arrive as two handovers at the same depth, so the visitor keeps the last key it saw at each
// depth and reads the path off that. A root mapping's keys are at depth 1.
type images struct {
	w    io.Writer
	keys []string
}

func (v *images) Enter(node ast.Node, at parser.Cursor) error {
	d := at.Depth()
	if at.IsKey() {
		for len(v.keys) < d-1 {
			v.keys = append(v.keys, "")
		}
		v.keys = append(v.keys[:d-1], node.String())

		return nil
	}

	if d > 0 && d <= len(v.keys) && v.keys[d-1] == "image" {
		fmt.Fprintf(v.w, "%s = %s\n", strings.Join(v.keys[:d], "."), node)
	}

	return nil
}

func (v *images) Leave(ast.Node, parser.Closing) error { return nil }

func main() {
	if _, err := parser.New().Walk([]byte(services), &images{w: os.Stdout}); err != nil {
		fmt.Println(err)
	}

}
Output:
services.web.image = nginx:1.27
services.db.image = postgres:17

type Visitor

type Visitor interface {
	// Enter is called before the node's content.
	//
	// Return nil to receive the content, [ErrSkipNode] to skip it, [ErrKeepNode] to receive the node whole at Leave
	// instead, and any other error to stop the walk.
	// Leave is not called for a node Enter skipped or failed on.
	Enter(node ast.Node, at Cursor) error
	// Leave is called after the node's content has been visited, and the Cursor answers as it did for Enter.
	//
	// The node is the one Enter received, filled in by what the parse read since. A block mapping's token is the
	// exception to watch for: Enter sees the first entry's key, or its '?', and Leave the entry's ':', as
	// [ast.MappingNode.Start] describes. In "name: app" Enter reads 1:1 and Leave 1:5.
	//
	// Return an error to stop the walk.
	Leave(node ast.Node, at Closing) error
}

Visitor receives each node of a document as Parser.Walk reaches it.

Enter comes before the node's content and Leave after it, so a writer opens a collection on Enter and closes it on Leave. A scalar gets Enter, then Leave at once.

A node is valid until its Leave returns. The parse reuses the tokens and the node cells behind the walk, so copy what is needed before then. Use ast.Clone to keep a scalar: the copy owns its tokens.

A mapping or a sequence reaches Leave without its entries: they were handed over one by one and not kept, so its Values are empty and it renders as "{}" or "[]". Build what you need from the entries as they arrive, or return ErrKeepNode from Enter to receive the collection whole instead of its entries. A collection standing as a mapping key or under an anchor also arrives whole: the parse keeps it to name the key or to answer an alias.

Under WithComments a node carries at its Leave the comments the parsed tree gives it: the one above it, the one closing its line, and the one on a "?" or ':' line that goes to it. A comment after the ',' that follows a collection, or a node with an anchor or tag, in a flow collection reaches the tree only after that node's Leave.

Do not key a map on the node pointer. Because the parse reuses node cells, two different nodes of one document often share a pointer. Key on the token's offset, or on the node's value.

A walk can hand over more values than the document writes. The parse reads "&!" as a tag on the empty node followed by an anchor on the empty node, so the walk hands over two roots at depth 0 in one document, or two values after one mapping key. Do not assume a mapping alternates key and value.

type YAMLVersion

type YAMLVersion string

YAMLVersion is a version of the YAML specification, as named by a "%YAML" directive or by WithYAMLVersion.

The version decides how a plain scalar resolves.

1.1 reads "0100" as 64, "1_000" as 1000, "1:30" as 90 and "yes" as true, where 1.2 reads 100 and three strings. A document may also name 1.0 or 1.3: 1.0 resolves as 1.1, and 1.3 as 1.2.

const (
	YAML10 YAMLVersion = "1.0"
	YAML11 YAMLVersion = "1.1"
	YAML12 YAMLVersion = "1.2"
	YAML13 YAMLVersion = "1.3"
)

func (YAMLVersion) Schema

func (v YAMLVersion) Schema() token.Schema

Schema returns the YAML schema to resolve plain scalars.

1.0 and 1.1 resolve against token.Schema11.

1.2, 1.3, the zero value and any other value resolve against token.Schema12.

Use it to scan a document alongside a parse with the same reading of plain scalars.

Directories

Path Synopsis
internal
key
Package key finds a mapping key that a document has already used.
Package key finds a mapping key that a document has already used.

Jump to

Keyboard shortcuts

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