Debian Codegraph @

internal/libyaml/emitter.go

raw symbols SCIP
1 // Copyright 2006-2010 Kirill Simonov
2 // Copyright 2011-2019 Canonical Ltd
3 // Copyright 2025 The go-yaml Project Contributors
4 // SPDX-License-Identifier: Apache-2.0 AND MIT
5
6 // Emitter stage: Generates YAML output from events.
7 // Handles formatting, indentation, line wrapping, and output buffering.
8
9 package libyaml
10
11 import (
12 "bytes"
13 "fmt"
14 "io"
15 )
16
17 // WriteHandler is called when the [Emitter] needs to flush the accumulated
18 // characters to the output. The handler should write @a size bytes of the
19 // @a buffer to the output.
20 //
21 // @param[in,out] data A pointer to an application data specified by
22 // yamlEmitter.setOutput().
23 // @param[in] buffer The buffer with bytes to be written.
24 // @param[in] size The size of the buffer.
25 //
26 // @returns On success, the handler should return @c 1. If the handler failed,
27 // the returned value should be @c 0.
28 type WriteHandler func(emitter *Emitter, buffer []byte) error
29
30 // EmitterState represents the current state of the emitter.
31 type EmitterState int
32
33 // The emitter states.
34 const (
35 // Expect STREAM-START.
36 EMIT_STREAM_START_STATE EmitterState = iota
37
38 EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END.
39 EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END.
40 EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document.
41 EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END.
42 EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence.
43 EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE // Expect the next item of a flow sequence, with the comma already written out
44 EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence.
45 EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping.
46 EMIT_FLOW_MAPPING_TRAIL_KEY_STATE // Expect the next key of a flow mapping, with the comma already written out
47 EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping.
48 EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping.
49 EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping.
50 EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence.
51 EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence.
52 EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping.
53 EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping.
54 EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping.
55 EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping.
56 EMIT_END_STATE // Expect nothing.
57 )
58
59 // Emitter holds all information about the current state of the emitter.
60 type Emitter struct {
61 // Writer stuff
62
63 write_handler WriteHandler // Write handler.
64
65 output_buffer *[]byte // String output data.
66 output_writer io.Writer // File output data.
67
68 buffer []byte // The working buffer.
69 buffer_pos int // The current position of the buffer.
70
71 encoding Encoding // The stream encoding.
72
73 // Emitter stuff
74
75 canonical bool // If the output is in the canonical style?
76 BestIndent int // The number of indentation spaces.
77 best_width int // The preferred width of the output lines.
78 unicode bool // Allow unescaped non-ASCII characters?
79 line_break LineBreak // The preferred line break.
80 quotePreference QuoteStyle // Preferred quote style when quoting is required.
81
82 state EmitterState // The current emitter state.
83 states []EmitterState // The stack of states.
84
85 events []Event // The event queue.
86 events_head int // The head of the event queue.
87
88 indents []int // The stack of indentation levels.
89
90 tag_directives []TagDirective // The list of tag directives.
91
92 indent int // The current indentation level.
93
94 CompactSequenceIndent bool // Is '- ' is considered part of the indentation for sequence elements?
95
96 flow_level int // The current flow level.
97
98 root_context bool // Is it the document root context?
99 sequence_context bool // Is it a sequence context?
100 mapping_context bool // Is it a mapping context?
101 simple_key_context bool // Is it a simple mapping key context?
102
103 line int // The current line.
104 column int // The current column.
105 whitespace bool // If the last character was a whitespace?
106 indention bool // If the last character was an indentation character (' ', '-', '?', ':')?
107 OpenEnded bool // If an explicit document end is required?
108
109 space_above bool // Is there's an empty line above?
110 foot_indent int // The indent used to write the foot comment above, or -1 if none.
111
112 // Anchor analysis.
113 anchor_data struct {
114 anchor []byte // The anchor value.
115 alias bool // Is it an alias?
116 }
117
118 // Tag analysis.
119 tag_data struct {
120 handle []byte // The tag handle.
121 suffix []byte // The tag suffix.
122 }
123
124 // Scalar analysis.
125 scalar_data struct {
126 value []byte // The scalar value.
127 multiline bool // Does the scalar contain line breaks?
128 flow_plain_allowed bool // Can the scalar be expressed in the flow plain style?
129 block_plain_allowed bool // Can the scalar be expressed in the block plain style?
130 single_quoted_allowed bool // Can the scalar be expressed in the single quoted style?
131 block_allowed bool // Can the scalar be expressed in the literal or folded styles?
132 style ScalarStyle // The output style.
133 }
134
135 // Comments
136 HeadComment []byte
137 LineComment []byte
138 FootComment []byte
139 TailComment []byte
140
141 key_line_comment []byte
142
143 // Representer stuff
144
145 opened bool // If the stream was already opened?
146 closed bool // If the stream was already closed?
147
148 // The information associated with the document nodes.
149 anchors *struct {
150 references int // The number of references.
151 anchor int // The anchor id.
152 serialized bool // If the node has been emitted?
153 }
154
155 last_anchor_id int // The last assigned anchor id.
156 }
157
158 // NewEmitter creates a new emitter object.
159 func NewEmitter() Emitter {
160 return Emitter{
161 buffer: make([]byte, output_buffer_size),
162 states: make([]EmitterState, 0, initial_stack_size),
163 events: make([]Event, 0, initial_queue_size),
164 best_width: -1,
165 }
166 }
167
168 // Emit an event.
169 func (emitter *Emitter) Emit(event *Event) error {
170 emitter.events = append(emitter.events, *event)
171 for !emitter.needMoreEvents() {
172 event := &emitter.events[emitter.events_head]
173 if err := emitter.analyzeEvent(event); err != nil {
174 return err
175 }
176 if err := emitter.stateMachine(event); err != nil {
177 return err
178 }
179 event.Delete()
180 emitter.events_head++
181 }
182 return nil
183 }
184
185 // Delete an emitter object.
186 func (emitter *Emitter) Delete() {
187 *emitter = Emitter{}
188 }
189
190 // String write handler.
191 func yamlStringWriteHandler(emitter *Emitter, buffer []byte) error {
192 *emitter.output_buffer = append(*emitter.output_buffer, buffer...)
193 return nil
194 }
195
196 // yamlWriterWriteHandler uses emitter.output_writer to write the
197 // emitted text.
198 func yamlWriterWriteHandler(emitter *Emitter, buffer []byte) error {
199 _, err := emitter.output_writer.Write(buffer)
200 return err
201 }
202
203 // SetOutputString sets a string output.
204 func (emitter *Emitter) SetOutputString(output_buffer *[]byte) {
205 if emitter.write_handler != nil {
206 panic("must set the output target only once")
207 }
208 emitter.write_handler = yamlStringWriteHandler
209 emitter.output_buffer = output_buffer
210 }
211
212 // SetOutputWriter sets a file output.
213 func (emitter *Emitter) SetOutputWriter(w io.Writer) {
214 if emitter.write_handler != nil {
215 panic("must set the output target only once")
216 }
217 emitter.write_handler = yamlWriterWriteHandler
218 emitter.output_writer = w
219 }
220
221 // SetEncoding sets the output encoding.
222 func (emitter *Emitter) SetEncoding(encoding Encoding) {
223 if emitter.encoding != ANY_ENCODING {
224 panic("must set the output encoding only once")
225 }
226 emitter.encoding = encoding
227 }
228
229 // SetCanonical sets the canonical output style.
230 func (emitter *Emitter) SetCanonical(canonical bool) {
231 emitter.canonical = canonical
232 }
233
234 // SetIndent sets the indentation increment.
235 func (emitter *Emitter) SetIndent(indent int) {
236 if indent < 2 || indent > 9 {
237 indent = 2
238 }
239 emitter.BestIndent = indent
240 }
241
242 // SetWidth sets the preferred line width.
243 func (emitter *Emitter) SetWidth(width int) {
244 if width < 0 {
245 width = -1
246 }
247 emitter.best_width = width
248 }
249
250 // SetUnicode sets if unescaped non-ASCII characters are allowed.
251 func (emitter *Emitter) SetUnicode(unicode bool) {
252 emitter.unicode = unicode
253 }
254
255 // SetLineBreak sets the preferred line break character.
256 func (emitter *Emitter) SetLineBreak(line_break LineBreak) {
257 emitter.line_break = line_break
258 }
259
260 // State dispatcher.
261 func (emitter *Emitter) stateMachine(event *Event) error {
262 switch emitter.state {
263 default:
264 case EMIT_STREAM_START_STATE:
265 return emitter.emitStreamStart(event)
266
267 case EMIT_FIRST_DOCUMENT_START_STATE:
268 return emitter.emitDocumentStart(event, true)
269
270 case EMIT_DOCUMENT_START_STATE:
271 return emitter.emitDocumentStart(event, false)
272
273 case EMIT_DOCUMENT_CONTENT_STATE:
274 return emitter.emitDocumentContent(event)
275
276 case EMIT_DOCUMENT_END_STATE:
277 return emitter.emitDocumentEnd(event)
278
279 case EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE:
280 return emitter.emitFlowSequenceItem(event, true, false)
281
282 case EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE:
283 return emitter.emitFlowSequenceItem(event, false, true)
284
285 case EMIT_FLOW_SEQUENCE_ITEM_STATE:
286 return emitter.emitFlowSequenceItem(event, false, false)
287
288 case EMIT_FLOW_MAPPING_FIRST_KEY_STATE:
289 return emitter.emitFlowMappingKey(event, true, false)
290
291 case EMIT_FLOW_MAPPING_TRAIL_KEY_STATE:
292 return emitter.emitFlowMappingKey(event, false, true)
293
294 case EMIT_FLOW_MAPPING_KEY_STATE:
295 return emitter.emitFlowMappingKey(event, false, false)
296
297 case EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE:
298 return emitter.emitFlowMappingValue(event, true)
299
300 case EMIT_FLOW_MAPPING_VALUE_STATE:
301 return emitter.emitFlowMappingValue(event, false)
302
303 case EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE:
304 return emitter.emitBlockSequenceItem(event, true)
305
306 case EMIT_BLOCK_SEQUENCE_ITEM_STATE:
307 return emitter.emitBlockSequenceItem(event, false)
308
309 case EMIT_BLOCK_MAPPING_FIRST_KEY_STATE:
310 return emitter.emitBlockMappingKey(event, true)
311
312 case EMIT_BLOCK_MAPPING_KEY_STATE:
313 return emitter.emitBlockMappingKey(event, false)
314
315 case EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE:
316 return emitter.emitBlockMappingValue(event, true)
317
318 case EMIT_BLOCK_MAPPING_VALUE_STATE:
319 return emitter.emitBlockMappingValue(event, false)
320
321 case EMIT_END_STATE:
322 return EmitterError{
323 Message: "expected nothing after STREAM-END",
324 }
325 }
326 panic("invalid emitter state")
327 }
328
329 // Check if we need to accumulate more events before emitting.
330 //
331 // We accumulate extra
332 // - 1 event for DOCUMENT-START
333 // - 2 events for SEQUENCE-START
334 // - 3 events for MAPPING-START
335 func (emitter *Emitter) needMoreEvents() bool {
336 if emitter.events_head == len(emitter.events) {
337 return true
338 }
339 var accumulate int
340 switch emitter.events[emitter.events_head].Type {
341 case DOCUMENT_START_EVENT:
342 accumulate = 1
343 case SEQUENCE_START_EVENT:
344 accumulate = 2
345 case MAPPING_START_EVENT:
346 accumulate = 3
347 default:
348 return false
349 }
350 if len(emitter.events)-emitter.events_head > accumulate {
351 return false
352 }
353 var level int
354 for i := emitter.events_head; i < len(emitter.events); i++ {
355 switch emitter.events[i].Type {
356 case STREAM_START_EVENT, DOCUMENT_START_EVENT, SEQUENCE_START_EVENT, MAPPING_START_EVENT:
357 level++
358 case STREAM_END_EVENT, DOCUMENT_END_EVENT, SEQUENCE_END_EVENT, MAPPING_END_EVENT:
359 level--
360 }
361 if level == 0 {
362 return false
363 }
364 }
365 return true
366 }
367
368 // Expect STREAM-START.
369 func (emitter *Emitter) emitStreamStart(event *Event) error {
370 if event.Type != STREAM_START_EVENT {
371 return EmitterError{
372 Message: "expected STREAM-START",
373 }
374 }
375 if emitter.encoding == ANY_ENCODING {
376 emitter.encoding = event.encoding
377 if emitter.encoding == ANY_ENCODING {
378 emitter.encoding = UTF8_ENCODING
379 }
380 }
381 if emitter.BestIndent < 2 || emitter.BestIndent > 9 {
382 emitter.BestIndent = 2
383 }
384 if emitter.best_width >= 0 && emitter.best_width <= emitter.BestIndent*2 {
385 emitter.best_width = 80
386 }
387 if emitter.best_width < 0 {
388 emitter.best_width = 1<<31 - 1
389 }
390 if emitter.line_break == ANY_BREAK {
391 emitter.line_break = LN_BREAK
392 }
393
394 emitter.indent = -1
395 emitter.line = 0
396 emitter.column = 0
397 emitter.whitespace = true
398 emitter.indention = true
399 emitter.space_above = true
400 emitter.foot_indent = -1
401
402 if emitter.encoding != UTF8_ENCODING {
403 if err := emitter.writeBom(); err != nil {
404 return err
405 }
406 }
407 emitter.state = EMIT_FIRST_DOCUMENT_START_STATE
408 return nil
409 }
410
411 // Expect DOCUMENT-START or STREAM-END.
412 func (emitter *Emitter) emitDocumentStart(event *Event, first bool) error {
413 if event.Type == DOCUMENT_START_EVENT {
414
415 if event.versionDirective != nil {
416 if err := emitter.analyzeVersionDirective(event.versionDirective); err != nil {
417 return err
418 }
419 }
420
421 for i := 0; i < len(event.tagDirectives); i++ {
422 tag_directive := &event.tagDirectives[i]
423 if err := emitter.analyzeTagDirective(tag_directive); err != nil {
424 return err
425 }
426 if err := emitter.appendTagDirective(tag_directive, false); err != nil {
427 return err
428 }
429 }
430
431 for i := 0; i < len(default_tag_directives); i++ {
432 tag_directive := &default_tag_directives[i]
433 if err := emitter.appendTagDirective(tag_directive, true); err != nil {
434 return err
435 }
436 }
437
438 implicit := event.Implicit
439 if !first || emitter.canonical {
440 implicit = false
441 }
442
443 if emitter.OpenEnded && (event.versionDirective != nil || len(event.tagDirectives) > 0) {
444 if err := emitter.writeIndicator([]byte("..."), true, false, false); err != nil {
445 return err
446 }
447 if err := emitter.writeIndent(); err != nil {
448 return err
449 }
450 }
451
452 if event.versionDirective != nil {
453 implicit = false
454 if err := emitter.writeIndicator([]byte("%YAML"), true, false, false); err != nil {
455 return err
456 }
457 if err := emitter.writeIndicator([]byte("1.1"), true, false, false); err != nil {
458 return err
459 }
460 if err := emitter.writeIndent(); err != nil {
461 return err
462 }
463 }
464
465 if len(event.tagDirectives) > 0 {
466 implicit = false
467 for i := 0; i < len(event.tagDirectives); i++ {
468 tag_directive := &event.tagDirectives[i]
469 if err := emitter.writeIndicator([]byte("%TAG"), true, false, false); err != nil {
470 return err
471 }
472 if err := emitter.writeTagHandle(tag_directive.handle); err != nil {
473 return err
474 }
475 if err := emitter.writeTagContent(tag_directive.prefix, true); err != nil {
476 return err
477 }
478 if err := emitter.writeIndent(); err != nil {
479 return err
480 }
481 }
482 }
483
484 if emitter.checkEmptyDocument() {
485 implicit = false
486 }
487 if !implicit {
488 if err := emitter.writeIndent(); err != nil {
489 return err
490 }
491 if err := emitter.writeIndicator([]byte("---"), true, false, false); err != nil {
492 return err
493 }
494 if emitter.canonical || true {
495 if err := emitter.writeIndent(); err != nil {
496 return err
497 }
498 }
499 }
500
501 if len(emitter.HeadComment) > 0 {
502 if err := emitter.processHeadComment(); err != nil {
503 return err
504 }
505 if err := emitter.putLineBreak(); err != nil {
506 return err
507 }
508 }
509
510 emitter.state = EMIT_DOCUMENT_CONTENT_STATE
511 return nil
512 }
513
514 if event.Type == STREAM_END_EVENT {
515 if emitter.OpenEnded {
516 if err := emitter.writeIndicator([]byte("..."), true, false, false); err != nil {
517 return err
518 }
519 if err := emitter.writeIndent(); err != nil {
520 return err
521 }
522 }
523 if err := emitter.flush(); err != nil {
524 return err
525 }
526 emitter.state = EMIT_END_STATE
527 return nil
528 }
529
530 return EmitterError{
531 Message: "expected DOCUMENT-START or STREAM-END",
532 }
533 }
534
535 // Expect the root node.
536 func (emitter *Emitter) emitDocumentContent(event *Event) error {
537 emitter.states = append(emitter.states, EMIT_DOCUMENT_END_STATE)
538
539 if err := emitter.processHeadComment(); err != nil {
540 return err
541 }
542 if err := emitter.emitNode(event, true, false, false, false); err != nil {
543 return err
544 }
545 if err := emitter.processLineComment(); err != nil {
546 return err
547 }
548 if err := emitter.processFootComment(); err != nil {
549 return err
550 }
551 return nil
552 }
553
554 // Expect DOCUMENT-END.
555 func (emitter *Emitter) emitDocumentEnd(event *Event) error {
556 if event.Type != DOCUMENT_END_EVENT {
557 return EmitterError{
558 Message: "expected DOCUMENT-END",
559 }
560 }
561 // [Go] Force document foot separation.
562 emitter.foot_indent = 0
563 if err := emitter.processFootComment(); err != nil {
564 return err
565 }
566 emitter.foot_indent = -1
567 if err := emitter.writeIndent(); err != nil {
568 return err
569 }
570 if !event.Implicit {
571 // [Go] Allocate the slice elsewhere.
572 if err := emitter.writeIndicator([]byte("..."), true, false, false); err != nil {
573 return err
574 }
575 if err := emitter.writeIndent(); err != nil {
576 return err
577 }
578 }
579 if err := emitter.flush(); err != nil {
580 return err
581 }
582 emitter.state = EMIT_DOCUMENT_START_STATE
583 emitter.tag_directives = emitter.tag_directives[:0]
584 return nil
585 }
586
587 // Expect a flow item node.
588 func (emitter *Emitter) emitFlowSequenceItem(event *Event, first, trail bool) error {
589 if first {
590 if err := emitter.writeIndicator([]byte{'['}, true, true, false); err != nil {
591 return err
592 }
593 if err := emitter.increaseIndent(true, false); err != nil {
594 return err
595 }
596 emitter.flow_level++
597 }
598
599 if event.Type == SEQUENCE_END_EVENT {
600 if emitter.canonical && !first && !trail {
601 if err := emitter.writeIndicator([]byte{','}, false, false, false); err != nil {
602 return err
603 }
604 }
605 emitter.flow_level--
606 emitter.indent = emitter.indents[len(emitter.indents)-1]
607 emitter.indents = emitter.indents[:len(emitter.indents)-1]
608 if emitter.column == 0 || emitter.canonical && !first {
609 if err := emitter.writeIndent(); err != nil {
610 return err
611 }
612 }
613 if err := emitter.writeIndicator([]byte{']'}, false, false, false); err != nil {
614 return err
615 }
616 if err := emitter.processLineComment(); err != nil {
617 return err
618 }
619 if err := emitter.processFootComment(); err != nil {
620 return err
621 }
622 emitter.state = emitter.states[len(emitter.states)-1]
623 emitter.states = emitter.states[:len(emitter.states)-1]
624
625 return nil
626 }
627
628 if !first && !trail {
629 if err := emitter.writeIndicator([]byte{','}, false, false, false); err != nil {
630 return err
631 }
632 }
633
634 if err := emitter.processHeadComment(); err != nil {
635 return err
636 }
637 if emitter.column == 0 {
638 if err := emitter.writeIndent(); err != nil {
639 return err
640 }
641 }
642
643 if emitter.canonical || emitter.column > emitter.best_width {
644 if err := emitter.writeIndent(); err != nil {
645 return err
646 }
647 }
648 if len(emitter.LineComment)+len(emitter.FootComment)+len(emitter.TailComment) > 0 {
649 emitter.states = append(emitter.states, EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE)
650 } else {
651 emitter.states = append(emitter.states, EMIT_FLOW_SEQUENCE_ITEM_STATE)
652 }
653 if err := emitter.emitNode(event, false, true, false, false); err != nil {
654 return err
655 }
656 if len(emitter.LineComment)+len(emitter.FootComment)+len(emitter.TailComment) > 0 {
657 if err := emitter.writeIndicator([]byte{','}, false, false, false); err != nil {
658 return err
659 }
660 }
661 if err := emitter.processLineComment(); err != nil {
662 return err
663 }
664 if err := emitter.processFootComment(); err != nil {
665 return err
666 }
667 return nil
668 }
669
670 // Expect a flow key node.
671 func (emitter *Emitter) emitFlowMappingKey(event *Event, first, trail bool) error {
672 if first {
673 if err := emitter.writeIndicator([]byte{'{'}, true, true, false); err != nil {
674 return err
675 }
676 if err := emitter.increaseIndent(true, false); err != nil {
677 return err
678 }
679 emitter.flow_level++
680 }
681
682 if event.Type == MAPPING_END_EVENT {
683 if (emitter.canonical ||
684 len(emitter.HeadComment)+len(emitter.FootComment)+len(emitter.TailComment) > 0) &&
685 !first && !trail {
686 if err := emitter.writeIndicator([]byte{','}, false, false, false); err != nil {
687 return err
688 }
689 }
690 if err := emitter.processHeadComment(); err != nil {
691 return err
692 }
693 emitter.flow_level--
694 emitter.indent = emitter.indents[len(emitter.indents)-1]
695 emitter.indents = emitter.indents[:len(emitter.indents)-1]
696 if emitter.canonical && !first {
697 if err := emitter.writeIndent(); err != nil {
698 return err
699 }
700 }
701 if err := emitter.writeIndicator([]byte{'}'}, false, false, false); err != nil {
702 return err
703 }
704 if err := emitter.processLineComment(); err != nil {
705 return err
706 }
707 if err := emitter.processFootComment(); err != nil {
708 return err
709 }
710 emitter.state = emitter.states[len(emitter.states)-1]
711 emitter.states = emitter.states[:len(emitter.states)-1]
712 return nil
713 }
714
715 if !first && !trail {
716 if err := emitter.writeIndicator([]byte{','}, false, false, false); err != nil {
717 return err
718 }
719 }
720
721 if err := emitter.processHeadComment(); err != nil {
722 return err
723 }
724
725 if emitter.column == 0 {
726 if err := emitter.writeIndent(); err != nil {
727 return err
728 }
729 }
730
731 if emitter.canonical || emitter.column > emitter.best_width {
732 if err := emitter.writeIndent(); err != nil {
733 return err
734 }
735 }
736
737 if !emitter.canonical && emitter.checkSimpleKey() {
738 emitter.states = append(emitter.states, EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE)
739 return emitter.emitNode(event, false, false, true, true)
740 }
741 if err := emitter.writeIndicator([]byte{'?'}, true, false, false); err != nil {
742 return err
743 }
744 emitter.states = append(emitter.states, EMIT_FLOW_MAPPING_VALUE_STATE)
745 return emitter.emitNode(event, false, false, true, false)
746 }
747
748 // Expect a flow value node.
749 func (emitter *Emitter) emitFlowMappingValue(event *Event, simple bool) error {
750 if simple {
751 if err := emitter.writeIndicator([]byte{':'}, false, false, false); err != nil {
752 return err
753 }
754 } else {
755 if emitter.canonical || emitter.column > emitter.best_width {
756 if err := emitter.writeIndent(); err != nil {
757 return err
758 }
759 }
760 if err := emitter.writeIndicator([]byte{':'}, true, false, false); err != nil {
761 return err
762 }
763 }
764 if len(emitter.LineComment)+len(emitter.FootComment)+len(emitter.TailComment) > 0 {
765 emitter.states = append(emitter.states, EMIT_FLOW_MAPPING_TRAIL_KEY_STATE)
766 } else {
767 emitter.states = append(emitter.states, EMIT_FLOW_MAPPING_KEY_STATE)
768 }
769 if err := emitter.emitNode(event, false, false, true, false); err != nil {
770 return err
771 }
772 if len(emitter.LineComment)+len(emitter.FootComment)+len(emitter.TailComment) > 0 {
773 if err := emitter.writeIndicator([]byte{','}, false, false, false); err != nil {
774 return err
775 }
776 }
777 if err := emitter.processLineComment(); err != nil {
778 return err
779 }
780 if err := emitter.processFootComment(); err != nil {
781 return err
782 }
783 return nil
784 }
785
786 // Expect a block item node.
787 func (emitter *Emitter) emitBlockSequenceItem(event *Event, first bool) error {
788 if first {
789 // emitter.mapping context tells us if we are currently in a
790 // mapping context. emitter.column tells us which column we
791 // are in the yaml output. 0 is the first char of the column.
792 // emitter.indentation tells us if the last character was an
793 // indentation character.
794 // emitter.compact_sequence_indent tells us if '- ' is
795 // considered part of the indentation for sequence elements.
796 // So, `seq` means that we are in a mapping context, and we are
797 // either at the first char of the column or the last character
798 // was not an indentation character, and we consider '- ' part
799 // of the indentation for sequence elements.
800 seq := emitter.mapping_context && (emitter.column == 0 || !emitter.indention) &&
801 emitter.CompactSequenceIndent
802 if err := emitter.increaseIndentCompact(false, false, seq); err != nil {
803 return err
804 }
805 }
806 if event.Type == SEQUENCE_END_EVENT {
807 emitter.indent = emitter.indents[len(emitter.indents)-1]
808 emitter.indents = emitter.indents[:len(emitter.indents)-1]
809 emitter.state = emitter.states[len(emitter.states)-1]
810 emitter.states = emitter.states[:len(emitter.states)-1]
811 return nil
812 }
813 if err := emitter.processHeadComment(); err != nil {
814 return err
815 }
816 if err := emitter.writeIndent(); err != nil {
817 return err
818 }
819 if err := emitter.writeIndicator([]byte{'-'}, true, false, true); err != nil {
820 return err
821 }
822 emitter.states = append(emitter.states, EMIT_BLOCK_SEQUENCE_ITEM_STATE)
823 if err := emitter.emitNode(event, false, true, false, false); err != nil {
824 return err
825 }
826 if err := emitter.processLineComment(); err != nil {
827 return err
828 }
829 if err := emitter.processFootComment(); err != nil {
830 return err
831 }
832 return nil
833 }
834
835 // Expect a block key node.
836 func (emitter *Emitter) emitBlockMappingKey(event *Event, first bool) error {
837 if first {
838 if err := emitter.increaseIndent(false, false); err != nil {
839 return err
840 }
841 }
842 if err := emitter.processHeadComment(); err != nil {
843 return err
844 }
845 if event.Type == MAPPING_END_EVENT {
846 emitter.indent = emitter.indents[len(emitter.indents)-1]
847 emitter.indents = emitter.indents[:len(emitter.indents)-1]
848 emitter.state = emitter.states[len(emitter.states)-1]
849 emitter.states = emitter.states[:len(emitter.states)-1]
850 return nil
851 }
852 if err := emitter.writeIndent(); err != nil {
853 return err
854 }
855 if len(emitter.LineComment) > 0 {
856 // [Go] A line comment was provided for the key. That's unusual as the
857 // scanner associates line comments with the value. Either way,
858 // save the line comment and render it appropriately later.
859 emitter.key_line_comment = emitter.LineComment
860 emitter.LineComment = nil
861 }
862 if emitter.checkSimpleKey() {
863 emitter.states = append(emitter.states, EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE)
864 if err := emitter.emitNode(event, false, false, true, true); err != nil {
865 return err
866 }
867
868 if event.Type == ALIAS_EVENT {
869 // make sure there's a space after the alias
870 return emitter.put(' ')
871 }
872
873 return nil
874 }
875 if err := emitter.writeIndicator([]byte{'?'}, true, false, true); err != nil {
876 return err
877 }
878 emitter.states = append(emitter.states, EMIT_BLOCK_MAPPING_VALUE_STATE)
879 return emitter.emitNode(event, false, false, true, false)
880 }
881
882 // Expect a block value node.
883 func (emitter *Emitter) emitBlockMappingValue(event *Event, simple bool) error {
884 if simple {
885 if err := emitter.writeIndicator([]byte{':'}, false, false, false); err != nil {
886 return err
887 }
888 } else {
889 if err := emitter.writeIndent(); err != nil {
890 return err
891 }
892 if err := emitter.writeIndicator([]byte{':'}, true, false, true); err != nil {
893 return err
894 }
895 }
896 if len(emitter.key_line_comment) > 0 {
897 // [Go] Line comments are generally associated with the value,
898 // but when there's no value on the same line as a mapping key
899 // they end up attached to the key itself.
900 if event.Type == SCALAR_EVENT {
901 if len(emitter.LineComment) == 0 {
902 // A scalar is coming and it has no line
903 // comments by itself yet, so just let it
904 // handle the line comment as usual. If it has
905 // a line comment, we can't have both so the
906 // one from the key is lost.
907 emitter.LineComment = emitter.key_line_comment
908 emitter.key_line_comment = nil
909 }
910 } else if event.SequenceStyle() != FLOW_SEQUENCE_STYLE &&
911 (event.Type == MAPPING_START_EVENT || event.Type == SEQUENCE_START_EVENT) {
912 // An indented block follows, so write the comment
913 // right now.
914 emitter.LineComment, emitter.key_line_comment = emitter.key_line_comment, emitter.LineComment
915 if err := emitter.processLineComment(); err != nil {
916 return err
917 }
918 emitter.LineComment, emitter.key_line_comment = emitter.key_line_comment, emitter.LineComment
919 }
920 }
921 emitter.states = append(emitter.states, EMIT_BLOCK_MAPPING_KEY_STATE)
922 if err := emitter.emitNode(event, false, false, true, false); err != nil {
923 return err
924 }
925 if err := emitter.processLineComment(); err != nil {
926 return err
927 }
928 if err := emitter.processFootComment(); err != nil {
929 return err
930 }
931 return nil
932 }
933
934 // Expect a node.
935 func (emitter *Emitter) emitNode(event *Event,
936 root bool, sequence bool, mapping bool, simple_key bool,
937 ) error {
938 emitter.root_context = root
939 emitter.sequence_context = sequence
940 emitter.mapping_context = mapping
941 emitter.simple_key_context = simple_key
942
943 switch event.Type {
944 case ALIAS_EVENT:
945 return emitter.emitAlias(event)
946 case SCALAR_EVENT:
947 return emitter.emitScalar(event)
948 case SEQUENCE_START_EVENT:
949 return emitter.emitSequenceStart(event)
950 case MAPPING_START_EVENT:
951 return emitter.emitMappingStart(event)
952 default:
953 return EmitterError{
954 Message: fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.Type),
955 }
956 }
957 }
958
959 // Expect ALIAS.
960 func (emitter *Emitter) emitAlias(event *Event) error {
961 if err := emitter.processAnchor(); err != nil {
962 return err
963 }
964 emitter.state = emitter.states[len(emitter.states)-1]
965 emitter.states = emitter.states[:len(emitter.states)-1]
966 return nil
967 }
968
969 // Expect SCALAR.
970 func (emitter *Emitter) emitScalar(event *Event) error {
971 if err := emitter.selectScalarStyle(event); err != nil {
972 return err
973 }
974 if err := emitter.processAnchor(); err != nil {
975 return err
976 }
977 if err := emitter.processTag(); err != nil {
978 return err
979 }
980 if err := emitter.increaseIndent(true, false); err != nil {
981 return err
982 }
983 if err := emitter.processScalar(); err != nil {
984 return err
985 }
986 emitter.indent = emitter.indents[len(emitter.indents)-1]
987 emitter.indents = emitter.indents[:len(emitter.indents)-1]
988 emitter.state = emitter.states[len(emitter.states)-1]
989 emitter.states = emitter.states[:len(emitter.states)-1]
990 return nil
991 }
992
993 // Expect SEQUENCE-START.
994 func (emitter *Emitter) emitSequenceStart(event *Event) error {
995 if err := emitter.processAnchor(); err != nil {
996 return err
997 }
998 if err := emitter.processTag(); err != nil {
999 return err
1000 }
1001 if emitter.flow_level > 0 || emitter.canonical ||
1002 event.SequenceStyle() == FLOW_SEQUENCE_STYLE ||
1003 emitter.checkEmptySequence() {
1004 emitter.state = EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE
1005 } else {
1006 emitter.state = EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE
1007 }
1008 return nil
1009 }
1010
1011 // Expect MAPPING-START.
1012 func (emitter *Emitter) emitMappingStart(event *Event) error {
1013 if err := emitter.processAnchor(); err != nil {
1014 return err
1015 }
1016 if err := emitter.processTag(); err != nil {
1017 return err
1018 }
1019 if emitter.flow_level > 0 || emitter.canonical ||
1020 event.MappingStyle() == FLOW_MAPPING_STYLE ||
1021 emitter.checkEmptyMapping() {
1022 emitter.state = EMIT_FLOW_MAPPING_FIRST_KEY_STATE
1023 } else {
1024 emitter.state = EMIT_BLOCK_MAPPING_FIRST_KEY_STATE
1025 }
1026 return nil
1027 }
1028
1029 // Check if the document content is an empty scalar.
1030 func (emitter *Emitter) checkEmptyDocument() bool {
1031 return false // [Go] Huh?
1032 }
1033
1034 // Check if the next events represent an empty sequence.
1035 func (emitter *Emitter) checkEmptySequence() bool {
1036 if len(emitter.events)-emitter.events_head < 2 {
1037 return false
1038 }
1039 return emitter.events[emitter.events_head].Type == SEQUENCE_START_EVENT &&
1040 emitter.events[emitter.events_head+1].Type == SEQUENCE_END_EVENT
1041 }
1042
1043 // Check if the next events represent an empty mapping.
1044 func (emitter *Emitter) checkEmptyMapping() bool {
1045 if len(emitter.events)-emitter.events_head < 2 {
1046 return false
1047 }
1048 return emitter.events[emitter.events_head].Type == MAPPING_START_EVENT &&
1049 emitter.events[emitter.events_head+1].Type == MAPPING_END_EVENT
1050 }
1051
1052 // Check if the next node can be expressed as a simple key.
1053 func (emitter *Emitter) checkSimpleKey() bool {
1054 length := 0
1055 switch emitter.events[emitter.events_head].Type {
1056 case ALIAS_EVENT:
1057 length += len(emitter.anchor_data.anchor)
1058 case SCALAR_EVENT:
1059 if emitter.scalar_data.multiline {
1060 return false
1061 }
1062 length += len(emitter.anchor_data.anchor) +
1063 len(emitter.tag_data.handle) +
1064 len(emitter.tag_data.suffix) +
1065 len(emitter.scalar_data.value)
1066 case SEQUENCE_START_EVENT:
1067 if !emitter.checkEmptySequence() {
1068 return false
1069 }
1070 length += len(emitter.anchor_data.anchor) +
1071 len(emitter.tag_data.handle) +
1072 len(emitter.tag_data.suffix)
1073 case MAPPING_START_EVENT:
1074 if !emitter.checkEmptyMapping() {
1075 return false
1076 }
1077 length += len(emitter.anchor_data.anchor) +
1078 len(emitter.tag_data.handle) +
1079 len(emitter.tag_data.suffix)
1080 default:
1081 return false
1082 }
1083 return length <= 128
1084 }
1085
1086 // Write an anchor.
1087 func (emitter *Emitter) processAnchor() error {
1088 if emitter.anchor_data.anchor == nil {
1089 return nil
1090 }
1091 c := []byte{'&'}
1092 if emitter.anchor_data.alias {
1093 c[0] = '*'
1094 }
1095 if err := emitter.writeIndicator(c, true, false, false); err != nil {
1096 return err
1097 }
1098 return emitter.writeAnchor(emitter.anchor_data.anchor)
1099 }
1100
1101 // Write a tag.
1102 func (emitter *Emitter) processTag() error {
1103 if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 {
1104 return nil
1105 }
1106 if len(emitter.tag_data.handle) > 0 {
1107 if err := emitter.writeTagHandle(emitter.tag_data.handle); err != nil {
1108 return err
1109 }
1110 if len(emitter.tag_data.suffix) > 0 {
1111 if err := emitter.writeTagContent(emitter.tag_data.suffix, false); err != nil {
1112 return err
1113 }
1114 }
1115 } else {
1116 // [Go] Allocate these slices elsewhere.
1117 if err := emitter.writeIndicator([]byte("!<"), true, false, false); err != nil {
1118 return err
1119 }
1120 if err := emitter.writeTagContent(emitter.tag_data.suffix, false); err != nil {
1121 return err
1122 }
1123 if err := emitter.writeIndicator([]byte{'>'}, false, false, false); err != nil {
1124 return err
1125 }
1126 }
1127 return nil
1128 }
1129
1130 // Write a scalar.
1131 func (emitter *Emitter) processScalar() error {
1132 switch emitter.scalar_data.style {
1133 case PLAIN_SCALAR_STYLE:
1134 return emitter.writePlainScalar(emitter.scalar_data.value, !emitter.simple_key_context)
1135
1136 case SINGLE_QUOTED_SCALAR_STYLE:
1137 return emitter.writeSingleQuotedScalar(emitter.scalar_data.value, !emitter.simple_key_context)
1138
1139 case DOUBLE_QUOTED_SCALAR_STYLE:
1140 return emitter.writeDoubleQuotedScalar(emitter.scalar_data.value, !emitter.simple_key_context)
1141
1142 case LITERAL_SCALAR_STYLE:
1143 return emitter.writeLiteralScalar(emitter.scalar_data.value)
1144
1145 case FOLDED_SCALAR_STYLE:
1146 return emitter.writeFoldedScalar(emitter.scalar_data.value)
1147 }
1148 panic("unknown scalar style")
1149 }
1150
1151 // Write a head comment.
1152 func (emitter *Emitter) processHeadComment() error {
1153 if len(emitter.TailComment) > 0 {
1154 if err := emitter.writeIndent(); err != nil {
1155 return err
1156 }
1157 if err := emitter.writeComment(emitter.TailComment); err != nil {
1158 return err
1159 }
1160 emitter.TailComment = emitter.TailComment[:0]
1161 emitter.foot_indent = emitter.indent
1162 if emitter.foot_indent < 0 {
1163 emitter.foot_indent = 0
1164 }
1165 }
1166
1167 if len(emitter.HeadComment) == 0 {
1168 return nil
1169 }
1170 if err := emitter.writeIndent(); err != nil {
1171 return err
1172 }
1173 if err := emitter.writeComment(emitter.HeadComment); err != nil {
1174 return err
1175 }
1176 emitter.HeadComment = emitter.HeadComment[:0]
1177 return nil
1178 }
1179
1180 // processLineComment preserves the original signature and delegates to
1181 // processLineCommentLinebreak passing false for linebreak
1182 func (emitter *Emitter) processLineComment() error {
1183 return emitter.processLineCommentLinebreak(false)
1184 }
1185
1186 // Write a line comment.
1187 func (emitter *Emitter) processLineCommentLinebreak(linebreak bool) error {
1188 if len(emitter.LineComment) == 0 {
1189 // The next 3 lines are needed to resolve an issue with leading newlines
1190 // See https://github.com/go-yaml/yaml/issues/755
1191 // When linebreak is set to true, put_break will be called and will add
1192 // the needed newline.
1193 if linebreak {
1194 if err := emitter.putLineBreak(); err != nil {
1195 return err
1196 }
1197 }
1198 return nil
1199 }
1200 if !emitter.whitespace {
1201 if err := emitter.put(' '); err != nil {
1202 return err
1203 }
1204 }
1205 if err := emitter.writeComment(emitter.LineComment); err != nil {
1206 return err
1207 }
1208 emitter.LineComment = emitter.LineComment[:0]
1209 return nil
1210 }
1211
1212 // Write a foot comment.
1213 func (emitter *Emitter) processFootComment() error {
1214 if len(emitter.FootComment) == 0 {
1215 return nil
1216 }
1217 if err := emitter.writeIndent(); err != nil {
1218 return err
1219 }
1220 if err := emitter.writeComment(emitter.FootComment); err != nil {
1221 return err
1222 }
1223 emitter.FootComment = emitter.FootComment[:0]
1224 emitter.foot_indent = emitter.indent
1225 if emitter.foot_indent < 0 {
1226 emitter.foot_indent = 0
1227 }
1228 return nil
1229 }
1230
1231 // Check if a %YAML directive is valid.
1232 func (emitter *Emitter) analyzeVersionDirective(version_directive *VersionDirective) error {
1233 if version_directive.major != 1 || version_directive.minor != 1 {
1234 return EmitterError{
1235 Message: "incompatible %YAML directive",
1236 }
1237 }
1238 return nil
1239 }
1240
1241 // Check if a %TAG directive is valid.
1242 func (emitter *Emitter) analyzeTagDirective(tag_directive *TagDirective) error {
1243 handle := tag_directive.handle
1244 prefix := tag_directive.prefix
1245 if len(handle) == 0 {
1246 return EmitterError{
1247 Message: "tag handle must not be empty",
1248 }
1249 }
1250 if handle[0] != '!' {
1251 return EmitterError{
1252 Message: "tag handle must start with '!'",
1253 }
1254 }
1255 if handle[len(handle)-1] != '!' {
1256 return EmitterError{
1257 Message: "tag handle must end with '!'",
1258 }
1259 }
1260 for i := 1; i < len(handle)-1; i += width(handle[i]) {
1261 if !isAlpha(handle, i) {
1262 return EmitterError{
1263 Message: "tag handle must contain alphanumerical characters only",
1264 }
1265 }
1266 }
1267 if len(prefix) == 0 {
1268 return EmitterError{
1269 Message: "tag prefix must not be empty",
1270 }
1271 }
1272 return nil
1273 }
1274
1275 // Check if an anchor is valid.
1276 func (emitter *Emitter) analyzeAnchor(anchor []byte, alias bool) error {
1277 if len(anchor) == 0 {
1278 problem := "anchor value must not be empty"
1279 if alias {
1280 problem = "alias value must not be empty"
1281 }
1282 return EmitterError{
1283 Message: problem,
1284 }
1285 }
1286 for i := 0; i < len(anchor); i += width(anchor[i]) {
1287 if !isAnchorChar(anchor, i) {
1288 problem := "anchor value must contain valid characters only"
1289 if alias {
1290 problem = "alias value must contain valid characters only"
1291 }
1292 return EmitterError{
1293 Message: problem,
1294 }
1295 }
1296 }
1297 emitter.anchor_data.anchor = anchor
1298 emitter.anchor_data.alias = alias
1299 return nil
1300 }
1301
1302 // Check if a tag is valid.
1303 func (emitter *Emitter) analyzeTag(tag []byte) error {
1304 if len(tag) == 0 {
1305 return EmitterError{
1306 Message: "tag value must not be empty",
1307 }
1308 }
1309 for i := 0; i < len(emitter.tag_directives); i++ {
1310 tag_directive := &emitter.tag_directives[i]
1311 if bytes.HasPrefix(tag, tag_directive.prefix) {
1312 emitter.tag_data.handle = tag_directive.handle
1313 emitter.tag_data.suffix = tag[len(tag_directive.prefix):]
1314 return nil
1315 }
1316 }
1317 emitter.tag_data.suffix = tag
1318 return nil
1319 }
1320
1321 // Check if a scalar is valid.
1322 func (emitter *Emitter) analyzeScalar(value []byte) error {
1323 var block_indicators,
1324 flow_indicators,
1325 line_breaks,
1326 special_characters,
1327 tab_characters,
1328
1329 leading_space,
1330 leading_break,
1331 trailing_space,
1332 trailing_break,
1333 break_space,
1334 space_break,
1335
1336 preceded_by_whitespace,
1337 followed_by_whitespace,
1338 previous_space,
1339 previous_break bool
1340
1341 emitter.scalar_data.value = value
1342
1343 if len(value) == 0 {
1344 emitter.scalar_data.multiline = false
1345 emitter.scalar_data.flow_plain_allowed = false
1346 emitter.scalar_data.block_plain_allowed = true
1347 emitter.scalar_data.single_quoted_allowed = true
1348 emitter.scalar_data.block_allowed = false
1349 return nil
1350 }
1351
1352 if len(value) >= 3 &&
1353 ((value[0] == '-' && value[1] == '-' && value[2] == '-') ||
1354 (value[0] == '.' && value[1] == '.' && value[2] == '.')) {
1355 block_indicators = true
1356 flow_indicators = true
1357 }
1358
1359 preceded_by_whitespace = true
1360 for i, w := 0, 0; i < len(value); i += w {
1361 w = width(value[i])
1362 followed_by_whitespace = i+w >= len(value) || isBlank(value, i+w)
1363
1364 if i == 0 {
1365 switch value[i] {
1366 case '#', ',', '[', ']', '{', '}', '&', '*', '!',
1367 '|', '>', '\'', '"', '%', '@', '`':
1368 flow_indicators = true
1369 block_indicators = true
1370 case '?', ':':
1371 flow_indicators = true
1372 if followed_by_whitespace {
1373 block_indicators = true
1374 }
1375 case '-':
1376 if followed_by_whitespace {
1377 flow_indicators = true
1378 block_indicators = true
1379 }
1380 }
1381 } else {
1382 switch value[i] {
1383 case ',', '?', '[', ']', '{', '}':
1384 flow_indicators = true
1385 case ':':
1386 flow_indicators = true
1387 if followed_by_whitespace {
1388 block_indicators = true
1389 }
1390 case '#':
1391 if preceded_by_whitespace {
1392 flow_indicators = true
1393 block_indicators = true
1394 }
1395 }
1396 }
1397
1398 if value[i] == '\t' {
1399 tab_characters = true
1400 } else if !isPrintable(value, i) || !isASCII(value, i) && !emitter.unicode {
1401 special_characters = true
1402 }
1403 if isSpace(value, i) {
1404 if i == 0 {
1405 leading_space = true
1406 }
1407 if i+width(value[i]) == len(value) {
1408 trailing_space = true
1409 }
1410 if previous_break {
1411 break_space = true
1412 }
1413 previous_space = true
1414 previous_break = false
1415 } else if isLineBreak(value, i) {
1416 line_breaks = true
1417 if i == 0 {
1418 leading_break = true
1419 }
1420 if i+width(value[i]) == len(value) {
1421 trailing_break = true
1422 }
1423 if previous_space {
1424 space_break = true
1425 }
1426 previous_space = false
1427 previous_break = true
1428 } else {
1429 previous_space = false
1430 previous_break = false
1431 }
1432
1433 // [Go]: Why 'z'? Couldn't be the end of the string as that's
1434 // the loop condition.
1435 preceded_by_whitespace = isBlankOrZero(value, i)
1436 }
1437
1438 emitter.scalar_data.multiline = line_breaks
1439 emitter.scalar_data.flow_plain_allowed = true
1440 emitter.scalar_data.block_plain_allowed = true
1441 emitter.scalar_data.single_quoted_allowed = true
1442 emitter.scalar_data.block_allowed = true
1443
1444 if leading_space || leading_break || trailing_space || trailing_break {
1445 emitter.scalar_data.flow_plain_allowed = false
1446 emitter.scalar_data.block_plain_allowed = false
1447 }
1448 if trailing_space {
1449 emitter.scalar_data.block_allowed = false
1450 }
1451 if break_space {
1452 emitter.scalar_data.flow_plain_allowed = false
1453 emitter.scalar_data.block_plain_allowed = false
1454 emitter.scalar_data.single_quoted_allowed = false
1455 }
1456 if space_break || tab_characters || special_characters {
1457 emitter.scalar_data.flow_plain_allowed = false
1458 emitter.scalar_data.block_plain_allowed = false
1459 emitter.scalar_data.single_quoted_allowed = false
1460 }
1461 if space_break || special_characters {
1462 emitter.scalar_data.block_allowed = false
1463 }
1464 if line_breaks {
1465 emitter.scalar_data.flow_plain_allowed = false
1466 emitter.scalar_data.block_plain_allowed = false
1467 }
1468 if flow_indicators {
1469 emitter.scalar_data.flow_plain_allowed = false
1470 }
1471 if block_indicators {
1472 emitter.scalar_data.block_plain_allowed = false
1473 }
1474 return nil
1475 }
1476
1477 // Check if the event data is valid.
1478 func (emitter *Emitter) analyzeEvent(event *Event) error {
1479 emitter.anchor_data.anchor = nil
1480 emitter.tag_data.handle = nil
1481 emitter.tag_data.suffix = nil
1482 emitter.scalar_data.value = nil
1483
1484 if len(event.HeadComment) > 0 {
1485 emitter.HeadComment = event.HeadComment
1486 }
1487 if len(event.LineComment) > 0 {
1488 emitter.LineComment = event.LineComment
1489 }
1490 if len(event.FootComment) > 0 {
1491 emitter.FootComment = event.FootComment
1492 }
1493 if len(event.TailComment) > 0 {
1494 emitter.TailComment = event.TailComment
1495 }
1496
1497 switch event.Type {
1498 case ALIAS_EVENT:
1499 if err := emitter.analyzeAnchor(event.Anchor, true); err != nil {
1500 return err
1501 }
1502
1503 case SCALAR_EVENT:
1504 if len(event.Anchor) > 0 {
1505 if err := emitter.analyzeAnchor(event.Anchor, false); err != nil {
1506 return err
1507 }
1508 }
1509 if len(event.Tag) > 0 && (emitter.canonical ||
1510 (!event.Implicit && !event.quoted_implicit)) {
1511 if err := emitter.analyzeTag(event.Tag); err != nil {
1512 return err
1513 }
1514 }
1515 if err := emitter.analyzeScalar(event.Value); err != nil {
1516 return err
1517 }
1518
1519 case SEQUENCE_START_EVENT:
1520 if len(event.Anchor) > 0 {
1521 if err := emitter.analyzeAnchor(event.Anchor, false); err != nil {
1522 return err
1523 }
1524 }
1525 if len(event.Tag) > 0 && (emitter.canonical || !event.Implicit) {
1526 if err := emitter.analyzeTag(event.Tag); err != nil {
1527 return err
1528 }
1529 }
1530
1531 case MAPPING_START_EVENT:
1532 if len(event.Anchor) > 0 {
1533 if err := emitter.analyzeAnchor(event.Anchor, false); err != nil {
1534 return err
1535 }
1536 }
1537 if len(event.Tag) > 0 && (emitter.canonical || !event.Implicit) {
1538 if err := emitter.analyzeTag(event.Tag); err != nil {
1539 return err
1540 }
1541 }
1542 }
1543 return nil
1544 }
1545
1546 // Determine an acceptable scalar style.
1547 func (emitter *Emitter) selectScalarStyle(event *Event) error {
1548 no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0
1549 if no_tag && !event.Implicit && !event.quoted_implicit {
1550 return EmitterError{
1551 Message: "neither tag nor implicit flags are specified",
1552 }
1553 }
1554
1555 style := event.ScalarStyle()
1556 if style == ANY_SCALAR_STYLE {
1557 style = PLAIN_SCALAR_STYLE
1558 }
1559 if emitter.canonical {
1560 style = DOUBLE_QUOTED_SCALAR_STYLE
1561 }
1562 if emitter.simple_key_context && emitter.scalar_data.multiline {
1563 style = DOUBLE_QUOTED_SCALAR_STYLE
1564 }
1565
1566 if style == PLAIN_SCALAR_STYLE {
1567 if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed ||
1568 emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed {
1569 style = emitter.requiredQuoteStyle()
1570 }
1571 if len(emitter.scalar_data.value) == 0 &&
1572 (emitter.flow_level > 0 || emitter.simple_key_context) {
1573 style = emitter.requiredQuoteStyle()
1574 }
1575 if no_tag && !event.Implicit {
1576 style = emitter.requiredQuoteStyle()
1577 }
1578 }
1579 if style == SINGLE_QUOTED_SCALAR_STYLE {
1580 if !emitter.scalar_data.single_quoted_allowed {
1581 style = DOUBLE_QUOTED_SCALAR_STYLE
1582 }
1583 }
1584 if style == LITERAL_SCALAR_STYLE || style == FOLDED_SCALAR_STYLE {
1585 if !emitter.scalar_data.block_allowed ||
1586 emitter.flow_level > 0 || emitter.simple_key_context {
1587 style = DOUBLE_QUOTED_SCALAR_STYLE
1588 }
1589 }
1590
1591 if no_tag && !event.quoted_implicit && style != PLAIN_SCALAR_STYLE {
1592 emitter.tag_data.handle = []byte{'!'}
1593 }
1594 emitter.scalar_data.style = style
1595 return nil
1596 }
1597
1598 // Write the BOM character.
1599 func (emitter *Emitter) writeBom() error {
1600 if err := emitter.flushIfNeeded(); err != nil {
1601 return err
1602 }
1603 pos := emitter.buffer_pos
1604 emitter.buffer[pos+0] = '\xEF'
1605 emitter.buffer[pos+1] = '\xBB'
1606 emitter.buffer[pos+2] = '\xBF'
1607 emitter.buffer_pos += 3
1608 return nil
1609 }
1610
1611 // writeIndent writes the appropriate indentation to the output.
1612 func (emitter *Emitter) writeIndent() error {
1613 indent := emitter.indent
1614 if indent < 0 {
1615 indent = 0
1616 }
1617 if !emitter.indention || emitter.column > indent ||
1618 (emitter.column == indent && !emitter.whitespace) {
1619 if err := emitter.putLineBreak(); err != nil {
1620 return err
1621 }
1622 }
1623 if emitter.foot_indent == indent {
1624 if err := emitter.putLineBreak(); err != nil {
1625 return err
1626 }
1627 }
1628 for emitter.column < indent {
1629 if err := emitter.put(' '); err != nil {
1630 return err
1631 }
1632 }
1633 emitter.whitespace = true
1634 emitter.space_above = false
1635 emitter.foot_indent = -1
1636 return nil
1637 }
1638
1639 // writeIndicator writes a YAML indicator (like ':', '-', '?') to the output.
1640 func (emitter *Emitter) writeIndicator(indicator []byte, need_whitespace, is_whitespace, is_indention bool) error {
1641 if need_whitespace && !emitter.whitespace {
1642 if err := emitter.put(' '); err != nil {
1643 return err
1644 }
1645 }
1646 if err := emitter.writeAll(indicator); err != nil {
1647 return err
1648 }
1649 emitter.whitespace = is_whitespace
1650 emitter.indention = (emitter.indention && is_indention)
1651 emitter.OpenEnded = false
1652 return nil
1653 }
1654
1655 // writeAnchor writes an anchor name to the output.
1656 func (emitter *Emitter) writeAnchor(value []byte) error {
1657 if err := emitter.writeAll(value); err != nil {
1658 return err
1659 }
1660 emitter.whitespace = false
1661 emitter.indention = false
1662 return nil
1663 }
1664
1665 // writeTagHandle writes a tag handle to the output.
1666 func (emitter *Emitter) writeTagHandle(value []byte) error {
1667 if !emitter.whitespace {
1668 if err := emitter.put(' '); err != nil {
1669 return err
1670 }
1671 }
1672 if err := emitter.writeAll(value); err != nil {
1673 return err
1674 }
1675 emitter.whitespace = false
1676 emitter.indention = false
1677 return nil
1678 }
1679
1680 // writeTagContent writes a tag URI to the output, URL-encoding special
1681 // characters as needed.
1682 func (emitter *Emitter) writeTagContent(value []byte, need_whitespace bool) error {
1683 if need_whitespace && !emitter.whitespace {
1684 if err := emitter.put(' '); err != nil {
1685 return err
1686 }
1687 }
1688 for i := 0; i < len(value); {
1689 var must_write bool
1690 switch value[i] {
1691 case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',',
1692 '_', '.', '~', '*', '\'', '(', ')', '[', ']':
1693 must_write = true
1694 default:
1695 must_write = isAlpha(value, i)
1696 }
1697 if must_write {
1698 if err := emitter.write(value, &i); err != nil {
1699 return err
1700 }
1701 } else {
1702 w := width(value[i])
1703 for k := 0; k < w; k++ {
1704 octet := value[i]
1705 i++
1706 if err := emitter.put('%'); err != nil {
1707 return err
1708 }
1709
1710 c := octet >> 4
1711 if c < 10 {
1712 c += '0'
1713 } else {
1714 c += 'A' - 10
1715 }
1716 if err := emitter.put(c); err != nil {
1717 return err
1718 }
1719
1720 c = octet & 0x0f
1721 if c < 10 {
1722 c += '0'
1723 } else {
1724 c += 'A' - 10
1725 }
1726 if err := emitter.put(c); err != nil {
1727 return err
1728 }
1729 }
1730 }
1731 }
1732 emitter.whitespace = false
1733 emitter.indention = false
1734 return nil
1735 }
1736
1737 // writePlainScalar writes a plain (unquoted) scalar to the output, handling
1738 // line breaks and wrapping as needed.
1739 func (emitter *Emitter) writePlainScalar(value []byte, allow_breaks bool) error {
1740 if len(value) > 0 && !emitter.whitespace {
1741 if err := emitter.put(' '); err != nil {
1742 return err
1743 }
1744 }
1745
1746 spaces := false
1747 breaks := false
1748 for i := 0; i < len(value); {
1749 if isSpace(value, i) {
1750 if allow_breaks && !spaces &&
1751 emitter.column > emitter.best_width &&
1752 !isSpace(value, i+1) {
1753 if err := emitter.writeIndent(); err != nil {
1754 return err
1755 }
1756 i += width(value[i])
1757 } else {
1758 if err := emitter.write(value, &i); err != nil {
1759 return err
1760 }
1761 }
1762 spaces = true
1763 } else if isLineBreak(value, i) {
1764 if !breaks && value[i] == '\n' {
1765 if err := emitter.putLineBreak(); err != nil {
1766 return err
1767 }
1768 }
1769 if err := emitter.writeLineBreak(value, &i); err != nil {
1770 return err
1771 }
1772 breaks = true
1773 } else {
1774 if breaks {
1775 if err := emitter.writeIndent(); err != nil {
1776 return err
1777 }
1778 }
1779 if err := emitter.write(value, &i); err != nil {
1780 return err
1781 }
1782 emitter.indention = false
1783 spaces = false
1784 breaks = false
1785 }
1786 }
1787
1788 if len(value) > 0 {
1789 emitter.whitespace = false
1790 }
1791 emitter.indention = false
1792 if emitter.root_context {
1793 emitter.OpenEnded = true
1794 }
1795
1796 return nil
1797 }
1798
1799 // writeSingleQuotedScalar writes a single-quoted scalar to the output,
1800 // escaping single quotes and handling line breaks.
1801 func (emitter *Emitter) writeSingleQuotedScalar(value []byte, allow_breaks bool) error {
1802 if err := emitter.writeIndicator([]byte{'\''}, true, false, false); err != nil {
1803 return err
1804 }
1805
1806 spaces := false
1807 breaks := false
1808 for i := 0; i < len(value); {
1809 if isSpace(value, i) {
1810 if allow_breaks && !spaces &&
1811 emitter.column > emitter.best_width &&
1812 i > 0 && i < len(value)-1 && !isSpace(value, i+1) {
1813 if err := emitter.writeIndent(); err != nil {
1814 return err
1815 }
1816 i += width(value[i])
1817 } else {
1818 if err := emitter.write(value, &i); err != nil {
1819 return err
1820 }
1821 }
1822 spaces = true
1823 } else if isLineBreak(value, i) {
1824 if !breaks && value[i] == '\n' {
1825 if err := emitter.putLineBreak(); err != nil {
1826 return err
1827 }
1828 }
1829 if err := emitter.writeLineBreak(value, &i); err != nil {
1830 return err
1831 }
1832 breaks = true
1833 } else {
1834 if breaks {
1835 if err := emitter.writeIndent(); err != nil {
1836 return err
1837 }
1838 }
1839 if value[i] == '\'' {
1840 if err := emitter.put('\''); err != nil {
1841 return err
1842 }
1843 }
1844 if err := emitter.write(value, &i); err != nil {
1845 return err
1846 }
1847 emitter.indention = false
1848 spaces = false
1849 breaks = false
1850 }
1851 }
1852 if err := emitter.writeIndicator([]byte{'\''}, false, false, false); err != nil {
1853 return err
1854 }
1855 emitter.whitespace = false
1856 emitter.indention = false
1857 return nil
1858 }
1859
1860 // writeDoubleQuotedScalar writes a double-quoted scalar to the output,
1861 // escaping special characters and handling Unicode.
1862 func (emitter *Emitter) writeDoubleQuotedScalar(value []byte, allow_breaks bool) error {
1863 spaces := false
1864 if err := emitter.writeIndicator([]byte{'"'}, true, false, false); err != nil {
1865 return err
1866 }
1867
1868 for i := 0; i < len(value); {
1869 if !isPrintable(value, i) || (!emitter.unicode && !isASCII(value, i)) ||
1870 isBOM(value, i) || isLineBreak(value, i) ||
1871 value[i] == '"' || value[i] == '\\' {
1872
1873 octet := value[i]
1874
1875 var w int
1876 var v rune
1877 switch {
1878 case octet&0x80 == 0x00:
1879 w, v = 1, rune(octet&0x7F)
1880 case octet&0xE0 == 0xC0:
1881 w, v = 2, rune(octet&0x1F)
1882 case octet&0xF0 == 0xE0:
1883 w, v = 3, rune(octet&0x0F)
1884 case octet&0xF8 == 0xF0:
1885 w, v = 4, rune(octet&0x07)
1886 }
1887 for k := 1; k < w; k++ {
1888 octet = value[i+k]
1889 v = (v << 6) + (rune(octet) & 0x3F)
1890 }
1891 i += w
1892
1893 if err := emitter.put('\\'); err != nil {
1894 return err
1895 }
1896
1897 var err error
1898 switch v {
1899 case 0x00:
1900 err = emitter.put('0')
1901 case 0x07:
1902 err = emitter.put('a')
1903 case 0x08:
1904 err = emitter.put('b')
1905 case 0x09:
1906 err = emitter.put('t')
1907 case 0x0A:
1908 err = emitter.put('n')
1909 case 0x0b:
1910 err = emitter.put('v')
1911 case 0x0c:
1912 err = emitter.put('f')
1913 case 0x0d:
1914 err = emitter.put('r')
1915 case 0x1b:
1916 err = emitter.put('e')
1917 case 0x22:
1918 err = emitter.put('"')
1919 case 0x5c:
1920 err = emitter.put('\\')
1921 case 0x85:
1922 err = emitter.put('N')
1923 case 0xA0:
1924 err = emitter.put('_')
1925 case 0x2028:
1926 err = emitter.put('L')
1927 case 0x2029:
1928 err = emitter.put('P')
1929 default:
1930 if v <= 0xFF {
1931 err = emitter.put('x')
1932 w = 2
1933 } else if v <= 0xFFFF {
1934 err = emitter.put('u')
1935 w = 4
1936 } else {
1937 err = emitter.put('U')
1938 w = 8
1939 }
1940 for k := (w - 1) * 4; err == nil && k >= 0; k -= 4 {
1941 digit := byte((v >> uint(k)) & 0x0F)
1942 if digit < 10 {
1943 err = emitter.put(digit + '0')
1944 } else {
1945 err = emitter.put(digit + 'A' - 10)
1946 }
1947 }
1948 }
1949 if err != nil {
1950 return err
1951 }
1952 spaces = false
1953 } else if isSpace(value, i) {
1954 if allow_breaks && !spaces &&
1955 emitter.column > emitter.best_width &&
1956 i > 0 && i < len(value)-1 {
1957 if err := emitter.writeIndent(); err != nil {
1958 return err
1959 }
1960 if isSpace(value, i+1) {
1961 if err := emitter.put('\\'); err != nil {
1962 return err
1963 }
1964 }
1965 i += width(value[i])
1966 } else if err := emitter.write(value, &i); err != nil {
1967 return err
1968 }
1969 spaces = true
1970 } else {
1971 if err := emitter.write(value, &i); err != nil {
1972 return err
1973 }
1974 spaces = false
1975 }
1976 }
1977 if err := emitter.writeIndicator([]byte{'"'}, false, false, false); err != nil {
1978 return err
1979 }
1980 emitter.whitespace = false
1981 emitter.indention = false
1982 return nil
1983 }
1984
1985 // writeBlockScalarHints writes the indentation and chomping indicators for
1986 // block scalars.
1987 func (emitter *Emitter) writeBlockScalarHints(value []byte) error {
1988 if isSpace(value, 0) {
1989 // https://github.com/yaml/go-yaml/issues/65
1990 // isLineBreak(value, 0) removed as the linebreak will only
1991 // write the indentation value.
1992 indent_hint := []byte{'0' + byte(emitter.BestIndent)}
1993 if err := emitter.writeIndicator(indent_hint, false, false, false); err != nil {
1994 return err
1995 }
1996 }
1997
1998 emitter.OpenEnded = false
1999
2000 var chomp_hint [1]byte
2001 if len(value) == 0 {
2002 chomp_hint[0] = '-'
2003 } else {
2004 i := len(value) - 1
2005 for value[i]&0xC0 == 0x80 {
2006 i--
2007 }
2008 if !isLineBreak(value, i) {
2009 chomp_hint[0] = '-'
2010 } else if i == 0 {
2011 chomp_hint[0] = '+'
2012 emitter.OpenEnded = true
2013 } else {
2014 i--
2015 for value[i]&0xC0 == 0x80 {
2016 i--
2017 }
2018 if isLineBreak(value, i) {
2019 chomp_hint[0] = '+'
2020 emitter.OpenEnded = true
2021 }
2022 }
2023 }
2024 if chomp_hint[0] != 0 {
2025 if err := emitter.writeIndicator(chomp_hint[:], false, false, false); err != nil {
2026 return err
2027 }
2028 }
2029 return nil
2030 }
2031
2032 // writeLiteralScalar writes a literal block scalar (|) to the output,
2033 // preserving line breaks exactly.
2034 func (emitter *Emitter) writeLiteralScalar(value []byte) error {
2035 if err := emitter.writeIndicator([]byte{'|'}, true, false, false); err != nil {
2036 return err
2037 }
2038 if err := emitter.writeBlockScalarHints(value); err != nil {
2039 return err
2040 }
2041 if err := emitter.processLineCommentLinebreak(true); err != nil {
2042 return err
2043 }
2044 emitter.whitespace = true
2045 breaks := true
2046 for i := 0; i < len(value); {
2047 if isLineBreak(value, i) {
2048 if err := emitter.writeLineBreak(value, &i); err != nil {
2049 return err
2050 }
2051 breaks = true
2052 } else {
2053 if breaks {
2054 if err := emitter.writeIndent(); err != nil {
2055 return err
2056 }
2057 }
2058 if err := emitter.write(value, &i); err != nil {
2059 return err
2060 }
2061 emitter.indention = false
2062 breaks = false
2063 }
2064 }
2065
2066 return nil
2067 }
2068
2069 // writeFoldedScalar writes a folded block scalar (>) to the output, folding
2070 // long lines at appropriate breaks.
2071 func (emitter *Emitter) writeFoldedScalar(value []byte) error {
2072 if err := emitter.writeIndicator([]byte{'>'}, true, false, false); err != nil {
2073 return err
2074 }
2075 if err := emitter.writeBlockScalarHints(value); err != nil {
2076 return err
2077 }
2078 if err := emitter.processLineCommentLinebreak(true); err != nil {
2079 return err
2080 }
2081
2082 emitter.whitespace = true
2083
2084 breaks := true
2085 leading_spaces := true
2086 for i := 0; i < len(value); {
2087 if isLineBreak(value, i) {
2088 if !breaks && !leading_spaces && value[i] == '\n' {
2089 k := 0
2090 for isLineBreak(value, k) {
2091 k += width(value[k])
2092 }
2093 if !isBlankOrZero(value, k) {
2094 if err := emitter.putLineBreak(); err != nil {
2095 return err
2096 }
2097 }
2098 }
2099 if err := emitter.writeLineBreak(value, &i); err != nil {
2100 return err
2101 }
2102 breaks = true
2103 } else {
2104 if breaks {
2105 if err := emitter.writeIndent(); err != nil {
2106 return err
2107 }
2108 leading_spaces = isBlank(value, i)
2109 }
2110 if !breaks && isSpace(value, i) &&
2111 !isSpace(value, i+1) &&
2112 emitter.column > emitter.best_width {
2113 if err := emitter.writeIndent(); err != nil {
2114 return err
2115 }
2116 i += width(value[i])
2117 } else {
2118 if err := emitter.write(value, &i); err != nil {
2119 return err
2120 }
2121 }
2122 emitter.indention = false
2123 breaks = false
2124 }
2125 }
2126 return nil
2127 }
2128
2129 // writeComment writes a comment to the output, ensuring each line starts
2130 // with '#' and handling line breaks appropriately.
2131 func (emitter *Emitter) writeComment(comment []byte) error {
2132 breaks := false
2133 pound := false
2134 for i := 0; i < len(comment); {
2135 if isLineBreak(comment, i) {
2136 if err := emitter.writeLineBreak(comment, &i); err != nil {
2137 return err
2138 }
2139 breaks = true
2140 pound = false
2141 } else {
2142 if breaks {
2143 if err := emitter.writeIndent(); err != nil {
2144 return err
2145 }
2146 }
2147 if !pound {
2148 if comment[i] != '#' {
2149 if err := emitter.put('#'); err != nil {
2150 return err
2151 }
2152 if err := emitter.put(' '); err != nil {
2153 return err
2154 }
2155 }
2156 pound = true
2157 }
2158 if err := emitter.write(comment, &i); err != nil {
2159 return err
2160 }
2161 emitter.indention = false
2162 breaks = false
2163 }
2164 }
2165 if !breaks {
2166 if err := emitter.putLineBreak(); err != nil {
2167 return err
2168 }
2169 }
2170
2171 emitter.whitespace = true
2172 return nil
2173 }
2174
2175 // Flush the buffer if needed.
2176 func (emitter *Emitter) flushIfNeeded() error {
2177 if emitter.buffer_pos+5 >= len(emitter.buffer) {
2178 return emitter.flush()
2179 }
2180 return nil
2181 }
2182
2183 // Put a character to the output buffer.
2184 func (emitter *Emitter) put(value byte) error {
2185 if emitter.buffer_pos+5 >= len(emitter.buffer) {
2186 if err := emitter.flush(); err != nil {
2187 return err
2188 }
2189 }
2190 emitter.buffer[emitter.buffer_pos] = value
2191 emitter.buffer_pos++
2192 emitter.column++
2193 return nil
2194 }
2195
2196 // Put a line break to the output buffer.
2197 func (emitter *Emitter) putLineBreak() error {
2198 if emitter.buffer_pos+5 >= len(emitter.buffer) {
2199 if err := emitter.flush(); err != nil {
2200 return err
2201 }
2202 }
2203 switch emitter.line_break {
2204 case CR_BREAK:
2205 emitter.buffer[emitter.buffer_pos] = '\r'
2206 emitter.buffer_pos += 1
2207 case LN_BREAK:
2208 emitter.buffer[emitter.buffer_pos] = '\n'
2209 emitter.buffer_pos += 1
2210 case CRLN_BREAK:
2211 emitter.buffer[emitter.buffer_pos+0] = '\r'
2212 emitter.buffer[emitter.buffer_pos+1] = '\n'
2213 emitter.buffer_pos += 2
2214 default:
2215 panic("unknown line break setting")
2216 }
2217 if emitter.column == 0 {
2218 emitter.space_above = true
2219 }
2220 emitter.column = 0
2221 emitter.line++
2222 // [Go] Do this here and below and drop from everywhere else (see
2223 // commented lines).
2224 emitter.indention = true
2225 return nil
2226 }
2227
2228 // Copy a character from a string into buffer.
2229 func (emitter *Emitter) write(s []byte, i *int) error {
2230 if emitter.buffer_pos+5 >= len(emitter.buffer) {
2231 if err := emitter.flush(); err != nil {
2232 return err
2233 }
2234 }
2235 p := emitter.buffer_pos
2236 w := width(s[*i])
2237 switch w {
2238 case 4:
2239 emitter.buffer[p+3] = s[*i+3]
2240 fallthrough
2241 case 3:
2242 emitter.buffer[p+2] = s[*i+2]
2243 fallthrough
2244 case 2:
2245 emitter.buffer[p+1] = s[*i+1]
2246 fallthrough
2247 case 1:
2248 emitter.buffer[p+0] = s[*i+0]
2249 default:
2250 panic("unknown character width")
2251 }
2252 emitter.column++
2253 emitter.buffer_pos += w
2254 *i += w
2255 return nil
2256 }
2257
2258 // Write a whole string into buffer.
2259 func (emitter *Emitter) writeAll(s []byte) error {
2260 for i := 0; i < len(s); {
2261 if err := emitter.write(s, &i); err != nil {
2262 return err
2263 }
2264 }
2265 return nil
2266 }
2267
2268 // Copy a line break character from a string into buffer.
2269 func (emitter *Emitter) writeLineBreak(s []byte, i *int) error {
2270 if s[*i] == '\n' {
2271 if err := emitter.putLineBreak(); err != nil {
2272 return err
2273 }
2274 *i++
2275 } else {
2276 if err := emitter.write(s, i); err != nil {
2277 return err
2278 }
2279 if emitter.column == 0 {
2280 emitter.space_above = true
2281 }
2282 emitter.column = 0
2283 emitter.line++
2284 // [Go] Do this here and above and drop from everywhere else
2285 // (see commented lines).
2286 emitter.indention = true
2287 }
2288 return nil
2289 }
2290
2291 // Append a directive to the directives stack.
2292 func (emitter *Emitter) appendTagDirective(value *TagDirective, allow_duplicates bool) error {
2293 for i := 0; i < len(emitter.tag_directives); i++ {
2294 if bytes.Equal(value.handle, emitter.tag_directives[i].handle) {
2295 if allow_duplicates {
2296 return nil
2297 }
2298 return EmitterError{
2299 Message: "duplicate %TAG directive",
2300 }
2301 }
2302 }
2303
2304 // [Go] Do we actually need to copy this given garbage collection
2305 // and the lack of deallocating destructors?
2306 tag_copy := TagDirective{
2307 handle: make([]byte, len(value.handle)),
2308 prefix: make([]byte, len(value.prefix)),
2309 }
2310 copy(tag_copy.handle, value.handle)
2311 copy(tag_copy.prefix, value.prefix)
2312 emitter.tag_directives = append(emitter.tag_directives, tag_copy)
2313 return nil
2314 }
2315
2316 // Increase the indentation level.
2317 func (emitter *Emitter) increaseIndentCompact(flow, indentless bool, compact_seq bool) error {
2318 emitter.indents = append(emitter.indents, emitter.indent)
2319 if emitter.indent < 0 {
2320 if flow {
2321 emitter.indent = emitter.BestIndent
2322 } else {
2323 emitter.indent = 0
2324 }
2325 } else if !indentless {
2326 // [Go] This was changed so that indentations are more regular.
2327 if emitter.states[len(emitter.states)-1] == EMIT_BLOCK_SEQUENCE_ITEM_STATE {
2328 // The first indent inside a sequence will just skip
2329 // the "- " indicator.
2330 emitter.indent += 2
2331 } else {
2332 // Everything else aligns to the chosen indentation.
2333 emitter.indent = emitter.BestIndent *
2334 ((emitter.indent + emitter.BestIndent) / emitter.BestIndent)
2335 if compact_seq {
2336 // The value compact_seq passed in is almost
2337 // always set to `false` when this function is
2338 // called, except when we are dealing with
2339 // sequence nodes. So this gets triggered to
2340 // subtract 2 only when we are increasing the
2341 // indent to account for sequence nodes, which
2342 // will be correct because we need to subtract
2343 // 2 to account for the - at the beginning of
2344 // the sequence node.
2345 emitter.indent = emitter.indent - 2
2346 }
2347 }
2348 }
2349 return nil
2350 }
2351
2352 // emitter preserves the original signature and delegates to
2353 // increaseIndentCompact without compact-sequence indentation
2354 func (emitter *Emitter) increaseIndent(flow, indentless bool) error {
2355 return emitter.increaseIndentCompact(flow, indentless, false)
2356 }
2357
2358 // silentNilEvent checks if an event represents an implicit null scalar that
2359 // can be omitted in non-canonical mode.
2360 func (emitter *Emitter) silentNilEvent(event *Event) bool {
2361 return event.Type == SCALAR_EVENT && event.Implicit && !emitter.canonical && len(emitter.scalar_data.value) == 0
2362 }
2363
2364 // requiredQuoteStyle returns the appropriate quote style based on the
2365 // emitter's quotePreference setting.
2366 func (emitter *Emitter) requiredQuoteStyle() ScalarStyle {
2367 if emitter.quotePreference == QuoteDouble {
2368 return DOUBLE_QUOTED_SCALAR_STYLE
2369 }
2370 return SINGLE_QUOTED_SCALAR_STYLE
2371 }