| | |

YAML 11 ๐Ÿ“„ Parser Mechanics and Abstract Syntax Trees (AST)

โฑ๏ธ Estimated read: 10 min | |

YAML parsers do not jump directly from text to a data structure. They follow a layered pipeline that mirrors the YAML 1.2.2 specification: bytes are scanned into tokens, tokens are composed into events, events are loaded into an abstract syntax tree, and the tree is finally converted into the application’s native objects . Each layer discards some information and preserves some, and knowing which layer does what is the difference between a parser that can round-trip a file faithfully and one that silently loses comments, anchors, or formatting.

This chapter covers the parser pipeline, the node types that make up the AST, and the distinction between the serialization tree and the representation graph. It explains why comments and whitespace are not part of the AST in most parsers, how anchors are represented as references rather than duplicated values, and the security limits that a streaming parser must enforce. The sections that follow walk through the pipeline stages, the AST node taxonomy, and the event-based alternative to full tree loading.

Key point: The AST is a lossy intermediate representation; comments, whitespace, and formatting are typically discarded unless the parser explicitly preserves them, and anchors appear as reference nodes rather than expanded values unless the loader resolves them.


a. The parser pipeline: scanner, parser, composer

A YAML parser processes input through at least three conceptual stages. The scanner converts the byte stream into a sequence of tokens. The parser consumes tokens and produces events or a serialization tree. The composer resolves aliases and tags to produce a representation graph that the constructor turns into native objects .

The scanner emits tokens that correspond to YAML’s structural indicators. The block mapping start, block sequence start, block entry, key, and value tokens represent the :, -, ?, and indentation changes that the scanner detects . A simple mapping like key: value produces SCALAR("key"), VALUE, SCALAR("value"). A block sequence produces BLOCK-SEQUENCE-START, BLOCK-ENTRY, SCALAR("item 1"), SCALAR("item 2"), BLOCK-END. The scanner’s job is to detect indentation changes and emit the corresponding start and end tokens, which is the mechanical basis for YAML’s whitespace sensitivity.

The parser stage consumes these tokens and builds the syntax tree. In the Dart yaml package, the parser produces a serialization tree whose nodes carry tags and anchors as written. The composer then visits that tree, resolving aliases by looking up the anchor map and parsing scalars according to their tags to produce a representation graph . The distinction matters: the serialization tree preserves the document’s structure as written, while the representation graph resolves the references and applies the core schema’s type resolution.

Streaming parsers separate these stages further. The rlsp-yaml-parser crate uses a line-oriented lexer that hands lines to an event iterator, and a separate loader consumes the event stream to build an AST only when a tree is needed . This means a parser can validate a document’s syntax without materializing the entire tree, which is why streaming parsers have O(1) first-event latency regardless of input size.


b. AST node types and the serialization tree

The AST node types vary by implementation, but the core taxonomy is consistent. Ruby’s Psych defines a Stream at the root, containing one or more Document nodes, each with exactly one root child that is a Scalar, Sequence, or Mapping . A Mapping has an even number of children alternating between keys and values. A Sequence has an arbitrary number of children. A Scalar is a leaf with no children .

The st2flow-yaml parser’s AST shows the same structure with position information. A mapping node has kind: 1, a key child with startPosition, endPosition, kind: 0, and value, and a value child with the same fields . The position information is what enables a round-trip serializer to reconstruct the original document, including the whitespace between tokens. The parser notes that yaml-ast-parser discards whitespace, comments, colons, and other special characters, and the wrapper recovers them by parsing the “gap” between a token’s endPosition and the next token’s startPosition, assigning each token a prefix that represents the gap before it .

This gap-recovery is the difference between a lossy AST and a faithful one. A parser that discards whitespace cannot round-trip a YAML file: the output will be semantically equivalent but textually different. A parser that preserves the gaps can reconstruct the original byte-for-byte, which is why the st2flow-yaml library claims tokenSet.toYAML(tokenSet.fromYAML(yaml_string)) === yaml_string . The cost is that the AST is larger and more complex, and consumers are advised to interact through a crawler or POJO conversion rather than reading the AST directly.


c. Anchors, comments, and the lossless AST

Anchors and aliases are represented as references in the AST, not as duplicated subtrees. The composer’s visitAlias method looks up the anchor name in a map and returns the node the anchor points to . This is why a YAML document with a large anchored block and many aliases does not expand to a large tree until the representation graph is constructedโ€”the serialization tree contains one anchored node and many small alias references.

Comments are the most commonly lost information. Most YAML parsers discard comments entirely because they are not part of the data model. The rlsp-yaml-parser crate explicitly lists “first-class comments” as a feature: comment text and spans are preserved and attached to adjacent AST nodes by the loader . The oak-yaml parser’s “high-fidelity AST” claims to retain “all trivia” including whitespace and comments, enabling “faithful round-trip processing” . These parsers are built for toolingโ€”linters, formatters, IDEsโ€”where the original text matters, not just the data.

