Debian Codegraph @

docs/dev/how-go-yaml-works.md

raw symbols SCIP
1 # How go-yaml Works
2
3 This document explains the internal architecture of YAML processing in
4 go-yaml.
5 Understanding this helps you debug issues, contribute to the project, and
6 appreciate why YAML loading isn't as simple as "parsing."
7
8 ## Common Misconceptions
9
10 ### "Loading" is not "Parsing"
11
12 Many people incorrectly refer to YAML loading as "parsing," and some
13 implementations even name their load function `parse()`.
14 This is technically wrong and obscures what's really happening.
15
16 **Parsing** is just one stage in a multi-stage pipeline.
17 A parser applies grammar rules to a token stream.
18 **Loading** encompasses the entire transformation from YAML bytes to
19 native language values, which involves many more steps than just parsing.
20
21 ### YAML Processing is a Pipeline
22
23 YAML processing isn't a single monolithic operation.
24 Both loading and dumping are **pipelines of transforms**, where each stage:
25 - Has a single, well-defined responsibility
26 - Consumes input in one representation
27 - Produces output in a different representation
28 - Can be inspected and debugged independently
29
30 The two user-facing functions in go-yaml are `Load()` and `Dump()`, but
31 these are just the entry points to much deeper pipelines.
32
33 ## The Big Picture: Paired Pipelines
34
35 Load and Dump are mirror-image stacks of transforms with mostly matching
36 stages.
37 Data flows through different representations at each stage:
38
39 ```
40 LOAD (YAML → Native) DUMP (Native → YAML)
41 ──────────────────── ────────────────────
42 (Native Value) ←→ (Native Value)
43 ↑ ↓
44 Constructor Representer
45 ↑ ↓
46 (Nodes) (Nodes - tagged)
47 ↑ ↓
48 Resolver Desolver
49 ↑ ↓
50 (Nodes - unresolved) (Nodes - minimal tags)
51 ↑ ↓
52 Composer Serializer
53 ↑ ↓
54 (Events) ←→ (Events)
55 ↑ ↓
56 Parser ↓
57 ↑ ↓
58 (Tokens) ↓
59 ↑ ↓
60 Scanner Emitter
61 ↑ ↓
62 (Code Points) ←→ (Code Points)
63 ↑ ↓
64 Reader Writer
65 ↑ ↓
66 (Raw Bytes) ←→ (Raw Bytes)
67 ```
68
69 **Stack Symmetry Improvements**
70
71 The v4 refactor has made the stacks more symmetric:
72
73 1. **3-Stage Pipelines**: Both Load and Dump now have clean 3-stage pipelines:
74 - **Load:** Composer → Resolver → Constructor
75 - **Dump:** Representer → Desolver → Serializer
76 2. **Symmetric Tag Handling**:
77 - **Resolver** (Load) infers tags from content
78 - **Desolver** (Dump) removes inferable tags - NEW in v4
79 3. **Node Trees on Both Sides**: Both stacks work with Node trees as
80 intermediate representation
81 4. **Remaining Asymmetry**: Scanner+Parser on Load vs single Emitter on Dump
82 (due to YAML's complex indentation-based syntax)
83
84 ## Data Representations
85
86 Each stage consumes and produces data in specific representations:
87
88 ### Raw Bytes
89 The actual file contents or byte stream.
90 No interpretation has been done yet.
91
92 ### Code Points
93 Unicode characters after encoding detection and conversion.
94 The Reader handles UTF-8, UTF-16LE, and UTF-16BE encoding.
95
96 ### Tokens
97 Lexical units produced by the Scanner.
98 Examples: `BLOCK_MAPPING_START_TOKEN`, `SCALAR_TOKEN`, `KEY_TOKEN`, `VALUE_TOKEN`, `ANCHOR_TOKEN`.
99
100 Tokens have no nested structure — they're a flat stream that describes
101 YAML syntax at the character level (indentation, indicators, scalars).
102
103 ### Events
104 Structural units produced by the Parser.
105 Examples: `MAPPING_START_EVENT`, `MAPPING_END_EVENT`, `SCALAR_EVENT`, `ALIAS_EVENT`.
106
107 Events represent the grammar-level structure of YAML.
108 The Parser validates that tokens conform to YAML grammar rules and produces
109 a cleaner event stream.
110
111 ### Nodes
112 The tree structure built by the Composer.
113 Each Node has a kind (Document, Mapping, Sequence, Scalar, Alias), value,
114 tag, style, and position.
115
116 At this stage, anchors are resolved to build the graph structure, but
117 tags are still in their raw form (`!!str`, `!!int`, or implicit).
118
119 ### Repr (Representation Graph)
120 The node tree after the Resolver has processed tags.
121 Tags are resolved according to YAML tag resolution rules (implicit typing,
122 tag directives, etc.).
123
124 In go-yaml's implementation, this is still represented using Node
125 structures, but with all tags fully resolved.
126 The "Repr" is a conceptual stage from the YAML specification.
127
128 ### Native Value
129 Go language values: structs, maps, slices, strings, ints, etc.
130 This is what application code works with.
131
132 ## Loading Pipeline Stages
133
134 ### 1. Reader (Raw Bytes → Code Points)
135
136 **File**: `internal/libyaml/reader.go`
137
138 The Reader handles input encoding:
139 - Detects encoding (UTF-8, UTF-16LE, UTF-16BE) via BOM or heuristics
140 - Converts bytes to Unicode code points
141 - Buffers input for efficient scanning
142
143 This stage ensures the Scanner works with a consistent Unicode stream
144 regardless of input encoding.
145
146 ### 2. Scanner (Code Points → Tokens)
147
148 **File**: `internal/libyaml/scanner.go`
149
150 The Scanner performs lexical analysis:
151 - Tracks indentation levels
152 - Identifies block vs. flow context
153 - Detects simple keys (for compact mappings like `key: value`)
154 - Produces a stream of tokens
155
156 This is the most complex stage because YAML's indentation-based syntax
157 requires careful context tracking.
158
159 **Example tokens** for `foo: bar`:
160 - `STREAM_START_TOKEN`
161 - `BLOCK_MAPPING_START_TOKEN`
162 - `KEY_TOKEN`
163 - `SCALAR_TOKEN` (value: "foo")
164 - `VALUE_TOKEN`
165 - `SCALAR_TOKEN` (value: "bar")
166 - `BLOCK_END_TOKEN`
167 - `STREAM_END_TOKEN`
168
169 ### 3. Parser (Tokens → Events)
170
171 **File**: `internal/libyaml/parser.go`
172
173 The Parser applies YAML grammar:
174 - Consumes the token stream
175 - Validates structure according to YAML grammar rules
176 - Produces a cleaner event stream
177
178 **This is what "parsing" actually means** — applying grammar rules to a
179 token stream.
180
181 **Example events** for `foo: bar`:
182 - `STREAM_START_EVENT`
183 - `DOCUMENT_START_EVENT`
184 - `MAPPING_START_EVENT`
185 - `SCALAR_EVENT` (value: "foo")
186 - `SCALAR_EVENT` (value: "bar")
187 - `MAPPING_END_EVENT`
188 - `DOCUMENT_END_EVENT`
189 - `STREAM_END_EVENT`
190
191 ### 4. Composer (Events → Nodes)
192
193 **File**: `internal/libyaml/composer.go`
194
195 The Composer builds the node tree:
196 - Creates Document, Mapping, Sequence, and Scalar nodes
197 - Registers anchors and resolves aliases to build the graph structure
198 - Handles multi-document streams
199 - Attaches comments to nodes
200
201 The output is a tree (or graph, with aliases) of Node objects.
202
203 ### 5. Resolver (Nodes → Repr)
204
205 **File**: `internal/libyaml/resolver.go`
206
207 The Resolver handles tag resolution:
208 - Determines implicit tags based on scalar content
209 (e.g., `true` → `!!bool`, `42` → `!!int`, `foo` → `!!str`)
210 - Processes explicit tags (e.g., `!!str 42` forces string type)
211 - Applies tag directives from document headers
212 - Produces the Representation Graph
213
214 In go-yaml's implementation, the Repr is the node tree with fully
215 resolved tags.
216
217 ### 6. Constructor (Repr → Native Values)
218
219 **File**: `internal/libyaml/constructor.go`
220
221 The Constructor converts YAML to Go:
222 - Maps YAML types to Go types (`!!str` → string, `!!seq` → slice)
223 - Handles struct field mapping via reflection
224 - Calls custom `UnmarshalYAML` methods when defined
225 - Supports `encoding.TextUnmarshaler` interface
226 - Tracks alias depth for security
227
228 This is where YAML becomes usable Go data structures.
229
230 ## Dumping Pipeline Stages
231
232 ### 1. Representer (Native Values → Tagged Nodes)
233
234 **File**: `internal/libyaml/representer.go`
235
236 The Representer converts Go values to a tagged Node tree:
237 - Handles basic types (maps, structs, slices, strings, numbers, bools)
238 - Calls custom `MarshalYAML` methods when defined
239 - Supports `encoding.TextMarshaler` interface
240 - Makes style decisions (literal vs. quoted scalars, flow vs. block
241 collections)
242 - Processes struct tags (`yaml:"name,omitempty,flow"`)
243 - Assigns explicit tags to all nodes (`!!str`, `!!int`, `!!map`, etc.)
244 - **Returns a Node tree** (no longer emits events directly)
245
246 ### 2. Desolver (Tagged Nodes → Minimal Nodes)
247
248 **File**: `internal/libyaml/desolver.go`
249
250 The Desolver removes inferable tags (NEW in v4, inverse of Resolver):
251 - Walks the tagged node tree from Representer
252 - Removes tags that can be inferred during parsing
253 - Preserves explicit tags when content would be misresolved
254 - Produces cleaner YAML output without unnecessary type annotations
255 - **Example:** `!!str "hello"` becomes `hello`, but `!!str "42"` keeps the tag
256
257 ### 3. Serializer (Nodes → Events)
258
259 **File**: `internal/libyaml/serializer.go`
260
261 The Serializer linearizes the node tree:
262 - Walks the node tree depth-first
263 - Produces a stream of events
264 - Handles anchor assignment for sharing/circular references
265 - Determines whether collections should use flow style
266 - Pushes events to the Emitter
267
268 ### 4. Emitter (Events → Code Points)
269
270 **File**: `internal/libyaml/emitter.go`
271
272 The Emitter generates formatted YAML:
273 - Converts events to YAML text
274 - Handles indentation and line wrapping
275 - Chooses between different scalar styles (plain, quoted, literal,
276 folded)
277 - Produces Unicode code points
278 - Supports canonical output mode
279
280 This stage combines the work that Scanner+Parser do on the Load side.
281
282 ### 5. Writer (Code Points → Raw Bytes)
283
284 **File**: `internal/libyaml/writer.go`
285
286 The Writer handles output:
287 - Converts Unicode code points to bytes
288 - Handles output encoding
289 - Buffers writes for efficiency
290 - Writes to the output stream
291
292 ## Why This Architecture Matters
293
294 ### Single Responsibility
295
296 Each stage has one job and does it well.
297 This makes the code easier to understand, test, and maintain.
298
299 ### Debuggability
300
301 You can inspect intermediate representations at any stage.
302 The `go-yaml` CLI tool leverages this to show tokens, events, and nodes.
303
304 ### Extensibility
305
306 A plugin system allows hooking into any stage to customize behavior.
307 Want custom tag resolution? Hook the Resolver.
308 Want custom output formatting? Hook the Emitter.
309
310 ### Spec Compliance
311
312 The architecture follows the YAML specification's terminology and
313 processing model.
314 This makes go-yaml easier to understand for anyone familiar with the
315 YAML spec.
316
317 ## Debugging with the go-yaml CLI Tool
318
319 The `go-yaml` command-line tool can show you each stage of processing:
320
321 ```bash
322 # Show tokens
323 go-yaml -t <<< 'foo: bar'
324
325 # Show events
326 go-yaml -e <<< 'foo: bar'
327
328 # Show node tree
329 go-yaml -n <<< 'foo: bar'
330 ```
331
332 This is invaluable for understanding what's happening at each stage and
333 debugging parsing issues.
334
335 See the [main README](../README.md#the-go-yaml-cli-tool) for more details
336 on using the CLI tool.
337
338 ## Summary
339
340 YAML processing is a pipeline, not a single operation:
341
342 - **Loading** flows through: Reader → Scanner → Parser → Composer →
343 Resolver → Constructor
344 - **Dumping** flows through: Representer → Desolver → Serializer → Emitter
345 → Writer
346 - Each stage transforms data from one representation to another
347 - The v4 refactor has made the stacks more symmetric with 3-stage pipelines:
348 - **Load:** Composer → Resolver → Constructor
349 - **Dump:** Representer → Desolver → Serializer
350 - "Parsing" is just one stage (tokens → events), not the whole process
351
352 Understanding these stages helps you work with YAML more effectively,
353 debug issues faster, and appreciate the complexity hidden behind the
354 simple `yaml.Load()` and `yaml.Dump()` functions.