Debian Codegraph @

internal/libyaml/composer.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 // Composer stage: Builds a node tree from a libyaml event stream.
6 // Handles document structure, anchors, and comment attachment.
7
8 package libyaml
9
10 import (
11 "fmt"
12 "io"
13 )
14
15 // Composer produces a node tree out of a libyaml event stream.
16 type Composer struct {
17 Parser Parser
18 event Event
19 doc *Node
20 anchors map[string]*Node
21 doneInit bool
22 Textless bool
23 streamNodes bool // enable stream node emission
24 returnStream bool // flag to return stream node next
25 atStreamEnd bool // at stream end
26 encoding Encoding // stream encoding from STREAM_START
27 opts *Options // options for loading
28 }
29
30 // NewComposer creates a new composer from a byte slice.
31 func NewComposer(b []byte, opts *Options) *Composer {
32 p := Composer{
33 Parser: NewParser(),
34 opts: opts,
35 }
36 if len(b) == 0 {
37 b = []byte{'\n'}
38 }
39 p.Parser.SetInputString(b)
40 if opts != nil {
41 p.Parser.depthCheck = opts.DepthCheck
42 }
43 return &p
44 }
45
46 // NewComposerFromReader creates a new composer from an [io.Reader].
47 func NewComposerFromReader(r io.Reader, opts *Options) *Composer {
48 p := Composer{
49 Parser: NewParser(),
50 opts: opts,
51 }
52 p.Parser.SetInputReader(r)
53 if opts != nil {
54 p.Parser.depthCheck = opts.DepthCheck
55 }
56 return &p
57 }
58
59 // Compose composes the next YAML node from the event stream.
60 func (c *Composer) Compose() *Node {
61 c.init()
62
63 // Handle stream nodes if enabled
64 if c.streamNodes {
65 // Check for stream end first
66 if c.peek() == STREAM_END_EVENT {
67 // If we haven't returned the final stream node yet,
68 // return it now
69 if !c.atStreamEnd {
70 c.atStreamEnd = true
71 return c.createStreamNode()
72 }
73 // Already returned final stream node
74 return nil
75 }
76
77 // Check if we should return a stream node before the next
78 // document
79 if c.returnStream {
80 c.returnStream = false
81 n := c.createStreamNode()
82 // Capture directives from upcoming document
83 c.captureDirectives(n)
84 return n
85 }
86 }
87
88 switch c.peek() {
89 case SCALAR_EVENT:
90 return c.scalar()
91 case ALIAS_EVENT:
92 return c.alias()
93 case MAPPING_START_EVENT:
94 return c.mapping()
95 case SEQUENCE_START_EVENT:
96 return c.sequence()
97 case DOCUMENT_START_EVENT:
98 return c.document()
99 case STREAM_END_EVENT:
100 // Happens when attempting to decode an empty buffer (when not
101 // using stream nodes).
102 return nil
103 case TAIL_COMMENT_EVENT:
104 panic("internal error: unexpected tail comment event (please report)")
105 default:
106 panic("internal error: attempted to parse unknown event (please report): " + c.event.Type.String())
107 }
108 }
109
110 // node creates a new node with the given kind, tag, and value, and attaches
111 // position and comment information from the current event.
112 func (c *Composer) node(kind Kind, tag, value string) *Node {
113 var style Style
114 if tag != "" && tag != "!" {
115 // Normalize tag to short form (e.g., tag:yaml.org,2002:str -> !!str)
116 tag = shortTag(tag)
117 style = TaggedStyle
118 }
119 // Note: Nodes without explicit tags are left with empty tags.
120 // Tag defaulting happens in a separate stage via Resolver.
121 n := &Node{
122 Kind: kind,
123 Tag: tag,
124 Value: value,
125 Style: style,
126 }
127 if !c.Textless {
128 n.Line = c.event.StartMark.Line
129 n.Column = c.event.StartMark.Column
130 n.HeadComment = string(c.event.HeadComment)
131 n.LineComment = string(c.event.LineComment)
132 n.FootComment = string(c.event.FootComment)
133 }
134 return n
135 }
136
137 // document composes a document node by parsing its content between
138 // DOCUMENT_START and DOCUMENT_END events.
139 func (c *Composer) document() *Node {
140 n := c.node(DocumentNode, "", "")
141 c.doc = n
142 c.expect(DOCUMENT_START_EVENT)
143 c.parseChild(n)
144 if c.peek() == DOCUMENT_END_EVENT {
145 n.FootComment = string(c.event.FootComment)
146 }
147 c.expect(DOCUMENT_END_EVENT)
148
149 // If stream nodes enabled, prepare to return a stream node next
150 if c.streamNodes {
151 c.returnStream = true
152 }
153
154 return n
155 }
156
157 // createStreamNode creates a stream node with encoding information.
158 func (c *Composer) createStreamNode() *Node {
159 n := &Node{
160 Kind: StreamNode,
161 Stream: &Stream{Encoding: c.encoding},
162 }
163 if !c.Textless && c.event.Type != NO_EVENT {
164 n.Line = c.event.StartMark.Line
165 n.Column = c.event.StartMark.Column
166 if c.event.Type == STREAM_END_EVENT {
167 n.HeadComment = string(c.event.HeadComment)
168 n.LineComment = string(c.event.LineComment)
169 n.FootComment = string(c.event.FootComment)
170 }
171 }
172 return n
173 }
174
175 // alias composes an alias node by resolving the referenced anchor.
176 func (c *Composer) alias() *Node {
177 n := c.node(AliasNode, "", string(c.event.Anchor))
178 n.Alias = c.anchors[n.Value]
179 if n.Alias == nil {
180 msg := fmt.Sprintf("unknown anchor '%s' referenced", n.Value)
181 Fail(formatComposerError(msg, Mark{
182 Line: n.Line,
183 Column: n.Column,
184 }))
185 }
186 c.expect(ALIAS_EVENT)
187 return n
188 }
189
190 // scalar composes a scalar node with value, tag, and style information.
191 func (c *Composer) scalar() *Node {
192 parsedStyle := c.event.ScalarStyle()
193 var nodeStyle Style
194 switch {
195 case parsedStyle&DOUBLE_QUOTED_SCALAR_STYLE != 0:
196 nodeStyle = DoubleQuotedStyle
197 case parsedStyle&SINGLE_QUOTED_SCALAR_STYLE != 0:
198 nodeStyle = SingleQuotedStyle
199 case parsedStyle&LITERAL_SCALAR_STYLE != 0:
200 nodeStyle = LiteralStyle
201 case parsedStyle&FOLDED_SCALAR_STYLE != 0:
202 nodeStyle = FoldedStyle
203 }
204 nodeValue := string(c.event.Value)
205 nodeTag := string(c.event.Tag)
206 n := c.node(ScalarNode, nodeTag, nodeValue)
207 n.Style |= nodeStyle
208 c.anchor(n, c.event.Anchor)
209 c.expect(SCALAR_EVENT)
210 return n
211 }
212
213 // sequence composes a sequence node by parsing elements between
214 // SEQUENCE_START and SEQUENCE_END events.
215 func (c *Composer) sequence() *Node {
216 n := c.node(SequenceNode, string(c.event.Tag), "")
217 if c.event.SequenceStyle()&FLOW_SEQUENCE_STYLE != 0 {
218 n.Style |= FlowStyle
219 }
220 c.anchor(n, c.event.Anchor)
221 c.expect(SEQUENCE_START_EVENT)
222 for c.peek() != SEQUENCE_END_EVENT {
223 c.parseChild(n)
224 }
225 n.LineComment = string(c.event.LineComment)
226 n.FootComment = string(c.event.FootComment)
227 c.expect(SEQUENCE_END_EVENT)
228 return n
229 }
230
231 // mapping composes a mapping node by parsing key-value pairs between
232 // MAPPING_START and MAPPING_END events, handling foot comments appropriately.
233 func (c *Composer) mapping() *Node {
234 n := c.node(MappingNode, string(c.event.Tag), "")
235 block := true
236 if c.event.MappingStyle()&FLOW_MAPPING_STYLE != 0 {
237 block = false
238 n.Style |= FlowStyle
239 }
240 c.anchor(n, c.event.Anchor)
241 c.expect(MAPPING_START_EVENT)
242 for c.peek() != MAPPING_END_EVENT {
243 k := c.parseChild(n)
244 if block && k.FootComment != "" {
245 // Must be a foot comment for the prior value when being dedented.
246 if len(n.Content) > 2 {
247 n.Content[len(n.Content)-3].FootComment = k.FootComment
248 k.FootComment = ""
249 }
250 }
251 v := c.parseChild(n)
252 if k.FootComment == "" && v.FootComment != "" {
253 k.FootComment = v.FootComment
254 v.FootComment = ""
255 }
256 if c.peek() == TAIL_COMMENT_EVENT {
257 if k.FootComment == "" {
258 k.FootComment = string(c.event.FootComment)
259 }
260 c.expect(TAIL_COMMENT_EVENT)
261 }
262 }
263 n.LineComment = string(c.event.LineComment)
264 n.FootComment = string(c.event.FootComment)
265 if n.Style&FlowStyle == 0 && n.FootComment != "" && len(n.Content) > 1 {
266 n.Content[len(n.Content)-2].FootComment = n.FootComment
267 n.FootComment = ""
268 }
269 c.expect(MAPPING_END_EVENT)
270 return n
271 }
272
273 // init initializes the composer by setting up the anchor map and consuming
274 // the STREAM_START event.
275 func (c *Composer) init() {
276 if c.doneInit {
277 return
278 }
279 c.anchors = make(map[string]*Node)
280 // Peek to get the encoding from STREAM_START_EVENT
281 if c.peek() == STREAM_START_EVENT {
282 c.encoding = c.event.GetEncoding()
283 }
284 c.expect(STREAM_START_EVENT)
285 c.doneInit = true
286
287 // If stream nodes are enabled, prepare to return the first stream node
288 if c.streamNodes {
289 c.returnStream = true
290 }
291 }
292
293 // Destroy cleans up the composer by deleting any pending event and the
294 // underlying parser.
295 func (c *Composer) Destroy() {
296 if c.event.Type != NO_EVENT {
297 c.event.Delete()
298 }
299 c.Parser.Delete()
300 }
301
302 // SetStreamNodes enables or disables stream node emission.
303 func (c *Composer) SetStreamNodes(enable bool) {
304 c.streamNodes = enable
305 }
306
307 // expect consumes an event from the event stream and
308 // checks that it's of the expected type.
309 func (c *Composer) expect(e EventType) {
310 if c.event.Type == NO_EVENT {
311 if err := c.Parser.Parse(&c.event); err != nil {
312 c.fail(err)
313 }
314 }
315 if c.event.Type == STREAM_END_EVENT {
316 Fail(formatComposerError(
317 "attempted to go past the end of stream; corrupted value?",
318 Mark{Line: c.event.StartMark.Line, Column: c.event.StartMark.Column},
319 ))
320 }
321 if c.event.Type != e {
322 Fail(formatComposerError(
323 fmt.Sprintf("expected %s event but got %s", e, c.event.Type),
324 Mark{Line: c.event.StartMark.Line, Column: c.event.StartMark.Column},
325 ))
326 }
327 c.event.Delete()
328 c.event.Type = NO_EVENT
329 }
330
331 // peek peeks at the next event in the event stream,
332 // puts the results into c.event and returns the event type.
333 func (c *Composer) peek() EventType {
334 if c.event.Type != NO_EVENT {
335 return c.event.Type
336 }
337 // It's curious choice from the underlying API to generally return a
338 // positive result on success, but on this case return true in an error
339 // scenario. This was the source of bugs in the past (issue #666).
340 if err := c.Parser.Parse(&c.event); err != nil {
341 c.fail(err)
342 }
343 return c.event.Type
344 }
345
346 // fail panics with the given error.
347 func (c *Composer) fail(err error) {
348 Fail(err)
349 }
350
351 // anchor sets the anchor name on a node and records it in the anchor map.
352 func (c *Composer) anchor(n *Node, anchor []byte) {
353 if anchor != nil {
354 n.Anchor = string(anchor)
355 c.anchors[n.Anchor] = n
356 }
357 }
358
359 // parseChild composes the next node and adds it as a child to the parent.
360 func (c *Composer) parseChild(parent *Node) *Node {
361 child := c.Compose()
362 parent.Content = append(parent.Content, child)
363 return child
364 }
365
366 // captureDirectives captures version and tag directives from upcoming
367 // DOCUMENT_START.
368 // The node n must have Stream initialized (as created by createStreamNode).
369 func (c *Composer) captureDirectives(n *Node) {
370 if c.peek() == DOCUMENT_START_EVENT {
371 if vd := c.event.GetVersionDirective(); vd != nil {
372 n.Stream.Version = &StreamVersionDirective{
373 Major: vd.Major(),
374 Minor: vd.Minor(),
375 }
376 }
377 if tds := c.event.GetTagDirectives(); len(tds) > 0 {
378 n.Stream.TagDirectives = make([]StreamTagDirective, len(tds))
379 for i, td := range tds {
380 n.Stream.TagDirectives[i] = StreamTagDirective{
381 Handle: td.GetHandle(),
382 Prefix: td.GetPrefix(),
383 }
384 }
385 }
386 }
387 }
388
389 // Fail panics with a YAMLError wrapping the given error.
390 func Fail(err error) {
391 panic(&YAMLError{err})
392 }
393
394 // failf panics with a YAMLError containing a formatted error message.
395 func failf(format string, args ...any) {
396 panic(&YAMLError{fmt.Errorf("yaml: "+format, args...)})
397 }
398
399 // formatComposerError creates a LoadError for composer-stage errors.
400 func formatComposerError(message string, mark Mark) *LoadError {
401 return &LoadError{
402 Stage: ComposerStage,
403 Mark: mark,
404 Message: message,
405 }
406 }
407
408 // formatComposerErrorContext creates a LoadError with both context and
409 // problem information for composer-stage errors.
410 func formatComposerErrorContext(context string, contextMark Mark, message string, mark Mark) *LoadError {
411 return &LoadError{
412 Stage: ComposerStage,
413 ContextMark: contextMark,
414 ContextMsg: context,
415 Mark: mark,
416 Message: message,
417 }
418 }