The security limits on the AST are also part of the parser’s mechanics. A deeply nested document can exhaust the stack, and a document with many anchors and aliases can exhaust memory even if it is small on disk. The rlsp-yaml-parser crate enforces a default max_nesting_depth of 512, a max_anchors of 10,000, and a max_expanded_nodes of 1,000,000 for alias-bomb protection . These limits are enforced by the loader, not the event iterator, which means a parser that only streams events without building the tree does not pay the memory costโ€”but also does not get the protection unless the limits are applied at the event layer.


Complete Example Session

# ============================================
# PART 1: THE SOURCE YAML
# ============================================
# version: 1.0
# # a comment
# defaults: &defaults
#   timeout: 30
# service:
#   <<: *defaults
#   endpoint: /api

# ============================================
# PART 2: THE TOKEN STREAM (SCANNER OUTPUT)
# ============================================
# SCALAR("version")
# VALUE
# SCALAR("1.0")
# SCALAR("defaults")
# VALUE
# ANCHOR("defaults")
# BLOCK-MAPPING-START
# SCALAR("timeout")
# VALUE
# SCALAR("30")
# BLOCK-END
# SCALAR("service")
# VALUE
# BLOCK-MAPPING-START
# MERGE-KEY
# ALIAS("defaults")
# SCALAR("endpoint")
# VALUE
# SCALAR("/api")
# BLOCK-END

# ============================================
# PART 3: THE SERIALIZATION TREE (LOSSY AST)
# ============================================
# Mapping
# โ”œโ”€โ”€ key: "version"
# โ”‚   โ””โ”€โ”€ value: "1.0"
# โ”œโ”€โ”€ key: "defaults"
# โ”‚   โ””โ”€โ”€ value: Mapping (anchor: "defaults")
# โ”‚       โ””โ”€โ”€ key: "timeout"
# โ”‚           โ””โ”€โ”€ value: "30"
# โ””โ”€โ”€ key: "service"
#     โ””โ”€โ”€ value: Mapping
#         โ”œโ”€โ”€ merge: Alias("defaults")
#         โ””โ”€โ”€ key: "endpoint"
#             โ””โ”€โ”€ value: "/api"
#
# The comment is gone. The anchor is a reference, not a copy.
# The merge key is a node, not yet resolved.

# ============================================
# PART 4: THE REPRESENTATION GRAPH (RESOLVED)
# ============================================
# The composer resolves the alias and the merge:
# service: { timeout: 30, endpoint: "/api" }
# The anchor and alias are no longer present.

The parts covered the source YAML, the token stream, the serialization tree with the anchor as a reference, and the resolved representation graph.


Quick Reference

Pipeline Stages

StageInputOutput
ScannerBytesTokens
ParserTokensSerialization tree
ComposerSerialization treeRepresentation graph
ConstructorRepresentation graphNative objects

AST Node Types (Psych)

NodeChildrenNotes
StreamDocument(s)Root
DocumentExactly one rootScalar/Sequence/Mapping
MappingEven numberKey-value pairs alternating
SequenceAny numberList items
ScalarNoneLeaf node
AliasNoneReference to anchor

Lossless Features

FeatureParser
Whitespace gapsst2flow-yaml prefix
Commentsrlsp-yaml-parser
All triviaoak-yaml

Best Practices

โœ… Do This:

# Use a lossless parser for tooling
# (linters, formatters, IDEs)                                 # โœ…

# Use a streaming parser for large files
# (validate without building the full tree)                   # โœ…

# Apply nesting and alias limits
# (max_nesting_depth, max_anchors)                            # โœ…

โŒ Don’t Do This:

# Assume the AST preserves comments
# (most parsers discard them)                                 # โŒ

# Assume anchors are expanded in the AST
# (they are references until the composer runs)               # โŒ

# Parse untrusted YAML without alias limits
# (billion laughs)                                            # โŒ

Common Pitfalls

PitfallWhy It HappensFix
Comments lost after parseAST does not store triviaUse a lossless parser
Round-trip changes formattingWhitespace discardedUse gap-preserving parser
Alias bomb exhausts memoryNo expansion limitSet max_expanded_nodes
Stack overflow on deep nestingNo depth limitSet max_nesting_depth

Real-World Examples

1. Scanner token for mapping

SCALAR("key") VALUE SCALAR("value")

2. Block sequence tokens

BLOCK-SEQUENCE-START BLOCK-ENTRY SCALAR("item") BLOCK-END

3. Psych AST root

Psych.parse("x: y").root # Mapping

4. Mapping children alternate

mapping.children.map(&:value) # ["x", "y"]

5. Alias node

Alias("defaults") references the anchored Mapping

6. Composer anchor lookup

_anchors[alias.anchor] // returns the node

7. Streaming event

parse_events("key: value\n") // iterator of Event

8. Security limit

LoaderBuilder::new().max_nesting_depth(128)

9. Gap prefix

token.prefix // whitespace before the token

