YAML 11 ๐ Parser Mechanics and Abstract Syntax Trees (AST)
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
| Stage | Input | Output |
|---|---|---|
| Scanner | Bytes | Tokens |
| Parser | Tokens | Serialization tree |
| Composer | Serialization tree | Representation graph |
| Constructor | Representation graph | Native objects |
AST Node Types (Psych)
| Node | Children | Notes |
|---|---|---|
| Stream | Document(s) | Root |
| Document | Exactly one root | Scalar/Sequence/Mapping |
| Mapping | Even number | Key-value pairs alternating |
| Sequence | Any number | List items |
| Scalar | None | Leaf node |
| Alias | None | Reference to anchor |
Lossless Features
| Feature | Parser |
|---|---|
| Whitespace gaps | st2flow-yaml prefix |
| Comments | rlsp-yaml-parser |
| All trivia | oak-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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Comments lost after parse | AST does not store trivia | Use a lossless parser |
| Round-trip changes formatting | Whitespace discarded | Use gap-preserving parser |
| Alias bomb exhausts memory | No expansion limit | Set max_expanded_nodes |
| Stack overflow on deep nesting | No depth limit | Set 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
| Item | Value |
|---|---|
| Pipeline | Bytes โ Tokens โ Serialization tree โ Representation graph |
| Scanner output | Tokens (SCALAR, VALUE, BLOCK-MAPPING-START) |
| AST root (Psych) | Stream โ Document โ root node |
| Mapping children | Even number, alternating key-value |
| Alias in AST | Reference node, not expanded |
| Comment preservation | Parser-dependent |
| Security limits | Nesting 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-yamlrecovers 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, andDocumentcover 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.
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!