Debian Codegraph @

internal/libyaml/serializer.go

raw symbols SCIP
1 // Copyright 2011-2019 Canonical Ltd
2 // Copyright 2025 The go-yaml Project Contributors
3 // SPDX-License-Identifier: Apache-2.0
4
5 // Serializer stage: Converts representation tree (Nodes) to event stream.
6 // Walks the node tree and produces events for the emitter.
7
8 package libyaml
9
10 import (
11 "errors"
12 "fmt"
13 "io"
14 "strings"
15 "unicode/utf8"
16 )
17
18 // Serializer handles serialization of YAML nodes to event stream.
19 type Serializer struct {
20 Emitter Emitter
21 out []byte
22 lineWidth int
23 explicitStart bool
24 explicitEnd bool
25 flowSimpleCollections bool
26 quotePreference QuoteStyle
27 doneInit bool
28 }
29
30 // NewSerializer creates a new Serializer with the given options.
31 func NewSerializer(w io.Writer, opts *Options) *Serializer {
32 emitter := NewEmitter()
33 emitter.CompactSequenceIndent = opts.CompactSeqIndent
34 emitter.quotePreference = opts.QuotePreference
35 emitter.SetWidth(opts.LineWidth)
36 emitter.SetUnicode(opts.Unicode)
37 emitter.SetCanonical(opts.Canonical)
38 emitter.SetLineBreak(opts.LineBreak)
39
40 // Set indentation (defaults to 2 if not specified)
41 indent := opts.Indent
42 if indent == 0 {
43 indent = 2
44 }
45 emitter.BestIndent = indent
46
47 if w != nil {
48 emitter.SetOutputWriter(w)
49 }
50
51 return &Serializer{
52 Emitter: emitter,
53 lineWidth: opts.LineWidth,
54 explicitStart: opts.ExplicitStart,
55 explicitEnd: opts.ExplicitEnd,
56 flowSimpleCollections: opts.FlowSimpleCollections,
57 quotePreference: opts.QuotePreference,
58 }
59 }
60
61 // Serialize walks a Node tree and emits events to produce YAML output.
62 // This is the primary method for the Serializer stage.
63 func (s *Serializer) Serialize(node *Node) {
64 s.init()
65 s.node(node, "")
66 }
67
68 // Sentinel values for event creation.
69 // These provide clarity at call sites, similar to http.NoBody.
70 var (
71 noVersionDirective *VersionDirective = nil
72 noTagDirective []TagDirective = nil
73 )
74
75 // init initializes the serializer by emitting a STREAM_START event.
76 func (s *Serializer) init() {
77 if s.doneInit {
78 return
79 }
80 s.emit(NewStreamStartEvent(UTF8_ENCODING))
81 s.doneInit = true
82 }
83
84 // Finish completes serialization by emitting a STREAM_END event.
85 func (s *Serializer) Finish() {
86 s.Emitter.OpenEnded = false
87 s.emit(NewStreamEndEvent())
88 }
89
90 // node serializes a Node tree into YAML events.
91 // This is the core of the serializer stage - it walks the tree and produces
92 // events.
93 func (s *Serializer) node(node *Node, tail string) {
94 // Zero nodes behave as nil.
95 if node.Kind == 0 && node.IsZero() {
96 s.emitScalar("null", "", "", PLAIN_SCALAR_STYLE, nil, nil, nil, nil)
97 return
98 }
99
100 // Tags have been processed by Desolver:
101 // - Empty tag = can be inferred or style handles it
102 // - Non-empty tag = emit explicitly
103 // Style has also been set by Desolver for quoting needs
104 tag := node.Tag
105 var forceQuoting bool
106 if tag == "" && node.Kind == ScalarNode {
107 // Empty tag with quoting style means the string type needs to
108 // be preserved
109 if node.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0 {
110 forceQuoting = true
111 }
112 }
113
114 switch node.Kind {
115 case DocumentNode:
116 event := NewDocumentStartEvent(noVersionDirective, noTagDirective, !s.explicitStart)
117 event.HeadComment = []byte(node.HeadComment)
118 s.emit(event)
119 for _, node := range node.Content {
120 s.node(node, "")
121 }
122 event = NewDocumentEndEvent(!s.explicitEnd)
123 event.FootComment = []byte(node.FootComment)
124 s.emit(event)
125
126 case SequenceNode:
127 style := BLOCK_SEQUENCE_STYLE
128 // Use flow style if explicitly requested or if it's a simple
129 // collection (scalar-only contents that fit within line width,
130 // enabled via WithFlowSimpleCollections)
131 if node.Style&FlowStyle != 0 || s.isSimpleCollection(node) {
132 style = FLOW_SEQUENCE_STYLE
133 }
134 event := NewSequenceStartEvent([]byte(node.Anchor), []byte(longTag(tag)), tag == "", style)
135 event.HeadComment = []byte(node.HeadComment)
136 s.emit(event)
137 for _, node := range node.Content {
138 s.node(node, "")
139 }
140 event = NewSequenceEndEvent()
141 event.LineComment = []byte(node.LineComment)
142 event.FootComment = []byte(node.FootComment)
143 s.emit(event)
144
145 case MappingNode:
146 style := BLOCK_MAPPING_STYLE
147 // Use flow style if explicitly requested or if it's a simple
148 // collection (scalar-only contents that fit within line width,
149 // enabled via WithFlowSimpleCollections)
150 if node.Style&FlowStyle != 0 || s.isSimpleCollection(node) {
151 style = FLOW_MAPPING_STYLE
152 }
153 event := NewMappingStartEvent([]byte(node.Anchor), []byte(longTag(tag)), tag == "", style)
154 event.TailComment = []byte(tail)
155 event.HeadComment = []byte(node.HeadComment)
156 s.emit(event)
157
158 // The tail logic below moves the foot comment of prior keys to
159 // the following key, since the value for each key may be a
160 // nested structure and the foot needs to be processed only the
161 // entirety of the value is streamed. The last tail is
162 // processed with the mapping end event.
163 var tail string
164 for i := 0; i+1 < len(node.Content); i += 2 {
165 k := node.Content[i]
166 foot := k.FootComment
167 if foot != "" {
168 kopy := *k
169 kopy.FootComment = ""
170 k = &kopy
171 }
172 s.node(k, tail)
173 tail = foot
174
175 v := node.Content[i+1]
176 s.node(v, "")
177 }
178
179 event = NewMappingEndEvent()
180 event.TailComment = []byte(tail)
181 event.LineComment = []byte(node.LineComment)
182 event.FootComment = []byte(node.FootComment)
183 s.emit(event)
184
185 case AliasNode:
186 event := NewAliasEvent([]byte(node.Value))
187 event.HeadComment = []byte(node.HeadComment)
188 event.LineComment = []byte(node.LineComment)
189 event.FootComment = []byte(node.FootComment)
190 s.emit(event)
191
192 case ScalarNode:
193 value := node.Value
194 if !utf8.ValidString(value) {
195 stag := shortTag(tag)
196 if stag == binaryTag {
197 failDumpf(SerializerStage, "explicitly tagged !!binary data must be base64-encoded")
198 }
199 if stag != "" {
200 failDumpf(SerializerStage, "cannot marshal invalid UTF-8 data as %s", stag)
201 }
202 // It can't be represented directly as YAML so use a binary tag
203 // and represent it as base64.
204 tag = binaryTag
205 value = encodeBase64(value)
206 }
207
208 style := PLAIN_SCALAR_STYLE
209 switch {
210 case node.Style&DoubleQuotedStyle != 0:
211 style = DOUBLE_QUOTED_SCALAR_STYLE
212 case node.Style&SingleQuotedStyle != 0:
213 style = SINGLE_QUOTED_SCALAR_STYLE
214 case node.Style&LiteralStyle != 0:
215 style = LITERAL_SCALAR_STYLE
216 case node.Style&FoldedStyle != 0:
217 style = FOLDED_SCALAR_STYLE
218 case strings.Contains(value, "\n"):
219 style = LITERAL_SCALAR_STYLE
220 case forceQuoting:
221 style = s.quotePreference.ScalarStyle()
222 }
223
224 s.emitScalar(value, node.Anchor, tag, style, []byte(node.HeadComment), []byte(node.LineComment), []byte(node.FootComment), []byte(tail))
225 default:
226 failDumpf(SerializerStage, "cannot represent node with unknown kind %d", node.Kind)
227 }
228 }
229
230 // emit sends an event to the underlying emitter.
231 func (s *Serializer) emit(event Event) {
232 s.must(s.Emitter.Emit(&event))
233 }
234
235 // must panics if the given error is non-nil, routing to the appropriate stage.
236 func (s *Serializer) must(err error) {
237 if err == nil {
238 return
239 }
240 var ee EmitterError
241 if errors.As(err, &ee) {
242 failDumpf(EmitterStage, "%s", ee.Message)
243 }
244 var we WriterError
245 if errors.As(err, &we) {
246 // Unwrap to get the original I/O error, stripping the
247 // "write error: " prefix that WriterError adds internally.
248 cause := we.Err
249 if unwrapped := errors.Unwrap(we.Err); unwrapped != nil {
250 cause = unwrapped
251 }
252 failDump(WriterStage, cause)
253 }
254 msg := err.Error()
255 if msg == "" {
256 msg = fmt.Sprintf("unknown problem generating YAML content with %T", err)
257 }
258 failDumpf(SerializerStage, "%s", msg)
259 }
260
261 // emitScalar emits a scalar event with the given value, anchor, tag, style,
262 // and associated comments.
263 func (s *Serializer) emitScalar(
264 value, anchor, tag string, style ScalarStyle, head, line, foot, tail []byte,
265 ) {
266 implicit := tag == ""
267 if !implicit {
268 tag = longTag(tag)
269 }
270 event := NewScalarEvent([]byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)
271 event.HeadComment = head
272 event.LineComment = line
273 event.FootComment = foot
274 event.TailComment = tail
275 s.emit(event)
276 }
277
278 // isSimpleCollection checks if a node contains only scalar values and would
279 // fit within the line width when rendered in flow style.
280 func (s *Serializer) isSimpleCollection(node *Node) bool {
281 if !s.flowSimpleCollections {
282 return false
283 }
284 if node.Kind != SequenceNode && node.Kind != MappingNode {
285 return false
286 }
287 // Check all children are scalars
288 for _, child := range node.Content {
289 if child.Kind != ScalarNode {
290 return false
291 }
292 }
293 // Estimate flow style length
294 estimatedLen := s.estimateFlowLength(node)
295 width := s.lineWidth
296 if width <= 0 {
297 width = 80 // Default width if not set
298 }
299 return estimatedLen > 0 && estimatedLen <= width
300 }
301
302 // estimateFlowLength estimates the character length of a node in flow style.
303 func (s *Serializer) estimateFlowLength(node *Node) int {
304 if node.Kind == SequenceNode {
305 // [item1, item2, ...] = 2 + sum(len(items)) + 2*(len-1)
306 length := 2 // []
307 for i, child := range node.Content {
308 if i > 0 {
309 length += 2 // ", "
310 }
311 length += len(child.Value)
312 }
313 return length
314 }
315 if node.Kind == MappingNode {
316 // {key1: val1, key2: val2} = 2 + sum(key: val) + 2*(pairs-1)
317 length := 2 // {}
318 for i := 0; i < len(node.Content); i += 2 {
319 if i > 0 {
320 length += 2 // ", "
321 }
322 length += len(node.Content[i].Value) + 2 + len(node.Content[i+1].Value) // "key: val"
323 }
324 return length
325 }
326 return 0
327 }
328
329 // NewStreamStartEvent creates a new STREAM-START event.
330 func NewStreamStartEvent(encoding Encoding) Event {
331 return Event{
332 Type: STREAM_START_EVENT,
333 encoding: encoding,
334 }
335 }
336
337 // NewStreamEndEvent creates a new STREAM-END event.
338 func NewStreamEndEvent() Event {
339 return Event{
340 Type: STREAM_END_EVENT,
341 }
342 }
343
344 // NewDocumentStartEvent creates a new DOCUMENT-START event.
345 func NewDocumentStartEvent(version_directive *VersionDirective, tag_directives []TagDirective, implicit bool) Event {
346 return Event{
347 Type: DOCUMENT_START_EVENT,
348 versionDirective: version_directive,
349 tagDirectives: tag_directives,
350 Implicit: implicit,
351 }
352 }
353
354 // NewDocumentEndEvent creates a new DOCUMENT-END event.
355 func NewDocumentEndEvent(implicit bool) Event {
356 return Event{
357 Type: DOCUMENT_END_EVENT,
358 Implicit: implicit,
359 }
360 }
361
362 // NewAliasEvent creates a new ALIAS event.
363 func NewAliasEvent(anchor []byte) Event {
364 return Event{
365 Type: ALIAS_EVENT,
366 Anchor: anchor,
367 }
368 }
369
370 // NewScalarEvent creates a new SCALAR event.
371 func NewScalarEvent(anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style ScalarStyle) Event {
372 return Event{
373 Type: SCALAR_EVENT,
374 Anchor: anchor,
375 Tag: tag,
376 Value: value,
377 Implicit: plain_implicit,
378 quoted_implicit: quoted_implicit,
379 Style: Style(style),
380 }
381 }
382
383 // NewSequenceStartEvent creates a new SEQUENCE-START event.
384 func NewSequenceStartEvent(anchor, tag []byte, implicit bool, style SequenceStyle) Event {
385 return Event{
386 Type: SEQUENCE_START_EVENT,
387 Anchor: anchor,
388 Tag: tag,
389 Implicit: implicit,
390 Style: Style(style),
391 }
392 }
393
394 // NewSequenceEndEvent creates a new SEQUENCE-END event.
395 func NewSequenceEndEvent() Event {
396 return Event{
397 Type: SEQUENCE_END_EVENT,
398 }
399 }
400
401 // NewMappingStartEvent creates a new MAPPING-START event.
402 func NewMappingStartEvent(anchor, tag []byte, implicit bool, style MappingStyle) Event {
403 return Event{
404 Type: MAPPING_START_EVENT,
405 Anchor: anchor,
406 Tag: tag,
407 Implicit: implicit,
408 Style: Style(style),
409 }
410 }
411
412 // NewMappingEndEvent creates a new MAPPING-END event.
413 func NewMappingEndEvent() Event {
414 return Event{
415 Type: MAPPING_END_EVENT,
416 }
417 }
418
419 // Delete an event object.
420 func (e *Event) Delete() {
421 *e = Event{}
422 }