10. Lossless round-trip

toYAML(fromYAML(s)) === s // true for st2flow-yaml

Visual

The Parser Pipeline

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  BYTES                                                  โ”‚
โ”‚    โ”‚                                                    โ”‚
โ”‚    โ–ผ                                                    โ”‚
โ”‚  SCANNER โ”€โ”€โ–บ Tokens                                     โ”‚
โ”‚    โ”‚                                                    โ”‚
โ”‚    โ–ผ                                                    โ”‚
โ”‚  PARSER โ”€โ”€โ–บ Serialization Tree (tags, anchors)          โ”‚
โ”‚    โ”‚                                                    โ”‚
โ”‚    โ–ผ                                                    โ”‚
โ”‚  COMPOSER โ”€โ”€โ–บ Representation Graph (resolved)           โ”‚
โ”‚    โ”‚                                                    โ”‚
โ”‚    โ–ผ                                                    โ”‚
โ”‚  CONSTRUCTOR โ”€โ”€โ–บ Native objects                         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

AST Node Taxonomy

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Stream                                                 โ”‚
โ”‚    โ””โ”€โ”€ Document                                         โ”‚
โ”‚          โ””โ”€โ”€ Mapping                                    โ”‚
โ”‚                โ”œโ”€โ”€ Scalar("key")                        โ”‚
โ”‚                โ””โ”€โ”€ Scalar("value")                      โ”‚
โ”‚                                                         โ”‚
โ”‚  Sequence                                               โ”‚
โ”‚    โ”œโ”€โ”€ Scalar("item 1")                                 โ”‚
โ”‚    โ””โ”€โ”€ Scalar("item 2")                                 โ”‚
โ”‚                                                         โ”‚
โ”‚  Alias โ”€โ”€โ–บ references an anchored node                  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Lossy vs Lossless AST

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  LOSSY                          LOSSLESS                โ”‚
โ”‚                                                         โ”‚
โ”‚  Data only                      Data + trivia           โ”‚
โ”‚  Comments gone                  Comments kept           โ”‚
โ”‚  Whitespace normalized          Gaps preserved          โ”‚
โ”‚  Round-trip changes text        Byte-identical output   โ”‚
โ”‚                                                         โ”‚
โ”‚  Standard parsers               Tooling parsers         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Anchor as Reference

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  defaults: &d                                           โ”‚
โ”‚    timeout: 30                                          โ”‚
โ”‚  service:                                               โ”‚
โ”‚    <<: *d                                               โ”‚
โ”‚                                                         โ”‚
โ”‚  Serialization tree:                                    โ”‚
โ”‚  defaults โ†’ Mapping (anchor "d")                        โ”‚
โ”‚  service  โ†’ Mapping                                     โ”‚
โ”‚    โ””โ”€โ”€ Alias("d") โ”€โ”€โ–บ points to defaults                โ”‚
โ”‚                                                         โ”‚
โ”‚  Representation graph:                                  โ”‚
โ”‚  service โ†’ { timeout: 30 }                              โ”‚
โ”‚  (the alias is resolved, the reference is gone)         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
PipelineBytes โ†’ Tokens โ†’ Serialization tree โ†’ Representation graph
Scanner outputTokens (SCALAR, VALUE, BLOCK-MAPPING-START)
AST root (Psych)Stream โ†’ Document โ†’ root node
Mapping childrenEven number, alternating key-value
Alias in ASTReference node, not expanded
Comment preservationParser-dependent
Security limitsNesting depth, anchor count, expanded nodes

Key takeaways:

  • The parser is a pipeline, not a single step. The scanner produces tokens, the parser builds the serialization tree, and the composer resolves aliases and tags into a representation graph . Each stage has a different output, and the AST most consumers see is the serialization tree before resolution.
  • The AST is lossy by default. Comments, whitespace, and formatting are discarded unless the parser explicitly preserves them. A lossless parser like st2flow-yaml recovers the gaps between tokens to achieve byte-identical round-trips .
  • Anchors are references, not copies. The AST contains one anchored node and alias nodes that point to it. The expansion happens in the composer, which is also where the billion-laughs risk livesโ€”hence the alias-expansion limits .
  • The node taxonomy is small. Scalar, Sequence, Mapping, Alias, and Document cover the structure. A mapping has an even number of children alternating between keys and values .
  • Security limits belong in the loader. A streaming parser can validate syntax without building the tree, but the tree-building loader must enforce nesting depth, anchor count, and expanded node count to prevent denial of service .

Remember: A YAML parser does not hand you your data; it hands you a tree that a constructor turns into your data. The tree is not the file. It loses comments, normalizes whitespace, and represents anchors as references. When a tool needs to preserve the file, it needs a parser that preserves the gaps and trivia, not just the data. When a service parses untrusted input, it needs a parser that bounds the tree’s depth and alias expansion. The AST is the intermediate representation, and knowing what it keeps and what it drops is the difference between a tool that respects the source and one that rewrites it.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!