Debian Codegraph @

internal/libyaml/README.md

raw symbols SCIP
1 # internal/libyaml
2
3 This package provides low-level YAML processing functionality through a 3-stage
4 pipeline: Scanner → Parser → Emitter.
5 It implements the libyaml C library functionality in Go.
6
7 ## Directory Overview
8
9 The `internal/libyaml` package implements the core YAML processing stages:
10
11 1. **Scanner** - Tokenizes YAML text into tokens
12 2. **Parser** - Converts tokens into events following YAML grammar rules
13 3. **Emitter** - Serializes events back into YAML text
14
15 ## File Organization
16
17 ### Main Source Files
18
19 - **scanner.go** - YAML scanner/tokenizer implementation
20 - **parser.go** - YAML parser (tokens → events)
21 - **emitter.go** - YAML emitter (events → YAML output)
22 - **api.go** - Public API for Parser and Emitter types
23 - **yaml.go** - Core types and constants (Event, Token, enums)
24 - **reader.go** - Input handling and encoding detection
25 - **writer.go** - Output handling
26 - **util.go** - Internal types and helper functions
27
28 ### Test Files
29
30 - **scanner_test.go** - Scanner tests
31 - **parser_test.go** - Parser tests
32 - **emitter_test.go** - Emitter tests
33 - **api_test.go** - API tests
34 - **yaml_test.go** - Utility function tests
35 - **reader_test.go** - Reader tests
36 - **writer_test.go** - Writer tests
37 - **util_test.go** - Character classification tests
38 - **loader_test.go** - Data loader scalar resolution tests
39 - **yamldatatest_test.go** - YAML test data loading framework
40 - **yamldatatest_loader.go** - YAML test data loader with scalar type
41 resolution (exported for reuse)
42
43 ### Test Data Files (in `testdata/`)
44
45 - **scanner.yaml** - Scanner test cases
46 - **parser.yaml** - Parser test cases
47 - **emitter.yaml** - Emitter test cases
48 - **api.yaml** - API test cases
49 - **yaml.yaml** - Utility function test cases
50 - **reader.yaml** - Reader test cases
51 - **writer.yaml** - Writer test cases
52 - **util.yaml** - Character classification test cases
53 - **loader.yaml** - Data loader scalar resolution test cases
54
55 ## Processing Pipeline
56
57 ### 1. Scanner (scanner.go)
58
59 The scanner converts YAML text into tokens.
60
61 **Input**: Raw YAML text (string or []byte)
62 **Output**: Stream of tokens
63
64 **Token types include**:
65 - `SCALAR_TOKEN` - Plain, quoted, or block scalar values
66 - `KEY_TOKEN`, `VALUE_TOKEN` - Mapping key/value indicators
67 - `BLOCK_MAPPING_START_TOKEN`, `FLOW_MAPPING_START_TOKEN` - Mapping delimiters
68 - `BLOCK_SEQUENCE_START_TOKEN`, `FLOW_SEQUENCE_START_TOKEN` - Sequence delimiters
69 - `ANCHOR_TOKEN`, `ALIAS_TOKEN` - Anchor definitions and references
70 - `TAG_TOKEN` - Type tags
71 - `DOCUMENT_START_TOKEN`, `DOCUMENT_END_TOKEN` - Document boundaries
72
73 **Responsibilities**:
74 - Character encoding detection (UTF-8, UTF-16LE, UTF-16BE)
75 - Line break normalization
76 - Indentation tracking
77 - Quote and escape sequence handling
78
79 ### 2. Parser (parser.go)
80
81 The parser converts tokens into events following YAML grammar rules.
82
83 **Input**: Stream of tokens from Scanner
84 **Output**: Stream of events
85
86 **Event types include**:
87 - `STREAM_START_EVENT`, `STREAM_END_EVENT` - Stream boundaries
88 - `DOCUMENT_START_EVENT`, `DOCUMENT_END_EVENT` - Document boundaries
89 - `SCALAR_EVENT` - Scalar values
90 - `MAPPING_START_EVENT`, `MAPPING_END_EVENT` - Mapping boundaries
91 - `SEQUENCE_START_EVENT`, `SEQUENCE_END_EVENT` - Sequence boundaries
92 - `ALIAS_EVENT` - Anchor references
93
94 **Responsibilities**:
95 - Implementing YAML grammar and validation
96 - Managing document directives (%YAML, %TAG)
97 - Resolving anchors and aliases
98 - Tracking implicit vs explicit markers
99 - Style preservation (plain, single-quoted, double-quoted, literal, folded)
100
101 ### 3. Emitter (emitter.go)
102
103 The emitter converts events back into YAML text.
104
105 **Input**: Stream of events
106 **Output**: YAML text
107
108 **Responsibilities**:
109 - Style selection (plain/quoted scalars, block/flow collections)
110 - Formatting control (canonical mode, indentation, line width)
111 - Character encoding
112 - Anchor and tag serialization
113 - Document marker generation (---, ...)
114
115 **Configuration options**:
116 - `Canonical` - Emit in canonical YAML form
117 - `Indent` - Indentation width (2-9 spaces)
118 - `Width` - Line width (-1 for unlimited)
119 - `Unicode` - Enable Unicode character output
120 - `LineBreak` - Line break style (LN, CR, CRLN)
121
122 ## Testing Framework
123
124 ### Test Architecture
125
126 The testing framework uses a data-driven approach:
127
128 1. **Test data** is stored in YAML files in the `testdata/` directory
129 2. **Test logic** is implemented in Go files (`*_test.go`)
130 3. **One-to-one pairing**: Each `testdata/foo.yaml` has a corresponding
131 `foo_test.go`
132
133 **Benefits**:
134 - Easy to add new test cases without writing Go code
135 - Test data is human-readable and self-documenting
136 - Test logic is reusable across many test cases
137 - Test data is separated from test code for clarity
138 - Tests can become a common suite for multiple YAML frameworks
139
140 ### Test Data Files
141
142 Each YAML file contains test cases for a specific component:
143
144 - **scanner.yaml** - Scanner/tokenization tests
145 - Token sequence verification
146 - Token property validation (value, style)
147 - Error detection
148
149 - **parser.yaml** - Parser/event generation tests
150 - Event sequence verification
151 - Event property validation (anchor, tag, value, directives)
152 - Error detection
153
154 - **emitter.yaml** - Emitter/serialization tests
155 - Event-to-YAML conversion
156 - Configuration options testing
157 - Roundtrip testing (parse → emit)
158 - Writer integration
159
160 - **api.yaml** - API constructor and method tests
161 - Constructor validation
162 - Method behavior and state changes
163 - Panic conditions
164 - Cleanup verification
165
166 - **yaml.yaml** - Utility function tests
167 - Enum String() methods
168 - Style accessor methods
169
170 - **reader.yaml** - Reader/input handling tests
171 - Encoding detection (UTF-8, UTF-16LE, UTF-16BE)
172 - Buffer management
173 - Error handling
174
175 - **writer.yaml** - Writer/output handling tests
176 - Buffer flushing
177 - Output handlers (string, io.Writer)
178 - Error conditions
179
180 - **util.yaml** - Character classification tests
181 - Character type predicates (isAlpha, isDigit, isHex, etc.)
182 - Character conversion functions (asDigit, asHex, width)
183 - Unicode handling
184
185 - **loader.yaml** - Data loader scalar resolution tests
186 - Numeric type resolution (integers, floats)
187 - Boolean and null value handling
188 - String vs numeric type disambiguation
189 - Mixed-type collections
190
191 ### Test Framework Implementation
192
193 The test framework is implemented in `testdata_test.go`:
194
195 **Core functions**:
196 - `LoadAny(data []byte) (interface{}, error)` - Parses YAML using production
197 loader with scalar type resolution (exported from loader.go)
198 - `UnmarshalStruct(target interface{}, data map[string]interface{}) error` -
199 Populates structs (exported)
200 - `LoadTestCases(filename string) ([]TestCase, error)` - Loads and parses
201 test YAML files
202
203 **Core types**:
204 - `TestCase` struct - Umbrella structure containing fields for all test types
205 - Uses `interface{}` for flexible field types
206 - Post-processing converts generic fields to specific types
207
208 **Post-processing**:
209 After loading, the framework processes test data:
210 - Converts `Want` (interface{}) to `WantEvents`, `WantTokens`, or `WantSpecs`
211 based on test type
212 - Converts `Want` (interface{}) to `WantContains` (handles both scalar and
213 sequence)
214 - Converts `Checks` to field validation specifications
215
216 ### Test Types
217
218 #### Scanner Tests
219
220 **scan-tokens** - Verify token sequence
221
222 ```yaml
223 - scan-tokens:
224 name: Simple scalar
225 yaml: |-
226 hello
227 want:
228 - STREAM_START_TOKEN
229 - SCALAR_TOKEN
230 - STREAM_END_TOKEN
231 ```
232
233 **scan-tokens-detailed** - Verify token properties
234
235 ```yaml
236 - scan-tokens-detailed:
237 name: Single quoted scalar
238 yaml: |-
239 'hello world'
240 want:
241 - STREAM_START_TOKEN
242 - SCALAR_TOKEN:
243 style: SINGLE_QUOTED_SCALAR_STYLE
244 value: hello world
245 - STREAM_END_TOKEN
246 ```
247
248 **scan-error** - Verify error detection
249
250 ```yaml
251 - scan-error:
252 name: Invalid character
253 yaml: "\x01"
254 ```
255
256 #### Parser Tests
257
258 **parse-events** - Verify event sequence
259
260 ```yaml
261 - parse-events:
262 name: Simple mapping
263 yaml: |
264 key: value
265 want:
266 - STREAM_START_EVENT
267 - DOCUMENT_START_EVENT
268 - MAPPING_START_EVENT
269 - SCALAR_EVENT
270 - SCALAR_EVENT
271 - MAPPING_END_EVENT
272 - DOCUMENT_END_EVENT
273 - STREAM_END_EVENT
274 ```
275
276 **parse-events-detailed** - Verify event properties
277
278 ```yaml
279 - parse-events-detailed:
280 name: Anchor and alias
281 yaml: |
282 - &anchor value
283 - *anchor
284 want:
285 - STREAM_START_EVENT
286 - DOCUMENT_START_EVENT
287 - SEQUENCE_START_EVENT
288 - SCALAR_EVENT:
289 anchor: anchor
290 value: value
291 - ALIAS_EVENT:
292 anchor: anchor
293 - SEQUENCE_END_EVENT
294 - DOCUMENT_END_EVENT
295 - STREAM_END_EVENT
296 ```
297
298 **parse-error** - Verify error detection
299
300 ```yaml
301 - parse-error:
302 name: Error state
303 yaml: |
304 key: : invalid
305 ```
306
307 #### Emitter Tests
308
309 **emit** - Emit events and verify output contains expected strings
310
311 ```yaml
312 - emit:
313 name: Simple scalar
314 data:
315 - STREAM_START_EVENT:
316 encoding: UTF8_ENCODING
317 - DOCUMENT_START_EVENT:
318 implicit: true
319 - SCALAR_EVENT:
320 value: hello
321 implicit: true
322 style: PLAIN_SCALAR_STYLE
323 - DOCUMENT_END_EVENT:
324 implicit: true
325 - STREAM_END_EVENT
326 want: hello
327 ```
328
329 **emit-config** - Emit with configuration
330
331 ```yaml
332 - emit-config:
333 name: Custom indent
334 conf:
335 indent: 4
336 data:
337 - STREAM_START_EVENT:
338 encoding: UTF8_ENCODING
339 - DOCUMENT_START_EVENT:
340 implicit: true
341 - MAPPING_START_EVENT:
342 implicit: true
343 style: BLOCK_MAPPING_STYLE
344 # ... more events
345 want: key
346 ```
347
348 **roundtrip** - Parse → emit, verify output
349
350 ```yaml
351 - roundtrip:
352 name: Roundtrip
353 yaml: |
354 key: value
355 list:
356 - item1
357 - item2
358 want:
359 - key
360 - value
361 - item1
362 ```
363
364 **emit-writer** - Emit to io.Writer
365
366 ```yaml
367 - emit-writer:
368 name: Writer
369 data:
370 - STREAM_START_EVENT:
371 encoding: UTF8_ENCODING
372 # ... more events
373 want: test
374 ```
375
376 #### API Tests
377
378 **api-new** - Test constructors
379
380 ```yaml
381 - api-new:
382 name: New parser
383 with: NewParser
384 test:
385 - nil: [raw-buffer, false]
386 - cap: [raw-buffer, 512]
387 - nil: [buffer, false]
388 - cap: [buffer, 1536]
389 ```
390
391 **api-method** - Test methods and field state
392
393 ```yaml
394 - api-method:
395 name: Parser set input string
396 with: NewParser
397 byte: true
398 call: [SetInputString, 'key: value']
399 test:
400 - eq: [input, 'key: value']
401 - eq: [input-pos, 0]
402 - nil: [read-handler, false]
403 ```
404
405 **api-panic** - Test methods that should panic
406
407 ```yaml
408 - api-panic:
409 name: Parser set input string twice
410 with: NewParser
411 byte: true
412 init: [SetInputString, first]
413 call: [SetInputString, second]
414 want: must set the input source only once
415 ```
416
417 **api-delete** - Test cleanup
418
419 ```yaml
420 - api-delete:
421 name: Parser delete
422 with: NewParser
423 byte: true
424 init: [SetInputString, test]
425 test:
426 - len: [input, 0]
427 - len: [buffer, 0]
428 ```
429
430 **api-new-event** - Test event constructors
431
432 ```yaml
433 - api-new-event:
434 name: New stream start event
435 call: [NewStreamStartEvent, UTF8_ENCODING]
436 test:
437 - eq: [Type, STREAM_START_EVENT]
438 - eq: [encoding, UTF8_ENCODING]
439 ```
440
441 #### Utility Tests
442
443 **enum-string** - Test String() methods of enums
444
445 ```yaml
446 - enum-string:
447 name: Scalar style plain
448 enum: [ScalarStyle, PLAIN_SCALAR_STYLE]
449 want: Plain
450 ```
451
452 **style-accessor** - Test style accessor methods
453
454 ```yaml
455 - style-accessor:
456 name: Event scalar style
457 test: [ScalarStyle, DOUBLE_QUOTED_SCALAR_STYLE]
458 ```
459
460 #### Loader Tests
461
462 **scalar-resolution** - Test scalar type resolution
463
464 ```yaml
465 - scalar-resolution:
466 name: Positive integer
467 yaml: "42"
468 want: 42
469
470 - scalar-resolution:
471 name: Negative float
472 yaml: "-2.5"
473 want: -2.5
474 ```
475
476 **Resolution order**:
477 1. Boolean (true, false)
478 2. Null (null keyword only)
479 3. Hexadecimal integer (0x prefix)
480 4. Float (contains .)
481 5. Decimal integer
482 6. String (fallback)
483
484 ### Common Keys in Test YAML Files
485
486 Test cases use a **type-as-key** format where the test type is the map key:
487
488 ```yaml
489 - test-type:
490 name: Test case name
491 # ... other fields
492 ```
493
494 **Common fields**:
495 - **name** - Test case name (title case convention)
496 - **yaml** - Input YAML string to test
497 - **want** - Expected result (format varies by test type)
498 - For api-panic: string containing expected panic message substring
499 - For scan-error/parse-error: boolean (defaults to true if omitted; set to
500 false if no error expected)
501 - For enum-string: string representing expected String() output
502 - For other types: varies (may be sequence or scalar)
503 - **data** - For emitter tests: list of event specifications to emit
504 - **conf** - For emitter config tests: emitter configuration options
505 - **with** - For API tests: constructor name (NewParser, NewEmitter)
506 - **call** - For API tests: method call [MethodName, arg1, arg2, ...]
507 - **init** - For API panic tests: setup method call before main method
508 - **byte** - For API tests: boolean flag to convert string args to []byte
509 - **test** - For API tests: list of field validation checks in format
510 `operator: [field, value]` where operator is one of: nil, cap, len, eq, gte,
511 len-gt.
512 - **test** - For style-accessor tests: array of [Method, STYLE] where Method
513 is the accessor method (e.g., ScalarStyle) and STYLE is the style constant
514 (e.g., DOUBLE_QUOTED_SCALAR_STYLE).
515 - **enum** - For enum tests: array of [Type, Value] where Type is the enum
516 type (e.g., ScalarStyle) and Value is the constant (e.g.,
517 PLAIN_SCALAR_STYLE)
518
519 **Note on scalar type resolution**: Unquoted scalar values in test data are
520 automatically resolved to appropriate Go types (int, float64, bool, nil) by the
521 `LoadAny` function.
522 Quoted scalars remain as strings.
523
524 ### Running Tests
525
526 ```bash
527 # Run all tests in the package
528 go test ./internal/libyaml
529
530 # Run specific test file
531 go test ./internal/libyaml -run TestScanner
532 go test ./internal/libyaml -run TestParser
533 go test ./internal/libyaml -run TestEmitter
534 go test ./internal/libyaml -run TestAPI
535 go test ./internal/libyaml -run TestYAML
536 go test ./internal/libyaml -run TestLoader
537
538 # Run specific test case (using subtest name)
539 go test ./internal/libyaml -run TestScanner/Block_sequence
540 go test ./internal/libyaml -run TestParser/Anchor_and_alias
541 go test ./internal/libyaml -run TestEmitter/Flow_mapping
542 go test ./internal/libyaml -run TestLoader/Scientific_notation_lowercase_e
543
544 # Run with verbose output
545 go test -v ./internal/libyaml
546
547 # Run with coverage
548 go test -cover ./internal/libyaml
549 ```