Debian Codegraph @

cmd/go-yaml/token.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package main provides YAML token formatting utilities for the go-yaml tool.
5
6 package main
7
8 import (
9 "bytes"
10 "fmt"
11 "io"
12 "os"
13 "strings"
14
15 "go.yaml.in/yaml/v4"
16 )
17
18 // Token represents a YAML token with comment information
19 type Token struct {
20 Type string
21 Value string
22 Style string
23 CommentType string // For COMMENT tokens: "head", "line", or "foot"
24 StartLine int
25 StartColumn int
26 EndLine int
27 EndColumn int
28 HeadComment string
29 LineComment string
30 FootComment string
31 }
32
33 // TokenInfo represents the information about a YAML token for YAML encoding
34 type TokenInfo struct {
35 Token string `yaml:"token"`
36 Value string `yaml:"value,omitempty"`
37 Style string `yaml:"style,omitempty"`
38 Head string `yaml:"head,omitempty"`
39 Line string `yaml:"line,omitempty"`
40 Foot string `yaml:"foot,omitempty"`
41 Pos string `yaml:"pos,omitempty"`
42 }
43
44 // ProcessTokens reads YAML from reader and outputs token information using the internal scanner
45 func ProcessTokens(reader io.Reader, profuse, compact, unmarshal bool) error {
46 if unmarshal {
47 return processTokensUnmarshal(reader, profuse, compact)
48 }
49 return processTokensWithParser(reader, profuse, compact)
50 }
51
52 // processTokensDecode uses Loader.Load for YAML processing
53 func processTokensDecode(profuse, compact bool) error {
54 loader, err := yaml.NewLoader(os.Stdin)
55 if err != nil {
56 return fmt.Errorf("failed to create loader: %w", err)
57 }
58 firstDoc := true
59
60 for {
61 var node yaml.Node
62 err := loader.Load(&node)
63 if err != nil {
64 if err == io.EOF {
65 break
66 }
67 return fmt.Errorf("failed to decode YAML: %w", err)
68 }
69
70 // Add document separator for all documents except the first
71 if !firstDoc {
72 fmt.Println("---")
73 }
74 firstDoc = false
75
76 tokens := processNodeToTokens(&node, profuse)
77
78 if compact {
79 // For compact mode, output each token as a flow style mapping in a sequence
80 for _, token := range tokens {
81 info := formatTokenInfo(token, profuse)
82
83 // Create a YAML node with flow style for the mapping
84 compactNode := &yaml.Node{
85 Kind: yaml.MappingNode,
86 Style: yaml.FlowStyle,
87 }
88
89 // Add the Token field
90 compactNode.Content = append(compactNode.Content,
91 &yaml.Node{Kind: yaml.ScalarNode, Value: "token"},
92 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Token})
93
94 // Add other fields if they exist
95 if info.Value != "" {
96 compactNode.Content = append(compactNode.Content,
97 &yaml.Node{Kind: yaml.ScalarNode, Value: "value"},
98 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Value})
99 }
100 if info.Style != "" {
101 compactNode.Content = append(compactNode.Content,
102 &yaml.Node{Kind: yaml.ScalarNode, Value: "style"},
103 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Style})
104 }
105 if info.Head != "" {
106 compactNode.Content = append(compactNode.Content,
107 &yaml.Node{Kind: yaml.ScalarNode, Value: "head"},
108 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Head})
109 }
110 if info.Line != "" {
111 compactNode.Content = append(compactNode.Content,
112 &yaml.Node{Kind: yaml.ScalarNode, Value: "line"},
113 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Line})
114 }
115 if info.Foot != "" {
116 compactNode.Content = append(compactNode.Content,
117 &yaml.Node{Kind: yaml.ScalarNode, Value: "foot"},
118 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Foot})
119 }
120 if info.Pos != "" {
121 compactNode.Content = append(compactNode.Content,
122 &yaml.Node{Kind: yaml.ScalarNode, Value: "pos"},
123 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Pos})
124 }
125
126 var buf bytes.Buffer
127 dumper, err := yaml.NewDumper(&buf)
128 if err != nil {
129 return fmt.Errorf("failed to create dumper: %w", err)
130 }
131 if err := dumper.Dump([]*yaml.Node{compactNode}); err != nil {
132 dumper.Close()
133 return fmt.Errorf("failed to dump compact token info: %w", err)
134 }
135 if err := dumper.Close(); err != nil {
136 return fmt.Errorf("failed to close dumper: %w", err)
137 }
138 fmt.Print(buf.String())
139 }
140 } else {
141 // For non-compact mode, output each token as a separate mapping
142 for _, token := range tokens {
143 info := formatTokenInfo(token, profuse)
144
145 var buf bytes.Buffer
146 dumper, err := yaml.NewDumper(&buf)
147 if err != nil {
148 return fmt.Errorf("failed to create dumper: %w", err)
149 }
150 if err := dumper.Dump([]*TokenInfo{info}); err != nil {
151 dumper.Close()
152 return fmt.Errorf("failed to dump token info: %w", err)
153 }
154 if err := dumper.Close(); err != nil {
155 return fmt.Errorf("failed to close dumper: %w", err)
156 }
157 fmt.Print(buf.String())
158 }
159 }
160 }
161
162 return nil
163 }
164
165 // processTokensWithParser uses the internal parser for token processing
166 func processTokensWithParser(reader io.Reader, profuse, compact bool) error {
167 p, err := NewParser(reader)
168 if err != nil {
169 return fmt.Errorf("failed to create parser: %w", err)
170 }
171 defer p.Close()
172
173 for {
174 token, err := p.Next()
175 if err != nil {
176 return fmt.Errorf("failed to get next token: %w", err)
177 }
178 if token == nil {
179 break
180 }
181
182 info := formatTokenInfo(token, profuse)
183
184 if compact {
185 // For compact mode, output each token as a flow style mapping in a sequence
186 compactNode := &yaml.Node{
187 Kind: yaml.MappingNode,
188 Style: yaml.FlowStyle,
189 }
190
191 // Add the Token field
192 compactNode.Content = append(compactNode.Content,
193 &yaml.Node{Kind: yaml.ScalarNode, Value: "token"},
194 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Token})
195
196 // Add other fields if they exist
197 if info.Value != "" {
198 compactNode.Content = append(compactNode.Content,
199 &yaml.Node{Kind: yaml.ScalarNode, Value: "value"},
200 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Value})
201 }
202 if info.Style != "" {
203 compactNode.Content = append(compactNode.Content,
204 &yaml.Node{Kind: yaml.ScalarNode, Value: "style"},
205 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Style})
206 }
207 if info.Head != "" {
208 compactNode.Content = append(compactNode.Content,
209 &yaml.Node{Kind: yaml.ScalarNode, Value: "head"},
210 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Head})
211 }
212 if info.Line != "" {
213 compactNode.Content = append(compactNode.Content,
214 &yaml.Node{Kind: yaml.ScalarNode, Value: "line"},
215 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Line})
216 }
217 if info.Foot != "" {
218 compactNode.Content = append(compactNode.Content,
219 &yaml.Node{Kind: yaml.ScalarNode, Value: "foot"},
220 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Foot})
221 }
222 if info.Pos != "" {
223 compactNode.Content = append(compactNode.Content,
224 &yaml.Node{Kind: yaml.ScalarNode, Value: "pos"},
225 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Pos})
226 }
227
228 var buf bytes.Buffer
229 dumper, err := yaml.NewDumper(&buf)
230 if err != nil {
231 return fmt.Errorf("failed to create dumper: %w", err)
232 }
233 if err := dumper.Dump([]*yaml.Node{compactNode}); err != nil {
234 dumper.Close()
235 return fmt.Errorf("failed to dump compact token info: %w", err)
236 }
237 if err := dumper.Close(); err != nil {
238 return fmt.Errorf("failed to close dumper: %w", err)
239 }
240 fmt.Print(buf.String())
241 } else {
242 // For non-compact mode, output each token as a separate mapping
243 var buf bytes.Buffer
244 dumper, err := yaml.NewDumper(&buf)
245 if err != nil {
246 return fmt.Errorf("failed to create dumper: %w", err)
247 }
248 if err := dumper.Dump([]*TokenInfo{info}); err != nil {
249 dumper.Close()
250 return fmt.Errorf("failed to dump token info: %w", err)
251 }
252 if err := dumper.Close(); err != nil {
253 return fmt.Errorf("failed to close dumper: %w", err)
254 }
255 fmt.Print(buf.String())
256 }
257 }
258
259 return nil
260 }
261
262 // processTokensUnmarshal uses [yaml.Unmarshal] for YAML processing
263 func processTokensUnmarshal(reader io.Reader, profuse, compact bool) error {
264 // Read all input from reader
265 input, err := io.ReadAll(reader)
266 if err != nil {
267 return fmt.Errorf("failed to read input: %w", err)
268 }
269
270 // Split input into documents
271 documents := bytes.Split(input, []byte("---"))
272 firstDoc := true
273
274 for _, doc := range documents {
275 // Skip empty documents
276 if len(bytes.TrimSpace(doc)) == 0 {
277 continue
278 }
279
280 // Add document separator for all documents except the first
281 if !firstDoc {
282 fmt.Println("---")
283 }
284 firstDoc = false
285
286 // For unmarshal mode, use `any` first to avoid preserving comments
287 var data any
288 if err := yaml.Load(doc, &data); err != nil {
289 return fmt.Errorf("failed to load YAML: %w", err)
290 }
291
292 // Convert to yaml.Node for token processing
293 var node yaml.Node
294 if err := yaml.Load(doc, &node); err != nil {
295 return fmt.Errorf("failed to load YAML to node: %w", err)
296 }
297
298 tokens := processNodeToTokens(&node, profuse)
299
300 if compact {
301 // For compact mode, output each token as a flow style mapping in a sequence
302 for _, token := range tokens {
303 info := formatTokenInfo(token, profuse)
304
305 // Create a YAML node with flow style for the mapping
306 compactNode := &yaml.Node{
307 Kind: yaml.MappingNode,
308 Style: yaml.FlowStyle,
309 }
310
311 // Add the Token field
312 compactNode.Content = append(compactNode.Content,
313 &yaml.Node{Kind: yaml.ScalarNode, Value: "token"},
314 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Token})
315
316 // Add other fields if they exist
317 if info.Value != "" {
318 compactNode.Content = append(compactNode.Content,
319 &yaml.Node{Kind: yaml.ScalarNode, Value: "value"},
320 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Value})
321 }
322 if info.Style != "" {
323 compactNode.Content = append(compactNode.Content,
324 &yaml.Node{Kind: yaml.ScalarNode, Value: "style"},
325 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Style})
326 }
327 if info.Head != "" {
328 compactNode.Content = append(compactNode.Content,
329 &yaml.Node{Kind: yaml.ScalarNode, Value: "head"},
330 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Head})
331 }
332 if info.Line != "" {
333 compactNode.Content = append(compactNode.Content,
334 &yaml.Node{Kind: yaml.ScalarNode, Value: "line"},
335 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Line})
336 }
337 if info.Foot != "" {
338 compactNode.Content = append(compactNode.Content,
339 &yaml.Node{Kind: yaml.ScalarNode, Value: "foot"},
340 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Foot})
341 }
342 if info.Pos != "" {
343 compactNode.Content = append(compactNode.Content,
344 &yaml.Node{Kind: yaml.ScalarNode, Value: "pos"},
345 &yaml.Node{Kind: yaml.ScalarNode, Value: info.Pos})
346 }
347
348 var buf bytes.Buffer
349 dumper, err := yaml.NewDumper(&buf)
350 if err != nil {
351 return fmt.Errorf("failed to create dumper: %w", err)
352 }
353 if err := dumper.Dump([]*yaml.Node{compactNode}); err != nil {
354 dumper.Close()
355 return fmt.Errorf("failed to dump compact token info: %w", err)
356 }
357 if err := dumper.Close(); err != nil {
358 return fmt.Errorf("failed to close dumper: %w", err)
359 }
360 fmt.Print(buf.String())
361 }
362 } else {
363 // For non-compact mode, output each token as a separate mapping
364 for _, token := range tokens {
365 info := formatTokenInfo(token, profuse)
366
367 var buf bytes.Buffer
368 dumper, err := yaml.NewDumper(&buf)
369 if err != nil {
370 return fmt.Errorf("failed to create dumper: %w", err)
371 }
372 if err := dumper.Dump([]*TokenInfo{info}); err != nil {
373 dumper.Close()
374 return fmt.Errorf("failed to dump token info: %w", err)
375 }
376 if err := dumper.Close(); err != nil {
377 return fmt.Errorf("failed to close dumper: %w", err)
378 }
379 fmt.Print(buf.String())
380 }
381 }
382 }
383
384 return nil
385 }
386
387 // formatTokenInfo converts a [Token] to a [TokenInfo] struct for YAML encoding
388 func formatTokenInfo(token *Token, profuse bool) *TokenInfo {
389 info := &TokenInfo{
390 Token: token.Type,
391 }
392
393 // For COMMENT tokens, use the CommentType to determine which field to populate
394 if token.Type == "COMMENT" && token.CommentType != "" && token.Value != "" {
395 switch token.CommentType {
396 case "head":
397 info.Head = token.Value
398 case "line":
399 info.Line = token.Value
400 case "foot":
401 info.Foot = token.Value
402 }
403 } else {
404 // For non-COMMENT tokens
405 if token.Value != "" {
406 info.Value = token.Value
407 }
408
409 if token.Style != "" && token.Style != "Plain" {
410 info.Style = token.Style
411 }
412
413 if token.HeadComment != "" {
414 info.Head = token.HeadComment
415 }
416 if token.LineComment != "" {
417 info.Line = token.LineComment
418 }
419 if token.FootComment != "" {
420 info.Foot = token.FootComment
421 }
422 }
423
424 if profuse {
425 if token.StartLine == token.EndLine && token.StartColumn == token.EndColumn {
426 // Single position
427 info.Pos = fmt.Sprintf("%d:%d", token.StartLine, token.StartColumn)
428 } else if token.StartLine == token.EndLine {
429 // Range on same line
430 info.Pos = fmt.Sprintf("%d:%d-%d", token.StartLine, token.StartColumn, token.EndColumn)
431 } else {
432 // Range across different lines
433 info.Pos = fmt.Sprintf("%d:%d-%d:%d", token.StartLine, token.StartColumn, token.EndLine, token.EndColumn)
434 }
435 }
436
437 return info
438 }
439
440 // processNodeToTokens converts a node to a slice of tokens
441 func processNodeToTokens(node *yaml.Node, profuse bool) []*Token {
442 var tokens []*Token
443
444 // Add stream start token
445 tokens = append(tokens, &Token{
446 Type: "STREAM-START",
447 })
448
449 // Add document start token
450 tokens = append(tokens, &Token{
451 Type: "DOCUMENT-START",
452 })
453
454 // Process the node content
455 tokens = append(tokens, processNodeToTokensRecursive(node, profuse)...)
456
457 // Add document end token
458 tokens = append(tokens, &Token{
459 Type: "DOCUMENT-END",
460 })
461
462 // Add stream end token
463 tokens = append(tokens, &Token{
464 Type: "STREAM-END",
465 })
466
467 return tokens
468 }
469
470 // processNodeToTokensRecursive recursively converts a node to tokens
471 func processNodeToTokensRecursive(node *yaml.Node, profuse bool) []*Token {
472 var tokens []*Token
473
474 switch node.Kind {
475 case yaml.DocumentNode:
476 for _, child := range node.Content {
477 tokens = append(tokens, processNodeToTokensRecursive(child, profuse)...)
478 }
479 case yaml.MappingNode:
480 tokens = append(tokens, &Token{
481 Type: "BLOCK-MAPPING-START",
482 StartLine: node.Line,
483 StartColumn: node.Column,
484 EndLine: node.Line,
485 EndColumn: node.Column,
486 HeadComment: node.HeadComment,
487 LineComment: node.LineComment,
488 FootComment: node.FootComment,
489 })
490 for i := 0; i < len(node.Content); i += 2 {
491 if i+1 < len(node.Content) {
492 // Key
493 tokens = append(tokens, &Token{
494 Type: "KEY",
495 StartLine: node.Content[i].Line,
496 StartColumn: node.Content[i].Column,
497 EndLine: node.Content[i].Line,
498 EndColumn: node.Content[i].Column,
499 })
500 keyTokens := processNodeToTokensRecursive(node.Content[i], profuse)
501 tokens = append(tokens, keyTokens...)
502 // Value
503 tokens = append(tokens, &Token{
504 Type: "VALUE",
505 StartLine: node.Content[i+1].Line,
506 StartColumn: node.Content[i+1].Column,
507 EndLine: node.Content[i+1].Line,
508 EndColumn: node.Content[i+1].Column,
509 })
510 valueTokens := processNodeToTokensRecursive(node.Content[i+1], profuse)
511 tokens = append(tokens, valueTokens...)
512 }
513 }
514 tokens = append(tokens, &Token{
515 Type: "BLOCK-END",
516 StartLine: node.Line,
517 StartColumn: node.Column,
518 EndLine: node.Line,
519 EndColumn: node.Column,
520 })
521 case yaml.SequenceNode:
522 tokens = append(tokens, &Token{
523 Type: "BLOCK-SEQUENCE-START",
524 StartLine: node.Line,
525 StartColumn: node.Column,
526 EndLine: node.Line,
527 EndColumn: node.Column,
528 HeadComment: node.HeadComment,
529 LineComment: node.LineComment,
530 FootComment: node.FootComment,
531 })
532 for _, child := range node.Content {
533 tokens = append(tokens, &Token{
534 Type: "BLOCK-ENTRY",
535 StartLine: child.Line,
536 StartColumn: child.Column,
537 EndLine: child.Line,
538 EndColumn: child.Column,
539 })
540 childTokens := processNodeToTokensRecursive(child, profuse)
541 tokens = append(tokens, childTokens...)
542 }
543 tokens = append(tokens, &Token{
544 Type: "BLOCK-END",
545 StartLine: node.Line,
546 StartColumn: node.Column,
547 EndLine: node.Line,
548 EndColumn: node.Column,
549 })
550 case yaml.ScalarNode:
551 // Check for anchor before the scalar
552 if node.Anchor != "" {
553 tokens = append(tokens, &Token{
554 Type: "ANCHOR",
555 Value: node.Anchor,
556 StartLine: node.Line,
557 StartColumn: node.Column,
558 EndLine: node.Line,
559 EndColumn: node.Column,
560 })
561 }
562
563 // Check for tag before the scalar
564 // Check if the tag was explicit in the input
565 tagWasExplicit := node.Style&yaml.TaggedStyle != 0
566
567 // Show tag if it exists and either:
568 // - it's not !!str, or
569 // - it's !!str and was explicit in the input
570 if node.Tag != "" && (node.Tag != "!!str" || tagWasExplicit) {
571 tokens = append(tokens, &Token{
572 Type: "TAG",
573 Value: node.Tag,
574 StartLine: node.Line,
575 StartColumn: node.Column,
576 EndLine: node.Line,
577 EndColumn: node.Column,
578 })
579 }
580
581 // Calculate end position for scalars based on value length
582 endLine := node.Line
583 endColumn := node.Column
584 if node.Value != "" {
585 // For single-line values, add the length to the column
586 if !strings.Contains(node.Value, "\n") {
587 endColumn += len(node.Value)
588 } else {
589 // For multi-line values, we'd need more complex logic
590 // For now, just use the start position
591 endColumn = node.Column
592 }
593 }
594 tokens = append(tokens, &Token{
595 Type: "SCALAR",
596 Value: node.Value,
597 StartLine: node.Line,
598 StartColumn: node.Column,
599 EndLine: endLine,
600 EndColumn: endColumn,
601 Style: formatStyle(node.Style, false),
602 HeadComment: node.HeadComment,
603 LineComment: node.LineComment,
604 FootComment: node.FootComment,
605 })
606 case yaml.AliasNode:
607 // Generate ALIAS token for alias nodes
608 tokens = append(tokens, &Token{
609 Type: "ALIAS",
610 Value: node.Value,
611 StartLine: node.Line,
612 StartColumn: node.Column,
613 EndLine: node.Line,
614 EndColumn: node.Column,
615 HeadComment: node.HeadComment,
616 LineComment: node.LineComment,
617 FootComment: node.FootComment,
618 })
619 }
620
621 return tokens
622 }