| 1 | go-yaml Internals |
| 2 | ================= |
| 3 | |
| 4 | This document analyzes the load and dump stacks in the go-yaml implementation, |
| 5 | documenting each stage's input/output forms, the transforms performed, and |
| 6 | identifying where processing happens in the "wrong places" that could be |
| 7 | refactored for cleaner API hooks. |
| 8 | |
| 9 | ``` |
| 10 | LOAD (YAML → Native) DUMP (Native → YAML) |
| 11 | ──────────────────── ──────────────────── |
| 12 | (Native Value) ←→ (Native Value) |
| 13 | ↑ ↓ |
| 14 | Constructor Representer |
| 15 | ↑ ↓ |
| 16 | (Nodes - tagged) ←→ (Nodes - tagged) |
| 17 | ↑ ↓ |
| 18 | Resolver Desolver |
| 19 | ↑ ↓ |
| 20 | (Nodes - untagged) ←→ (Nodes - untagged) |
| 21 | ↑ ↓ |
| 22 | Composer Serializer |
| 23 | ↑ ↓ |
| 24 | (Events) ←→ (Events) |
| 25 | ↑ ↓ |
| 26 | Parser Emitter |
| 27 | ↑ ↓ |
| 28 | (Tokens) ↓ |
| 29 | ↑ ↓ |
| 30 | Scanner ↓ |
| 31 | ↑ ↓ |
| 32 | (Code Points) ←→ (Code Points) |
| 33 | ↑ ↓ |
| 34 | Reader Writer |
| 35 | ↑ ↓ |
| 36 | (Raw Bytes) ←→ (Raw Bytes) |
| 37 | ``` |
| 38 | |
| 39 | See also: |
| 40 | - [Pipeline Overview Diagram](pipeline-overview.mmd) |
| 41 | - [Call Hierarchy Diagram](call-hierarchy.mmd) |
| 42 | - [Comment Flow Diagram](comment-flow.mmd) |
| 43 | |
| 44 | |
| 45 | ## Load Stack |
| 46 | |
| 47 | The load stack transforms YAML text into Go values through a series of stages. |
| 48 | |
| 49 | **Control Flow:** The load stack uses a pull-based call hierarchy. |
| 50 | Entry points |
| 51 | (such as `Load()`, `Loader.Load()`, or `Node.Load()`) orchestrate the |
| 52 | process by creating and coordinating the stages: |
| 53 | |
| 54 | - **Entry points** create a **Loader** which owns **Composer**, **Resolver**, |
| 55 | and **Constructor** |
| 56 | - **Entry points** call **Loader.Load()** which executes the 3-stage pipeline: |
| 57 | 1. **Composer.Compose()** creates Node tree with unresolved tags (calls |
| 58 | Parser for Events) |
| 59 | 2. **Resolver.Resolve()** determines implicit types for untagged scalars |
| 60 | 3. **Constructor.Construct()** converts Node tree to Go values |
| 61 | - **Composer** calls **Parser**.Parse() to get Events (Parser and Scanner share |
| 62 | the same struct) |
| 63 | - **Parser** calls its own **Scanner** methods (Scan via peekToken) to get |
| 64 | Tokens |
| 65 | - **Scanner** calls **Reader** functions (updateBuffer) to get more bytes |
| 66 | |
| 67 | |
| 68 | ### Reader |
| 69 | |
| 70 | Handles input buffering and character encoding detection/conversion. |
| 71 | |
| 72 | Info: |
| 73 | - File: internal/libyaml/reader.go (170 lines) |
| 74 | - Main Function: `func (parser *Parser) updateBuffer(length int) error` |
| 75 | - Input: `[]byte` or `io.Reader` |
| 76 | - Output: UTF-8 normalized bytes in `parser.buffer` |
| 77 | - Called From: |
| 78 | * Scanner ([`scanner.go`](../../internal/libyaml/scanner.go) / |
| 79 | `fetchNextToken()`) |
| 80 | - Important Processes: |
| 81 | * `reader.go / determineEncoding - Detects UTF-8/UTF-16 from BOM` |
| 82 | * `reader.go / updateRawBuffer - Reads more bytes from input source` |
| 83 | |
| 84 | Transforms: |
| 85 | * **Encoding detection from BOM** (UTF-8, UTF-16LE, UTF-16BE) |
| 86 | * **UTF-16 to UTF-8 conversion** with surrogate pair handling |
| 87 | * **YAML 1.2 character set validation** (Tab, LF, CR, printable ASCII, BMP, |
| 88 | supplementary planes) |
| 89 | * **UTF-8 sequence validation** |
| 90 | * **Input buffering** for lookahead |
| 91 | |
| 92 | Notes: |
| 93 | * Encoding is stored in `parser.encoding` field |
| 94 | * The reader is not a separate stage but integrated into the Parser struct |
| 95 | * Character validation rules: allowed characters are Tab (0x09), LF (0x0A), CR |
| 96 | (0x0D), printable ASCII (0x20-0x7E), BMP (U+0080-U+FFFD excluding |
| 97 | surrogates), and supplementary planes (U+10000-U+10FFFF) |
| 98 | |
| 99 | |
| 100 | ### Scanner |
| 101 | |
| 102 | Lexical analysis - converts raw bytes into tokens. |
| 103 | |
| 104 | Info: |
| 105 | - File: internal/libyaml/scanner.go (2599 lines) |
| 106 | - Main Function: `func (parser *Parser) Scan(token *Token) error` |
| 107 | - Input: UTF-8 bytes from reader buffer |
| 108 | - Output: `Token` struct |
| 109 | - Called From: |
| 110 | * Parser ([`parser.go`](../../internal/libyaml/parser.go) / `peekToken()`) |
| 111 | - Important Processes: |
| 112 | * `scanner.go / fetchMoreTokens - Ensures token queue has enough tokens` |
| 113 | * `scanner.go / fetchNextToken - Dispatches to token fetchers by character` |
| 114 | * `scanner.go / scanComments - Classifies comments as head/foot/line` |
| 115 | * `scanner.go / scanLineComment - Captures same-line comments` |
| 116 | * `reader.go / updateBuffer - Refills input buffer (calls Reader)` |
| 117 | |
| 118 | Transforms: |
| 119 | * **Character classification and dispatch** |
| 120 | ([`fetchNextToken()`](../../internal/libyaml/scanner.go)) |
| 121 | * **Flow level tracking** (`flow_level` field) |
| 122 | * **Indentation stack management** (`indent`, `indents` fields) |
| 123 | * **Simple key candidate tracking** (`simple_keys` stack) |
| 124 | * **Synthetic token generation** |
| 125 | (`BLOCK_SEQUENCE_START/BLOCK_MAPPING_START/BLOCK_END`) |
| 126 | * **Escape sequence processing** in quoted scalars |
| 127 | * **Line folding** in folded block scalars |
| 128 | * **Chomping behavior** for block scalars (`-` strip, `+` keep) |
| 129 | * **URI decoding** in tags |
| 130 | * **Comment tokenization** via `scanLineComment()` and `scanComments()` |
| 131 | * **Comment classification** (head/foot/line) based on indentation and context |
| 132 | |
| 133 | Notes: |
| 134 | * Scanner and Parser share the same `Parser` struct |
| 135 | * Tag handle and suffix remain separate at this stage (`Value` + `suffix` |
| 136 | fields) |
| 137 | * Scalar style is recorded (Plain, SingleQuoted, DoubleQuoted, Literal, Folded) |
| 138 | * 2-token lookahead requirement for comment association (see |
| 139 | [Comment Handling](#comment-handling-in-the-load-stack)) |
| 140 | * Comment processing details covered in |
| 141 | [Comment Handling](#comment-handling-in-the-load-stack) section |
| 142 | * Depth limits enforced: `max_flow_level` and `max_indents` both set to 10000 |
| 143 | (see [Security Limits](#security-limits-and-protections)) |
| 144 | * 23 token types defined: |
| 145 | - `NO_TOKEN` |
| 146 | - `STREAM_START_TOKEN` |
| 147 | - `STREAM_END_TOKEN` |
| 148 | - `VERSION_DIRECTIVE_TOKEN` |
| 149 | - `TAG_DIRECTIVE_TOKEN` |
| 150 | - `DOCUMENT_START_TOKEN` |
| 151 | - `DOCUMENT_END_TOKEN` |
| 152 | - `BLOCK_SEQUENCE_START_TOKEN` |
| 153 | - `BLOCK_MAPPING_START_TOKEN` |
| 154 | - `BLOCK_END_TOKEN` |
| 155 | - `FLOW_SEQUENCE_START_TOKEN` |
| 156 | - `FLOW_SEQUENCE_END_TOKEN` |
| 157 | - `FLOW_MAPPING_START_TOKEN` |
| 158 | - `FLOW_MAPPING_END_TOKEN` |
| 159 | - `BLOCK_ENTRY_TOKEN` |
| 160 | - `FLOW_ENTRY_TOKEN` |
| 161 | - `KEY_TOKEN` |
| 162 | - `VALUE_TOKEN` |
| 163 | - `ALIAS_TOKEN` |
| 164 | - `ANCHOR_TOKEN` |
| 165 | - `TAG_TOKEN` |
| 166 | - `SCALAR_TOKEN` |
| 167 | - `COMMENT_TOKEN` |
| 168 | |
| 169 | |
| 170 | ### Parser |
| 171 | |
| 172 | Syntactic analysis - converts token stream into event stream. |
| 173 | |
| 174 | Info: |
| 175 | - File: internal/libyaml/parser.go (1174 lines) |
| 176 | - Main Function: `func (parser *Parser) Parse(event *Event) error` |
| 177 | - Input: `Token` stream from Scanner (via internal `peekToken()`/`skipToken()`) |
| 178 | - Output: `Event` struct |
| 179 | - Called From: |
| 180 | * Composer ([`composer.go / Composer.peek()`](../../internal/libyaml/composer.go)) |
| 181 | * Composer ([`composer.go / Composer.expect()`](../../internal/libyaml/composer.go)) |
| 182 | - Important Processes: |
| 183 | * `parser.go / stateMachine - Dispatches to parser state handlers` |
| 184 | * `parser.go / peekToken - Looks at next token (calls Scanner)` |
| 185 | * `parser.go / skipToken - Consumes current token` |
| 186 | * `scanner.go / Scan - Gets next token from Scanner (same struct)` |
| 187 | * `parser.go / parseStreamStart - Handles stream start event` |
| 188 | * `parser.go / parseDocumentStart - Handles document boundaries` |
| 189 | * `parser.go / parseNode - Parses scalar/sequence/mapping nodes` |
| 190 | * `parser.go / UnfoldComments - Joins comment lines to tokens` |
| 191 | * `parser.go / setEventComments - Transfers comments to Event` |
| 192 | |
| 193 | Transforms: |
| 194 | * **LL(1) grammar production matching** (22 parser states): |
| 195 | - `PARSE_STREAM_START_STATE` |
| 196 | - `PARSE_IMPLICIT_DOCUMENT_START_STATE` |
| 197 | - `PARSE_DOCUMENT_START_STATE` |
| 198 | - `PARSE_DOCUMENT_CONTENT_STATE` |
| 199 | - `PARSE_DOCUMENT_END_STATE` |
| 200 | - `PARSE_BLOCK_NODE_STATE` |
| 201 | - `PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE` |
| 202 | - `PARSE_BLOCK_SEQUENCE_ENTRY_STATE` |
| 203 | - `PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE` |
| 204 | - `PARSE_BLOCK_MAPPING_FIRST_KEY_STATE` |
| 205 | - `PARSE_BLOCK_MAPPING_KEY_STATE` |
| 206 | - `PARSE_BLOCK_MAPPING_VALUE_STATE` |
| 207 | - `PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE` |
| 208 | - `PARSE_FLOW_SEQUENCE_ENTRY_STATE` |
| 209 | - `PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE` |
| 210 | - `PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE` |
| 211 | - `PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE` |
| 212 | - `PARSE_FLOW_MAPPING_FIRST_KEY_STATE` |
| 213 | - `PARSE_FLOW_MAPPING_KEY_STATE` |
| 214 | - `PARSE_FLOW_MAPPING_VALUE_STATE` |
| 215 | - `PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE` |
| 216 | - `PARSE_END_STATE` |
| 217 | * **Tag handle → full URI resolution** (`!!str` → `tag:yaml.org,2002:str`) |
| 218 | * **Token grouping** (anchor + tag + scalar tokens → single `SCALAR_EVENT`) |
| 219 | * **Comment attachment to events** via `UnfoldComments()` and |
| 220 | `setEventComments()` |
| 221 | * **`TAIL_COMMENT_EVENT` generation** for block-end foot comments |
| 222 | * **`splitStemComment()` processing** for comments preceding nested structures |
| 223 | * **Implicit/`quoted_implicit` flag calculation** |
| 224 | * **Block structure tokens → hierarchical event pairs** |
| 225 | |
| 226 | Notes: |
| 227 | * Tag handle/suffix split is lost here - only full URI remains |
| 228 | * The `Implicit` flag indicates whether tag was omitted in source |
| 229 | * Comment processing details covered in [Comment |
| 230 | Handling](#comment-handling-in-the-load-stack) section |
| 231 | |
| 232 | |
| 233 | ### Composer |
| 234 | |
| 235 | Builds the Node tree from the event stream. |
| 236 | |
| 237 | Info: |
| 238 | - File: internal/libyaml/composer.go (320 lines) |
| 239 | - Main Function: `func (c *Composer) Parse() *Node` |
| 240 | - Input: `Event` stream from owned Parser (via internal `peek()`/`expect()`) |
| 241 | - Output: `*Node` tree |
| 242 | - Called From: |
| 243 | * Entry point [`yaml.go / unmarshal()`](../../yaml.go) |
| 244 | * Entry point [`yaml.go / Decoder.Decode()`](../../yaml.go) |
| 245 | * Entry point [`constructor.go / |
| 246 | Construct()`](../../internal/libyaml/constructor.go) |
| 247 | - Important Processes: |
| 248 | * `composer.go / peek - Peeks at next event type (calls Parser)` |
| 249 | * `composer.go / expect - Consumes event of expected type (calls Parser)` |
| 250 | * `parser.go / Parser.Parse - Gets next event from owned Parser` |
| 251 | * `composer.go / node - Creates Node with tag/style` |
| 252 | * `composer.go / scalar - Builds ScalarNode from event` |
| 253 | * `composer.go / mapping - Builds MappingNode recursively` |
| 254 | * `composer.go / sequence - Builds SequenceNode recursively` |
| 255 | * `composer.go / document - Builds DocumentNode wrapper` |
| 256 | |
| 257 | Transforms: |
| 258 | * **Event sequence → tree structure** |
| 259 | * **Tag short-form normalization** (`tag:yaml.org,2002:str` → `!!str`) |
| 260 | * **Anchor registration** in map (`c.anchors`) |
| 261 | * **Alias name → pointer to target Node** |
| 262 | * **Style flag conversion** (libyaml styles → Node Style flags) |
| 263 | * **Comment transfer** from Event to Node |
| 264 | * **Comment reassignment logic** in mappings (foot → key, tail → key) |
| 265 | |
| 266 | Notes: |
| 267 | * Byte-level Index is lost here (only Line/Column preserved) |
| 268 | * Implicit document distinction is lost |
| 269 | * Tag resolution happens in the next stage (Resolver) |
| 270 | * Comment reassignment rules detailed in |
| 271 | [Comment Handling](#comment-handling-in-the-load-stack) section |
| 272 | |
| 273 | |
| 274 | ### Resolver |
| 275 | |
| 276 | Resolves tags to determine the type of each scalar value in the node tree. |
| 277 | |
| 278 | Info: |
| 279 | - File: internal/libyaml/resolver.go (300+ lines) |
| 280 | - Main Function: `func (r *Resolver) Resolve(node *Node)` |
| 281 | - Input: `*Node` tree with unresolved tags |
| 282 | - Output: Modified Node tree with resolved tags (in-place) |
| 283 | - Called From: |
| 284 | * Loader ([`loader.go:267`](../../internal/libyaml/loader.go) / |
| 285 | `Loader.Load()`) |
| 286 | - Important Processes: |
| 287 | * `resolver.go / Resolve - Walks node tree, resolves scalar tags` |
| 288 | * `resolver.go / resolveScalar - Infers tag based on content` |
| 289 | * `resolver.go / parseTimestamp - Parses ISO 8601 timestamps` |
| 290 | * `strconv / ParseInt - Parses signed integers` |
| 291 | * `strconv / ParseUint - Parses unsigned integers` |
| 292 | * `strconv / ParseFloat - Parses floating point numbers` |
| 293 | |
| 294 | Transforms: |
| 295 | * **Implicit tag resolution** based on scalar content (`true` → `!!bool`, `42` |
| 296 | → `!!int`) |
| 297 | * **YAML 1.1 compatibility handling** (sexagesimal, old bools) |
| 298 | * **Timestamp parsing** |
| 299 | * **Special value recognition** (`.nan`, `.inf`, `null`) |
| 300 | * **Recursive tree walking** to resolve all scalars in sequences and mappings |
| 301 | |
| 302 | Notes: |
| 303 | * Now a proper stage in the Load pipeline, called once between Composer and |
| 304 | Constructor |
| 305 | * Modifies the Node tree in-place (sets Tag field on ScalarNodes) |
| 306 | * The YAML spec treats Resolver as a distinct stage producing the |
| 307 | "Representation Graph" |
| 308 | * This refactor eliminates duplicate resolution calls that existed in the old |
| 309 | architecture |
| 310 | |
| 311 | |
| 312 | ### Constructor |
| 313 | |
| 314 | Converts Node tree into Go values. |
| 315 | |
| 316 | Info: |
| 317 | - File: internal/libyaml/constructor.go (1183 lines) |
| 318 | - Main Function: `func (c *Constructor) Construct(n *Node, out reflect.Value) |
| 319 | bool` |
| 320 | - Input: `*Node` tree (received from Composer via entry point) |
| 321 | - Output: `reflect.Value` (Go values modified in place) |
| 322 | - Called From: |
| 323 | * Entry point [`yaml.go / unmarshal()`](../../yaml.go) |
| 324 | * Entry point [`yaml.go / Decoder.Decode()`](../../yaml.go) |
| 325 | * Entry point [`node.go / Node.Decode()`](../../internal/libyaml/node.go) |
| 326 | - Important Processes: |
| 327 | * `constructor.go / prepare - Checks for Unmarshaler interface` |
| 328 | * `constructor.go / scalar - Converts ScalarNode to Go value` |
| 329 | * `constructor.go / mapping - Converts MappingNode to map/struct` |
| 330 | * `constructor.go / sequence - Converts SequenceNode to slice` |
| 331 | * `constructor.go / document - Unwraps DocumentNode` |
| 332 | * `constructor.go / alias - Follows alias pointer, reconstructs` |
| 333 | |
| 334 | Transforms: |
| 335 | * **Custom Unmarshaler interface detection and dispatch** |
| 336 | * **Duplicate key detection** (when `UniqueKeys` option enabled) - checks all |
| 337 | mapping keys |
| 338 | * **Alias expansion ratio protection** (billion laughs defense) - limits |
| 339 | constructs from alias expansion |
| 340 | * **Self-referential alias detection** - prevents infinite loops from aliases |
| 341 | containing themselves |
| 342 | * **Tag-based type conversion** using already-resolved tags from Resolver stage |
| 343 | * **`indicatedString()` check** for quoted scalars (quoted/literal scalars |
| 344 | force string type) |
| 345 | * **Merge key (`<<`) handling** - explicit keys take precedence, can merge |
| 346 | single mapping or sequence of mappings |
| 347 | * **Inline struct/map handling** (`,inline` tag) - one inline map per struct, |
| 348 | string keys required, unknown keys go there |
| 349 | * **Known fields enforcement** (`WithKnownFields` option) - rejects unknown |
| 350 | struct fields when enabled |
| 351 | * **Unhashable key error handling** - maps/slices as mapping keys trigger |
| 352 | errors |
| 353 | * **TextUnmarshaler support** - for scalar types only |
| 354 | * **YAML 1.1 boolean compatibility** - `yes/no/on/off` recognized for typed |
| 355 | bool targets |
| 356 | * **Type coercion** (YAML types → Go types) |
| 357 | * **Alias expansion** (full reconstruction each time) |
| 358 | * **Binary base64 decoding** (`!!binary` tag) |
| 359 | * **Struct field mapping** via `getStructInfo()` |
| 360 | |
| 361 | Notes: |
| 362 | * Now receives fully-resolved tags from the Resolver stage (no duplicate |
| 363 | resolution) |
| 364 | * Aliases are fully reconstructed each time (not shared) |
| 365 | * Duplicate key detection (in |
| 366 | [`mapping()`](../../internal/libyaml/constructor.go) function) compares all |
| 367 | keys in mappings when enabled |
| 368 | * Merge key rules: explicit keys take precedence over merged keys, can merge a |
| 369 | single mapping or a sequence of mappings |
| 370 | * Inline rules: only one inline map allowed per struct, requires string keys, |
| 371 | unknown keys are stored in the inline map field |
| 372 | * Indicated strings (quoted or literal style) force string type regardless of |
| 373 | content |
| 374 | * Node tree, comments, style, anchors, positions are all discarded |
| 375 | |
| 376 | |
| 377 | ## Comment Handling in the Load Stack |
| 378 | |
| 379 | Comments flow through Scanner → Parser → Composer with classification, |
| 380 | attachment, and reassignment at each stage. |
| 381 | The goal is to preserve comments and associate them with the appropriate YAML |
| 382 | nodes so they can be round-tripped or presented in the Node tree. |
| 383 | |
| 384 | See also: [Comment Flow Diagram](comment-flow.mmd) |
| 385 | |
| 386 | ### Comment Types |
| 387 | |
| 388 | Comments are classified into several types based on their position relative to |
| 389 | nodes: |
| 390 | |
| 391 | | Type | Purpose | Example | |
| 392 | |------|---------|---------| |
| 393 | | `HeadComment` | Lines preceding a node (no blank line separation) | `# This is a comment\nkey: value` | |
| 394 | | `LineComment` | Same line as a node, after its value | `key: value # inline comment` | |
| 395 | | `FootComment` | After a node, before any blank lines | `key: value\n# trailing comment` | |
| 396 | | `TailComment` | Internal: foot comment at end of block mapping value | Used during parsing only | |
| 397 | | `stem_comment` | Internal: comment on entry before nested structure | Used during parsing only | |
| 398 | |
| 399 | ### Scanner: Comment Tokenization |
| 400 | |
| 401 | The scanner identifies and classifies comments as it processes tokens: |
| 402 | |
| 403 | - **`scanLineComment()`** - Captures same-line comments (when no newlines have |
| 404 | occurred since the last token) |
| 405 | - **`scanComments()`** - Main classifier that determines head/foot/line based |
| 406 | on: |
| 407 | - Indentation relative to `next_indent` |
| 408 | - Flow context (all remaining comments become foot comments in `[...]` or |
| 409 | `{...}`) |
| 410 | - Empty line boundaries (blank lines separate head from foot) |
| 411 | - **2-token lookahead requirement** |
| 412 | ([`scanLineComment()`](../../internal/libyaml/scanner.go)) - Scanner needs to |
| 413 | peek ahead to properly associate comments |
| 414 | - **Special case**: Sequence entry line comments are transformed to head |
| 415 | comments |
| 416 | |
| 417 | Location: [`scanner.go`](../../internal/libyaml/scanner.go) / `scanComments()` |
| 418 | and `scanLineComment()` |
| 419 | |
| 420 | ### Parser: Comment Attachment |
| 421 | |
| 422 | The parser accumulates comments from tokens and attaches them to events: |
| 423 | |
| 424 | - **`UnfoldComments()`** - Joins accumulated comment lines to tokens based on |
| 425 | position |
| 426 | - **Parser comment fields** - `HeadComment`, `LineComment`, `FootComment` |
| 427 | accumulate during token processing |
| 428 | - **`setEventComments()`** - Transfers parser comment fields to Event struct |
| 429 | - **`TAIL_COMMENT_EVENT`** - Special event type for foot comments at block ends |
| 430 | (e.g., end of mapping value) |
| 431 | - **`splitStemComment()`** - Handles comments on entries preceding nested |
| 432 | structures (splits into head comment for the nested item) |
| 433 | - **Document header splitting** - HeadComment is split at empty lines; content |
| 434 | after blank goes to FootComment |
| 435 | |
| 436 | Location: [`parser.go`](../../internal/libyaml/parser.go) / `UnfoldComments()`, |
| 437 | `setEventComments()`, and `splitStemComment()` |
| 438 | |
| 439 | ### Composer: Comment Transfer and Reassignment |
| 440 | |
| 441 | The composer transfers comments from events to nodes and applies reassignment |
| 442 | logic: |
| 443 | |
| 444 | - **Basic transfer**: Event.{Head,Line,Foot}Comment → |
| 445 | Node.{Head,Line,Foot}Comment |
| 446 | - **Mapping reassignment rules** (in `mapping()` function): |
| 447 | 1. **Key FootComment reassignment for dedented comments** - If a comment is |
| 448 | dedented (less indented than the key), it moves from key's FootComment to |
| 449 | the mapping's FootComment |
| 450 | 2. **Value FootComment transfers to Key** - When the value has a FootComment |
| 451 | but the key doesn't, the value's FootComment becomes the key's FootComment |
| 452 | 3. **TAIL_COMMENT_EVENT FootComment goes to Key** - Tail comments (from |
| 453 | block-end events) are assigned to the key's FootComment |
| 454 | 4. **Final mapping FootComment moves to last key** - At the end of a mapping, |
| 455 | if the mapping has a FootComment, it's moved to the last key's FootComment |
| 456 | |
| 457 | Location: [`composer.go`](../../internal/libyaml/composer.go) / `mapping()` |
| 458 | function |
| 459 | |
| 460 | ### Edge Cases |
| 461 | |
| 462 | Several edge cases require special handling: |
| 463 | |
| 464 | - **Sequence entry line-to-head transformation** - Line comments on sequence |
| 465 | entries (`- item # comment`) become head comments of the item |
| 466 | - **Block end token skip for head comments** - When `BLOCK_END` tokens have |
| 467 | head comments, they're handled specially |
| 468 | - **Flow context closure** - When closing `]` or `}` in flow style, all |
| 469 | remaining comments become foot comments |
| 470 | - **Document header splitting at empty lines** - Head comments with embedded |
| 471 | blank lines are split (before blank stays head, after blank becomes foot) |
| 472 | |
| 473 | |
| 474 | ## Security Limits and Protections |
| 475 | |
| 476 | go-yaml includes several security features to prevent denial-of-service |
| 477 | attacks. |
| 478 | |
| 479 | ### Depth Limits (Scanner) |
| 480 | |
| 481 | The scanner enforces maximum nesting depth to prevent stack overflow: |
| 482 | - `max_flow_level = 10000` - Maximum nesting in flow style `[[[...]]]` or |
| 483 | `{{{...}}}` |
| 484 | - `max_indents = 10000` - Maximum nesting via indentation (block style) |
| 485 | |
| 486 | Location: [`scanner.go`](../../internal/libyaml/scanner.go) / flow level and |
| 487 | indent tracking |
| 488 | |
| 489 | ### Alias Expansion Ratio (Constructor) |
| 490 | |
| 491 | Prevents "billion laughs" style attacks via nested alias expansion: |
| 492 | - Documents under 400,000 constructs: allows up to 99% from alias expansion |
| 493 | - Documents over 4,000,000 constructs: allows only 10% from alias expansion |
| 494 | - Scales smoothly between thresholds |
| 495 | |
| 496 | Error: `"document contains excessive aliasing"` |
| 497 | |
| 498 | Location: [`constructor.go`](../../internal/libyaml/constructor.go) / |
| 499 | `allowedAliasRatio()` function and expansion check in `sequence()` |
| 500 | |
| 501 | ### Self-Referential Alias Detection (Constructor) |
| 502 | |
| 503 | Detects and prevents infinite loops from aliases referencing themselves: |
| 504 | - Tracks nodes being expanded in `c.aliases` map |
| 505 | - Error: `"anchor '%s' value contains itself"` |
| 506 | |
| 507 | Location: [`constructor.go`](../../internal/libyaml/constructor.go) / `alias()` |
| 508 | function |
| 509 | |
| 510 | |
| 511 | ## Dump Stack |
| 512 | |
| 513 | The dump stack transforms Go values into YAML text through a symmetric 3-stage |
| 514 | pipeline. |
| 515 | |
| 516 | **Control Flow:** The dump stack uses a push-based call hierarchy. |
| 517 | Entry points (such as `Dump()`, `Dumper.Dump()`, or `Node.Dump()`) orchestrate |
| 518 | the process by creating and coordinating the stages: |
| 519 | |
| 520 | - **Entry points** create a **Dumper** which owns **Representer**, |
| 521 | **Desolver**, and **Serializer** |
| 522 | - **Entry points** call **Dumper.Dump()** which executes the 3-stage pipeline: |
| 523 | 1. **Representer.Represent()** converts Go values to tagged Node tree |
| 524 | 2. **Desolver.Desolve()** removes inferable tags to minimize output |
| 525 | 3. **Serializer.Serialize()** converts Node tree to Events and pushes to |
| 526 | Emitter |
| 527 | - **Serializer** owns an **Emitter** and calls emit() to push Events |
| 528 | - **Emitter** accumulates Events, formats output, and calls **Writer** to flush |
| 529 | bytes |
| 530 | |
| 531 | |
| 532 | ### Representer |
| 533 | |
| 534 | Converts Go values to a tagged Node tree (Stage 1 of Dump pipeline). |
| 535 | |
| 536 | Info: |
| 537 | - File: internal/libyaml/representer.go (600+ lines) |
| 538 | - Main Function: `func (r *Representer) Represent(tag string, in reflect.Value) |
| 539 | *Node` |
| 540 | - Input: `reflect.Value` + `Options` |
| 541 | - Output: `*Node` tree with explicit tags |
| 542 | - Called From: |
| 543 | * Dumper ([`dumper.go:116`](../../internal/libyaml/dumper.go) / |
| 544 | `Dumper.Dump()`) |
| 545 | - Important Processes: |
| 546 | * `representer.go / marshal - Dispatches by Go type` |
| 547 | * `representer.go / mapv - Marshals map with sorted keys` |
| 548 | * `representer.go / structv - Marshals struct fields` |
| 549 | * `representer.go / slicev - Marshals slice/array` |
| 550 | * `representer.go / stringv - Marshals string with style choice` |
| 551 | * `representer.go / intv - Marshals integer values` |
| 552 | * `representer.go / floatv - Marshals floating point values` |
| 553 | |
| 554 | Transforms: |
| 555 | * **Go type dispatch** ([`marshal()`](../../internal/libyaml/representer.go) |
| 556 | type switch) |
| 557 | * **Custom Marshaler interface detection and dispatch** |
| 558 | * **TextMarshaler support** - detects and calls TextMarshaler interface methods |
| 559 | * **Struct field ordering and filtering** (exported, by tag, omitempty) |
| 560 | * **Map key sorting** (natural sort with numeric awareness) - ensures |
| 561 | deterministic output |
| 562 | * **Explicit tag assignment** - all nodes get explicit tags (e.g., `!!str`, |
| 563 | `!!int`, `!!map`) |
| 564 | * **YAML 1.1 compatibility checks** (`isBase60Float()`, `isOldBool()`) |
| 565 | * **Style selection** (literal for multiline strings, flow from struct tags) |
| 566 | * **Binary data base64 encoding** - non-UTF-8 strings automatically tagged |
| 567 | `!!binary` and base64 encoded |
| 568 | * **Anchor assignment** for shared/circular references |
| 569 | |
| 570 | Notes: |
| 571 | * Now returns `*Node` instead of emitting events directly |
| 572 | * All output nodes have explicit tags - Desolver stage removes inferable ones |
| 573 | * Map key sorting ensures deterministic output by using natural sort with |
| 574 | numeric awareness |
| 575 | * This stage is now symmetric with Constructor on the Load side |
| 576 | |
| 577 | |
| 578 | ### Desolver |
| 579 | |
| 580 | Removes inferable tags from Node tree (Stage 2 of Dump pipeline, inverse of |
| 581 | Resolver). |
| 582 | |
| 583 | Info: |
| 584 | - File: internal/libyaml/desolver.go (150+ lines) |
| 585 | - Main Function: `func (d *Desolver) Desolve(node *Node)` |
| 586 | - Input: `*Node` tree with explicit tags |
| 587 | - Output: Modified Node tree with minimal tags (in-place) |
| 588 | - Called From: |
| 589 | * Dumper ([`dumper.go:119`](../../internal/libyaml/dumper.go) / |
| 590 | `Dumper.Dump()`) |
| 591 | - Important Processes: |
| 592 | * `desolver.go / Desolve - Walks node tree, removes inferable tags` |
| 593 | * `desolver.go / desolveScalar - Checks if tag can be inferred` |
| 594 | * `desolver.go / canInferTag - Tests if value would resolve to same tag` |
| 595 | |
| 596 | Transforms: |
| 597 | * **Tag elision** for scalars where tag can be inferred (`!!str "hello"` → |
| 598 | `hello`) |
| 599 | * **Recursive tree walking** to process all scalars in sequences and mappings |
| 600 | * **Preserve explicit tags** when content would be misresolved (e.g., `!!str |
| 601 | "42"`) |
| 602 | * **YAML 1.1 compatibility awareness** (checks for ambiguous old-style values) |
| 603 | |
| 604 | Notes: |
| 605 | * NEW stage in v4, makes Dump symmetric with Load (mirrors Resolver) |
| 606 | * Modifies the Node tree in-place (clears Tag field when inferable) |
| 607 | * This is the inverse operation of Resolver - while Resolver adds tags based on |
| 608 | content, Desolver removes tags that can be inferred |
| 609 | * Results in cleaner YAML output without unnecessary type annotations |
| 610 | * Called between Representer and Serializer in the dump pipeline |
| 611 | |
| 612 | |
| 613 | ### Serializer |
| 614 | |
| 615 | Converts Node tree to events (Stage 3 of Dump pipeline). |
| 616 | |
| 617 | Info: |
| 618 | - File: internal/libyaml/serializer.go (250+ lines) |
| 619 | - Main Function: `func (s *Serializer) Serialize(node *Node)` |
| 620 | - Input: `*Node` tree with minimal tags (from Desolver) |
| 621 | - Output: Events pushed to owned Emitter |
| 622 | - Called From: |
| 623 | * Dumper ([`dumper.go:122`](../../internal/libyaml/dumper.go) / |
| 624 | `Dumper.Dump()`) |
| 625 | - Important Processes: |
| 626 | * `serializer.go / emit - Sends event to owned Emitter` |
| 627 | * `serializer.go / node (recursive) - Walks child nodes` |
| 628 | * `serializer.go / isSimpleCollection - Checks if flow style appropriate` |
| 629 | * `emitter.go / Emitter.Emit - Emits events (owned Emitter)` |
| 630 | |
| 631 | Transforms: |
| 632 | * **Node tree → event stream** |
| 633 | * **Recursive tree walking** to emit events for all nodes |
| 634 | * **Flow style detection for simple collections** (`WithFlowSimpleCollections` |
| 635 | option) - automatically uses flow style for eligible collections |
| 636 | * **Comment placement/shifting** (foot → tail) |
| 637 | * **Style flag interpretation** (converts Node.Style to Event.Style) |
| 638 | * **Anchor emission** for nodes that need aliasing |
| 639 | * **Invalid UTF-8 → base64** conversion for binary data |
| 640 | |
| 641 | Notes: |
| 642 | * Now a proper stage that owns the Emitter (was part of Representer before) |
| 643 | * Receives Node tree with tags already optimized by Desolver stage |
| 644 | * Simple collection = all scalar children, fits within line width |
| 645 | * This stage is now symmetric with Composer on the Load side |
| 646 | |
| 647 | |
| 648 | ### Emitter |
| 649 | |
| 650 | Converts events to YAML text output. |
| 651 | |
| 652 | Info: |
| 653 | - File: internal/libyaml/emitter.go (2075 lines) |
| 654 | - Main Function: `func (emitter *Emitter) Emit(event *Event) error` |
| 655 | - Input: `Event` stream (queued in `emitter.events`) |
| 656 | - Output: UTF-8 bytes to `emitter.buffer` |
| 657 | - Called From: |
| 658 | * Representer ([`representer.go / |
| 659 | Representer.must()`](../../internal/libyaml/representer.go)) |
| 660 | * Representer ([`representer.go / |
| 661 | Representer.emit()`](../../internal/libyaml/representer.go)) |
| 662 | - Important Processes: |
| 663 | * `emitter.go / needMoreEvents - Checks if more events needed for lookahead` |
| 664 | * `emitter.go / analyzeEvent - Analyzes scalar/tag for style decisions` |
| 665 | * `emitter.go / stateMachine - Dispatches to emitter state handlers` |
| 666 | * `emitter.go / selectScalarStyle - Final style selection (can override)` |
| 667 | * `emitter.go / writeScalar - Writes scalar with chosen style` |
| 668 | * `writer.go / flush - Flushes buffer to output (calls Writer)` |
| 669 | |
| 670 | Transforms: |
| 671 | * **Event accumulation** for lookahead decisions |
| 672 | * **Final style selection** (`selectScalarStyle()` can override earlier choices) |
| 673 | * **Simple key eligibility check** (length ≤128, no multiline) |
| 674 | * **Block vs flow style** (context-dependent) |
| 675 | * **Scalar analysis** for style validity (`analyzeScalar()`) |
| 676 | * **Line wrapping** at `best_width` |
| 677 | * **Indentation management** |
| 678 | * **Escape sequence encoding** |
| 679 | * **Tag directive shortening** |
| 680 | |
| 681 | Notes: |
| 682 | * Emitter can override style decisions made by Representer/Serializer |
| 683 | * Style decisions are split across multiple stages |
| 684 | |
| 685 | |
| 686 | ### Writer |
| 687 | |
| 688 | Flushes output buffer to destination. |
| 689 | |
| 690 | Info: |
| 691 | - File: internal/libyaml/writer.go (32 lines) |
| 692 | - Main Function: `func (emitter *Emitter) flush() error` |
| 693 | - Input: `emitter.buffer` |
| 694 | - Output: bytes to `write_handler` callback |
| 695 | - Called From: |
| 696 | * Emitter ([`emitter.go / put()`](../../internal/libyaml/emitter.go)) |
| 697 | - Important Processes: |
| 698 | * `write_handler callback - Configured output destination` |
| 699 | |
| 700 | Transforms: |
| 701 | * **Buffer flush** to output destination |
| 702 | |
| 703 | Notes: |
| 704 | * Very simple - just calls the configured write handler |
| 705 | |
| 706 | |
| 707 | ## Intermediate Forms |
| 708 | |
| 709 | The data representations passed between stages. |
| 710 | |
| 711 | |
| 712 | ### Bytes |
| 713 | |
| 714 | Raw input/output bytes. |
| 715 | |
| 716 | At input: Raw bytes from file or string, potentially any encoding (UTF-8, |
| 717 | UTF-16LE, UTF-16BE). |
| 718 | |
| 719 | At output: UTF-8 encoded YAML text. |
| 720 | |
| 721 | |
| 722 | ### Token |
| 723 | |
| 724 | Scanner output - lexical tokens. |
| 725 | |
| 726 | ```go |
| 727 | type Token struct { |
| 728 | Type TokenType // SCALAR_TOKEN, ALIAS_TOKEN, TAG_TOKEN, etc. |
| 729 | StartMark Mark // Position: Index, Line, Column |
| 730 | EndMark Mark |
| 731 | encoding Encoding // For STREAM_START_TOKEN only |
| 732 | Value []byte // Scalar value, anchor name, or tag handle |
| 733 | suffix []byte // Tag suffix (for TAG_TOKEN) |
| 734 | prefix []byte // Tag directive prefix |
| 735 | Style ScalarStyle // Plain, SingleQuoted, DoubleQuoted, Literal, Folded |
| 736 | major, minor int8 // For VERSION_DIRECTIVE_TOKEN |
| 737 | } |
| 738 | ``` |
| 739 | |
| 740 | Location: [`yaml.go`](../../internal/libyaml/yaml.go) / `Token` struct |
| 741 | definition |
| 742 | |
| 743 | Notes: |
| 744 | * Tag handle and suffix are still separate here |
| 745 | * Full byte-level position (Index) is available |
| 746 | * For the complete list of 23 token types, see [Scanner Notes](#scanner) |
| 747 | |
| 748 | |
| 749 | ### Event |
| 750 | |
| 751 | Parser output - syntactic events. |
| 752 | |
| 753 | ```go |
| 754 | type Event struct { |
| 755 | Type EventType // SCALAR_EVENT, MAPPING_START_EVENT, etc. |
| 756 | StartMark Mark |
| 757 | EndMark Mark |
| 758 | encoding Encoding |
| 759 | versionDirective *VersionDirective |
| 760 | tagDirectives []TagDirective |
| 761 | HeadComment []byte |
| 762 | LineComment []byte |
| 763 | FootComment []byte |
| 764 | TailComment []byte |
| 765 | Anchor []byte |
| 766 | Tag []byte // FULL resolved URI (not handle+suffix) |
| 767 | Value []byte |
| 768 | Implicit bool // Was tag omitted? |
| 769 | quoted_implicit bool // Was tag omitted for quoted style? |
| 770 | Style Style |
| 771 | } |
| 772 | ``` |
| 773 | |
| 774 | Location: [`yaml.go`](../../internal/libyaml/yaml.go) / `Event` struct |
| 775 | definition |
| 776 | |
| 777 | Notes: |
| 778 | * Tag is now full URI - handle/suffix split is lost |
| 779 | * Comments are attached |
| 780 | * 11 event types defined: |
| 781 | - `STREAM_START_EVENT` |
| 782 | - `STREAM_END_EVENT` |
| 783 | - `DOCUMENT_START_EVENT` |
| 784 | - `DOCUMENT_END_EVENT` |
| 785 | - `ALIAS_EVENT` |
| 786 | - `SCALAR_EVENT` |
| 787 | - `SEQUENCE_START_EVENT` |
| 788 | - `SEQUENCE_END_EVENT` |
| 789 | - `MAPPING_START_EVENT` |
| 790 | - `MAPPING_END_EVENT` |
| 791 | - `TAIL_COMMENT_EVENT` |
| 792 | |
| 793 | |
| 794 | ### Node |
| 795 | |
| 796 | Composer output - tree structure. |
| 797 | |
| 798 | ```go |
| 799 | type Node struct { |
| 800 | Kind Kind // DocumentNode, SequenceNode, MappingNode, ScalarNode, AliasNode |
| 801 | Style Style // TaggedStyle, DoubleQuotedStyle, LiteralStyle, FlowStyle, etc. |
| 802 | Tag string // SHORT form tag (!!str, !!int, etc.) |
| 803 | Value string // Scalar content (unescaped, unquoted) |
| 804 | Anchor string |
| 805 | Alias *Node // Points to target Node for AliasNode |
| 806 | Content []*Node // Children for Document/Sequence/Mapping |
| 807 | HeadComment string |
| 808 | LineComment string |
| 809 | FootComment string |
| 810 | Line, Column int // NOTE: Byte Index is lost |
| 811 | // StreamNode-specific: |
| 812 | Encoding Encoding |
| 813 | Version *StreamVersionDirective |
| 814 | TagDirectives []StreamTagDirective |
| 815 | } |
| 816 | ``` |
| 817 | |
| 818 | Location: [`node.go`](../../internal/libyaml/node.go) / `Node` struct |
| 819 | definition |
| 820 | |
| 821 | Notes: |
| 822 | * Tag is short form - full URI is lost |
| 823 | * Byte Index is lost - only Line/Column remain |
| 824 | * 6 node kinds: |
| 825 | - `DocumentNode` |
| 826 | - `SequenceNode` |
| 827 | - `MappingNode` |
| 828 | - `ScalarNode` |
| 829 | - `AliasNode` |
| 830 | - `StreamNode` |
| 831 | * 6 style flags: |
| 832 | - `TaggedStyle` |
| 833 | - `DoubleQuotedStyle` |
| 834 | - `SingleQuotedStyle` |
| 835 | - `LiteralStyle` |
| 836 | - `FoldedStyle` |
| 837 | - `FlowStyle` |
| 838 | * `indicatedString()` method determines if a scalar skips tag resolution |
| 839 | (quoted or literal style) |
| 840 | * `shouldUseLiteralStyle()` heuristic for multi-line strings decides between |
| 841 | literal block style and quoted style |
| 842 | |
| 843 | |
| 844 | ### Repr (Representation Graph) |
| 845 | |
| 846 | The Node tree after tag resolution. |
| 847 | |
| 848 | In the YAML specification, the Representation Graph is a distinct stage where |
| 849 | all tags have been fully resolved. |
| 850 | In go-yaml's implementation, this is still represented using Node structures |
| 851 | with resolved tags. |
| 852 | |
| 853 | The "Repr" is conceptual - there's no separate struct. |
| 854 | The transformation from Nodes to Repr happens when `resolve()` is called to |
| 855 | determine implicit tags. |
| 856 | |
| 857 | |
| 858 | ### Native Value |
| 859 | |
| 860 | Go language values: structs, maps, slices, strings, ints, etc. |
| 861 | |
| 862 | This is the final output of the Load stack and the input to the Dump stack. |
| 863 | Represented as `reflect.Value` internally. |
| 864 | |
| 865 | |
| 866 | ## Potential Problems and Inconsistencies |
| 867 | |
| 868 | ### 1. ~~resolve() Called in Four Places~~ FIXED ✓ |
| 869 | |
| 870 | **Status:** This problem has been resolved in the current refactor. |
| 871 | |
| 872 | **Old Problem:** The `resolve()` function was called from 4 different places: |
| 873 | - Composer (to set Node.Tag) |
| 874 | - Constructor (to get typed value) - duplicate work |
| 875 | - Representer (to check if quoting needed) |
| 876 | - Serializer (to check if tag can be elided) |
| 877 | |
| 878 | **Solution Implemented:** |
| 879 | - **Load Stack:** Resolver is now a proper stage with `Resolve()` method, |
| 880 | called once in `Loader.Load()` between Composer and Constructor |
| 881 | - **Dump Stack:** Desolver is a new stage with `Desolve()` method, called once |
| 882 | in `Dumper.Dump()` between Representer and Serializer |
| 883 | - **Result:** Both stacks now have clean 3-stage pipelines with symmetric tag |
| 884 | resolution/desolving stages |
| 885 | |
| 886 | The pipelines are now: |
| 887 | - **Load:** Composer → Resolver → Constructor |
| 888 | - **Dump:** Representer → Desolver → Serializer |
| 889 | |
| 890 | |
| 891 | ### 2. Style Decisions Split Across Stages |
| 892 | |
| 893 | **Load:** Scanner → Parser → Composer → Constructor (each touches style) |
| 894 | |
| 895 | **Dump:** Representer → Serializer → Emitter (each can override style) |
| 896 | |
| 897 | **Problem:** Hard to control or predict final output style. |
| 898 | Emitter can override everything. |
| 899 | |
| 900 | **Better:** Make style decisions once and respect them, or clearly separate |
| 901 | "hints" from "requirements". |
| 902 | |
| 903 | |
| 904 | ### 3. Information Lost at Each Stage |
| 905 | |
| 906 | | Information | Lost At | Impact | |
| 907 | |-------------|---------|--------| |
| 908 | | Tag handle/suffix split | Parser | Can't reconstruct `!custom!type` | |
| 909 | | Byte-level Index | Composer | Less precise error positions | |
| 910 | | Implicit document flag | Composer | Can't round-trip explicit `---` | |
| 911 | | Full tag URI | Composer | Can't round-trip verbatim tags | |
| 912 | |
| 913 | |
| 914 | ### 4. YAML 1.1 Compatibility Scattered |
| 915 | |
| 916 | These checks appear in multiple files: |
| 917 | - `isBase60Float()` - representer.go, resolver.go |
| 918 | - `isOldBool()` - representer.go, resolver.go |
| 919 | - YAML 1.1 bool values (y/Y/yes/Yes/YES) - resolver.go |
| 920 | |
| 921 | **Problem:** No single configuration point for YAML version semantics. |
| 922 | |
| 923 | |
| 924 | ### 5. ~~Representer Has Parser Logic~~ FIXED ✓ |
| 925 | |
| 926 | **Status:** This problem has been resolved in the current refactor. |
| 927 | |
| 928 | **Old Problem:** The Representer called `resolve()` to check if strings would |
| 929 | be misresolved - this was parser-era logic living in the dump stack. |
| 930 | |
| 931 | **Solution Implemented:** The Desolver stage now handles tag removal using the |
| 932 | same resolution logic, but as a proper inverse operation of the Resolver. |
| 933 | The Representer no longer needs to call resolution functions - it simply |
| 934 | creates a fully-tagged Node tree, and the Desolver removes inferable tags in a |
| 935 | separate stage. |
| 936 | |
| 937 | **Result:** Clean separation of concerns - Representer focuses on Go→Node |
| 938 | conversion, Desolver handles tag optimization. |
| 939 | |
| 940 | |
| 941 | ### 6. Scanner and Parser Share Struct |
| 942 | |
| 943 | Both stages use the `Parser` struct, making it hard to: |
| 944 | - Expose tokens separately from events |
| 945 | - Have clean API boundaries between stages |
| 946 | |
| 947 | |
| 948 | ### 7. v4 vs Legacy Default Differences |
| 949 | |
| 950 | Different entry points use different default settings, which can cause |
| 951 | inconsistent behavior: |
| 952 | |
| 953 | | Setting | v4 Defaults | Legacy Defaults | |
| 954 | |---------|-------------|-----------------| |
| 955 | | Indent | 2 | 4 | |
| 956 | | CompactSeqIndent | true | false | |
| 957 | | LineWidth | 80 | -1 (unlimited) | |
| 958 | |
| 959 | `Load/Dump` use v4 defaults; `Marshal/Unmarshal` use Legacy defaults. |
| 960 | |
| 961 | Location: [`options.go`](../../internal/libyaml/options.go) / `Options` struct |
| 962 | v4 defaults and `LegacyOptions` variable |
| 963 | |
| 964 | **Problem:** Users may see different formatting depending on which API they |
| 965 | use, even with identical data. |
| 966 | |
| 967 | |
| 968 | ## Anything Else I Missed? |
| 969 | |
| 970 | Areas that may need deeper investigation: |
| 971 | - Anchor/alias reconstruction behavior |
| 972 | - Error propagation and position reporting |
| 973 | - The relationship between root package types and internal/libyaml types |
| 974 | |
| 975 | |
| 976 | ## Glossary |
| 977 | |
| 978 | ### A |
| 979 | |
| 980 | **Alias** - A YAML reference to a previously defined anchor, allowing reuse of |
| 981 | content. |
| 982 | Represented with `*name` syntax in YAML. |
| 983 | In go-yaml, AliasNode points to the target Node. |
| 984 | |
| 985 | **Anchor** - A named marker (`&name`) that identifies a YAML node for later |
| 986 | reference via aliases. |
| 987 | Stored as a string in Node/Event/Token structs. |
| 988 | |
| 989 | ### B |
| 990 | |
| 991 | **Billion Laughs Attack** - A denial-of-service attack using nested aliases to |
| 992 | cause exponential expansion. |
| 993 | go-yaml protects against this with alias expansion ratio limits. |
| 994 | |
| 995 | **Block Style** - YAML's indentation-based syntax for collections and scalars. |
| 996 | Examples: indented mappings/sequences, literal blocks (`|`), folded blocks |
| 997 | (`>`). |
| 998 | |
| 999 | **BOM (Byte Order Mark)** - A special Unicode character at the start of a file |
| 1000 | indicating encoding. |
| 1001 | go-yaml detects UTF-8, UTF-16LE, and UTF-16BE from BOM. |
| 1002 | |
| 1003 | ### C |
| 1004 | |
| 1005 | **Chomping** - Controls how trailing newlines are handled in block scalars. |
| 1006 | Strip (`-`) removes them, keep (`+`) preserves them, clip (default) keeps one |
| 1007 | newline. |
| 1008 | |
| 1009 | **Composer** - Load stack stage that builds Node trees from Event streams. |
| 1010 | Handles tag normalization, anchor registration, and comment transfer. |
| 1011 | |
| 1012 | **Constructor** - Load stack stage that converts Node trees to native Go values. |
| 1013 | Performs type coercion, handles custom Unmarshalers, and enforces constraints. |
| 1014 | |
| 1015 | ### D |
| 1016 | |
| 1017 | **Document** - A single YAML data structure within a stream. |
| 1018 | Can be explicit (starts with `---`) or implicit. |
| 1019 | Represented as DocumentNode in go-yaml. |
| 1020 | |
| 1021 | **Dump Stack** - The pipeline that transforms Go values into YAML text: |
| 1022 | Representer → Serializer → Emitter → Writer. |
| 1023 | |
| 1024 | ### E |
| 1025 | |
| 1026 | **Emitter** - Dump stack stage that converts Events to UTF-8 YAML text. |
| 1027 | Handles final style selection, line wrapping, and indentation. |
| 1028 | |
| 1029 | **Event** - Parser output representing syntactic structure. |
| 1030 | 11 types including `SCALAR_EVENT`, `MAPPING_START_EVENT`, `SEQUENCE_END_EVENT`. |
| 1031 | Contains tag, value, comments, and position. |
| 1032 | |
| 1033 | ### F |
| 1034 | |
| 1035 | **Flow Style** - YAML's compact JSON-like syntax using brackets `[]` and braces |
| 1036 | `{}`. |
| 1037 | Example: `{key: value}` or `[a, b, c]`. |
| 1038 | |
| 1039 | **Folded Block Scalar** - Multi-line string (`>`) where newlines are converted |
| 1040 | to spaces, except for blank lines and more-indented lines. |
| 1041 | |
| 1042 | **FootComment** - A comment appearing after a node but before any blank lines. |
| 1043 | Can be reassigned to keys in mappings. |
| 1044 | |
| 1045 | ### H |
| 1046 | |
| 1047 | **HeadComment** - Comments appearing before a node with no blank line |
| 1048 | separation. |
| 1049 | |
| 1050 | ### I |
| 1051 | |
| 1052 | **Implicit Tag** - A tag inferred by the resolver based on scalar content |
| 1053 | rather than explicitly specified. |
| 1054 | Example: `42` → `!!int`. |
| 1055 | |
| 1056 | **Indicated String** - A scalar that has quoted or literal style, indicating it |
| 1057 | should be treated as a string regardless of content. |
| 1058 | Skips tag resolution. |
| 1059 | |
| 1060 | **Indentless Sequence** - A YAML sequence where entries are indicated by `-` |
| 1061 | but not further indented relative to the parent. |
| 1062 | Used in some mapping values. |
| 1063 | |
| 1064 | **Inline Struct** - A struct field tagged with `,inline` that merges its fields |
| 1065 | into the parent struct during marshaling/unmarshaling. |
| 1066 | |
| 1067 | ### L |
| 1068 | |
| 1069 | **Literal Block Scalar** - Multi-line string (`|`) where newlines are preserved |
| 1070 | exactly as written. |
| 1071 | |
| 1072 | **Load Stack** - The pipeline that transforms YAML text into Go values: Reader |
| 1073 | → Scanner → Parser → Composer → Resolver → Constructor. |
| 1074 | |
| 1075 | ### M |
| 1076 | |
| 1077 | **Mapping** - YAML's key-value structure (like a map or dictionary). |
| 1078 | Represented as MappingNode in go-yaml. |
| 1079 | |
| 1080 | **Marshaling** - The process of converting Go values to YAML text (Dump stack). |
| 1081 | |
| 1082 | **Merge Key** - Special YAML key (`<<`) that merges content from another |
| 1083 | mapping or sequence of mappings. |
| 1084 | Explicit keys take precedence. |
| 1085 | |
| 1086 | ### N |
| 1087 | |
| 1088 | **Node** - Tree-based representation of YAML structure. |
| 1089 | 6 kinds: DocumentNode, SequenceNode, MappingNode, ScalarNode, AliasNode, |
| 1090 | StreamNode. |
| 1091 | |
| 1092 | ### P |
| 1093 | |
| 1094 | **Parser** - Load stack stage that converts Tokens to Events using LL(1) |
| 1095 | grammar. |
| 1096 | Implements 22 parser states and handles comment attachment. |
| 1097 | |
| 1098 | **Pull-Based** - Architecture where higher stages request data from lower |
| 1099 | stages. |
| 1100 | Used in Load stack (Constructor pulls from Composer, which pulls from Parser, |
| 1101 | etc.). |
| 1102 | |
| 1103 | **Push-Based** - Architecture where lower stages push data to higher stages. |
| 1104 | Used in Dump stack (Representer pushes Events to Emitter). |
| 1105 | |
| 1106 | ### R |
| 1107 | |
| 1108 | **Reader** - Load stack component that handles encoding detection, UTF-8 |
| 1109 | conversion, and input buffering. |
| 1110 | Not a separate stage but integrated into Parser struct. |
| 1111 | |
| 1112 | **Representer** - Dump stack stage that converts Go values to Events. |
| 1113 | Handles type dispatch, field filtering, key sorting, and style selection. |
| 1114 | |
| 1115 | **Representation Graph** - In YAML spec, the data structure after tag |
| 1116 | resolution. |
| 1117 | In go-yaml, conceptually the Node tree with resolved tags. |
| 1118 | |
| 1119 | **Resolver** - Function (not a separate stage) that infers tags from scalar |
| 1120 | content. |
| 1121 | Called from multiple places in both Load and Dump stacks. |
| 1122 | |
| 1123 | ### S |
| 1124 | |
| 1125 | **Scalar** - YAML's atomic value type (string, number, boolean, null). |
| 1126 | Represented as ScalarNode with a style (plain, quoted, literal, folded). |
| 1127 | |
| 1128 | **Scanner** - Load stack stage performing lexical analysis. |
| 1129 | Converts UTF-8 bytes to Tokens, handling indentation tracking, flow level |
| 1130 | tracking, and comment tokenization. |
| 1131 | |
| 1132 | **Self-Referential Alias** - An alias that references itself directly or |
| 1133 | indirectly, causing infinite loops. |
| 1134 | go-yaml detects and prevents this. |
| 1135 | |
| 1136 | **Sequence** - YAML's ordered list structure (like an array). |
| 1137 | Represented as SequenceNode in go-yaml. |
| 1138 | |
| 1139 | **Serializer** - Dump stack stage that converts Node trees to Events. |
| 1140 | Handles tag elision checks and flow style detection. |
| 1141 | |
| 1142 | **Simple Collection** - A sequence or mapping containing only scalar children |
| 1143 | that fits within line width. |
| 1144 | Eligible for automatic flow style. |
| 1145 | |
| 1146 | **Simple Key** - A mapping key that is short enough (≤128 characters) and |
| 1147 | single-line. |
| 1148 | Flow mappings require simple keys. |
| 1149 | |
| 1150 | **Stream** - Top-level container for YAML documents. |
| 1151 | A stream can contain multiple documents separated by `---`. |
| 1152 | Represented as StreamNode in go-yaml. |
| 1153 | |
| 1154 | **Surrogate Pair** - UTF-16 encoding mechanism for characters outside the Basic |
| 1155 | Multilingual Plane. |
| 1156 | go-yaml handles these during UTF-16 to UTF-8 conversion. |
| 1157 | |
| 1158 | ### T |
| 1159 | |
| 1160 | **Tag** - Type indicator for YAML nodes. |
| 1161 | Short form (`!!str`, `!!int`) or full URI (`tag:yaml.org,2002:str`). |
| 1162 | Can be explicit or implicit. |
| 1163 | |
| 1164 | **Tag Directive** - YAML directive (`%TAG`) that defines a short handle for tag |
| 1165 | URIs. |
| 1166 | Example: `%TAG ! tag:yaml.org,2002:`. |
| 1167 | |
| 1168 | **Tag Elision** - Omitting an explicit tag when it can be inferred. |
| 1169 | Serializer checks if tags can be elided during dump. |
| 1170 | |
| 1171 | **Tag Handle** - Short prefix for tags (like `!!` or `!custom!`). |
| 1172 | Stored separately from suffix in Token but merged in Event. |
| 1173 | |
| 1174 | **TAIL_COMMENT_EVENT** - Special event type for foot comments at block |
| 1175 | structure ends. |
| 1176 | Used during parsing to properly assign comments to mapping keys. |
| 1177 | |
| 1178 | **TextMarshaler/TextUnmarshaler** - Go interfaces for custom text |
| 1179 | encoding/decoding. |
| 1180 | Supported by Representer (marshaling) and Constructor (unmarshaling, scalars |
| 1181 | only). |
| 1182 | |
| 1183 | **Token** - Scanner output representing lexical units. |
| 1184 | 23 types including `SCALAR_TOKEN`, `BLOCK_MAPPING_START_TOKEN`, `TAG_TOKEN`. |
| 1185 | Contains byte-level position (Index). |
| 1186 | |
| 1187 | ### U |
| 1188 | |
| 1189 | **Unmarshaling** - The process of converting YAML text to Go values (Load |
| 1190 | stack). |
| 1191 | |
| 1192 | **UniqueKeys** - Option that enables duplicate key detection in mappings. |
| 1193 | Enabled by default in v2, v3, and v4. |
| 1194 | |
| 1195 | ### V |
| 1196 | |
| 1197 | **Version Directive** - YAML directive (`%YAML 1.2`) specifying the YAML |
| 1198 | version. |
| 1199 | Stored in StreamNode. |
| 1200 | |
| 1201 | ### W |
| 1202 | |
| 1203 | **Writer** - Dump stack component that flushes output buffer to destination. |
| 1204 | Very simple - just calls configured write handler. |