Debian Codegraph @

internal/libyaml/scanner.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 // Scanner stage: Transforms input stream into token sequence.
7 // The Scanner is the most complex stage, handling indentation, simple keys,
8 // and block collection detection.
9
10 package libyaml
11
12 import (
13 "bytes"
14 "fmt"
15 "io"
16 )
17
18 // Introduction
19 // ************
20 //
21 // The following notes assume that you are familiar with the YAML specification
22 // (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in
23 // some cases we are less restrictive that it requires.
24 //
25 // The process of transforming a YAML stream into a sequence of events is
26 // divided on two steps: Scanning and Parsing.
27 //
28 // The Scanner transforms the input stream into a sequence of tokens, while the
29 // parser transform the sequence of tokens produced by the Scanner into a
30 // sequence of parsing events.
31 //
32 // The Scanner is rather clever and complicated. The Parser, on the contrary,
33 // is a straightforward implementation of a recursive-descendant parser (or,
34 // LL(1) parser, as it is usually called).
35 //
36 // Actually there are two issues of Scanning that might be called "clever", the
37 // rest is quite straightforward. The issues are "block collection start" and
38 // "simple keys". Both issues are explained below in details.
39 //
40 // Here the Scanning step is explained and implemented. We start with the list
41 // of all the tokens produced by the Scanner together with short descriptions.
42 //
43 // Now, tokens:
44 //
45 // STREAM-START(encoding) # The stream start.
46 // STREAM-END # The stream end.
47 // VERSION-DIRECTIVE(major,minor) # The '%YAML' directive.
48 // TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive.
49 // DOCUMENT-START # '---'
50 // DOCUMENT-END # '...'
51 // BLOCK-SEQUENCE-START # Indentation increase denoting a block
52 // BLOCK-MAPPING-START # sequence or a block mapping.
53 // BLOCK-END # Indentation decrease.
54 // FLOW-SEQUENCE-START # '['
55 // FLOW-SEQUENCE-END # ']'
56 // BLOCK-SEQUENCE-START # '{'
57 // BLOCK-SEQUENCE-END # '}'
58 // BLOCK-ENTRY # '-'
59 // FLOW-ENTRY # ','
60 // KEY # '?' or nothing (simple keys).
61 // VALUE # ':'
62 // ALIAS(anchor) # '*anchor'
63 // ANCHOR(anchor) # '&anchor'
64 // TAG(handle,suffix) # '!handle!suffix'
65 // SCALAR(value,style) # A scalar.
66 //
67 // The following two tokens are "virtual" tokens denoting the beginning and the
68 // end of the stream:
69 //
70 // STREAM-START(encoding)
71 // STREAM-END
72 //
73 // We pass the information about the input stream encoding with the
74 // STREAM-START token.
75 //
76 // The next two tokens are responsible for tags:
77 //
78 // VERSION-DIRECTIVE(major,minor)
79 // TAG-DIRECTIVE(handle,prefix)
80 //
81 // Example:
82 //
83 // %YAML 1.1
84 // %TAG ! !foo
85 // %TAG !yaml! tag:yaml.org,2002:
86 // ---
87 //
88 // The corresponding sequence of tokens:
89 //
90 // STREAM-START(utf-8)
91 // VERSION-DIRECTIVE(1,1)
92 // TAG-DIRECTIVE("!","!foo")
93 // TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:")
94 // DOCUMENT-START
95 // STREAM-END
96 //
97 // Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole
98 // line.
99 //
100 // The document start and end indicators are represented by:
101 //
102 // DOCUMENT-START
103 // DOCUMENT-END
104 //
105 // Note that if a YAML stream contains an implicit document (without '---'
106 // and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be
107 // produced.
108 //
109 // In the following examples, we present whole documents together with the
110 // produced tokens.
111 //
112 // 1. An implicit document:
113 //
114 // 'a scalar'
115 //
116 // Tokens:
117 //
118 // STREAM-START(utf-8)
119 // SCALAR("a scalar",single-quoted)
120 // STREAM-END
121 //
122 // 2. An explicit document:
123 //
124 // ---
125 // 'a scalar'
126 // ...
127 //
128 // Tokens:
129 //
130 // STREAM-START(utf-8)
131 // DOCUMENT-START
132 // SCALAR("a scalar",single-quoted)
133 // DOCUMENT-END
134 // STREAM-END
135 //
136 // 3. Several documents in a stream:
137 //
138 // 'a scalar'
139 // ---
140 // 'another scalar'
141 // ---
142 // 'yet another scalar'
143 //
144 // Tokens:
145 //
146 // STREAM-START(utf-8)
147 // SCALAR("a scalar",single-quoted)
148 // DOCUMENT-START
149 // SCALAR("another scalar",single-quoted)
150 // DOCUMENT-START
151 // SCALAR("yet another scalar",single-quoted)
152 // STREAM-END
153 //
154 // We have already introduced the SCALAR token above. The following tokens are
155 // used to describe aliases, anchors, tag, and scalars:
156 //
157 // ALIAS(anchor)
158 // ANCHOR(anchor)
159 // TAG(handle,suffix)
160 // SCALAR(value,style)
161 //
162 // The following series of examples illustrate the usage of these tokens:
163 //
164 // 1. A recursive sequence:
165 //
166 // &A [ *A ]
167 //
168 // Tokens:
169 //
170 // STREAM-START(utf-8)
171 // ANCHOR("A")
172 // FLOW-SEQUENCE-START
173 // ALIAS("A")
174 // FLOW-SEQUENCE-END
175 // STREAM-END
176 //
177 // 2. A tagged scalar:
178 //
179 // !!float "3.14" # A good approximation.
180 //
181 // Tokens:
182 //
183 // STREAM-START(utf-8)
184 // TAG("!!","float")
185 // SCALAR("3.14",double-quoted)
186 // STREAM-END
187 //
188 // 3. Various scalar styles:
189 //
190 // --- # Implicit empty plain scalars do not produce tokens.
191 // --- a plain scalar
192 // --- 'a single-quoted scalar'
193 // --- "a double-quoted scalar"
194 // --- |-
195 // a literal scalar
196 // --- >-
197 // a folded
198 // scalar
199 //
200 // Tokens:
201 //
202 // STREAM-START(utf-8)
203 // DOCUMENT-START
204 // DOCUMENT-START
205 // SCALAR("a plain scalar",plain)
206 // DOCUMENT-START
207 // SCALAR("a single-quoted scalar",single-quoted)
208 // DOCUMENT-START
209 // SCALAR("a double-quoted scalar",double-quoted)
210 // DOCUMENT-START
211 // SCALAR("a literal scalar",literal)
212 // DOCUMENT-START
213 // SCALAR("a folded scalar",folded)
214 // STREAM-END
215 //
216 // Now it's time to review collection-related tokens. We will start with
217 // flow collections:
218 //
219 // FLOW-SEQUENCE-START
220 // FLOW-SEQUENCE-END
221 // FLOW-MAPPING-START
222 // FLOW-MAPPING-END
223 // FLOW-ENTRY
224 // KEY
225 // VALUE
226 //
227 // The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and
228 // FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}'
229 // correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the
230 // indicators '?' and ':', which are used for denoting mapping keys and values,
231 // are represented by the KEY and VALUE tokens.
232 //
233 // The following examples show flow collections:
234 //
235 // 1. A flow sequence:
236 //
237 // [item 1, item 2, item 3]
238 //
239 // Tokens:
240 //
241 // STREAM-START(utf-8)
242 // FLOW-SEQUENCE-START
243 // SCALAR("item 1",plain)
244 // FLOW-ENTRY
245 // SCALAR("item 2",plain)
246 // FLOW-ENTRY
247 // SCALAR("item 3",plain)
248 // FLOW-SEQUENCE-END
249 // STREAM-END
250 //
251 // 2. A flow mapping:
252 //
253 // {
254 // a simple key: a value, # Note that the KEY token is produced.
255 // ? a complex key: another value,
256 // }
257 //
258 // Tokens:
259 //
260 // STREAM-START(utf-8)
261 // FLOW-MAPPING-START
262 // KEY
263 // SCALAR("a simple key",plain)
264 // VALUE
265 // SCALAR("a value",plain)
266 // FLOW-ENTRY
267 // KEY
268 // SCALAR("a complex key",plain)
269 // VALUE
270 // SCALAR("another value",plain)
271 // FLOW-ENTRY
272 // FLOW-MAPPING-END
273 // STREAM-END
274 //
275 // A simple key is a key which is not denoted by the '?' indicator. Note that
276 // the Scanner still produce the KEY token whenever it encounters a simple key.
277 //
278 // For scanning block collections, the following tokens are used (note that we
279 // repeat KEY and VALUE here):
280 //
281 // BLOCK-SEQUENCE-START
282 // BLOCK-MAPPING-START
283 // BLOCK-END
284 // BLOCK-ENTRY
285 // KEY
286 // VALUE
287 //
288 // The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation
289 // increase that precedes a block collection (cf. the INDENT token in Python).
290 // The token BLOCK-END denote indentation decrease that ends a block collection
291 // (cf. the DEDENT token in Python). However YAML has some syntax peculiarities
292 // that makes detections of these tokens more complex.
293 //
294 // The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators
295 // '-', '?', and ':' correspondingly.
296 //
297 // The following examples show how the tokens BLOCK-SEQUENCE-START,
298 // BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner:
299 //
300 // 1. Block sequences:
301 //
302 // - item 1
303 // - item 2
304 // -
305 // - item 3.1
306 // - item 3.2
307 // -
308 // key 1: value 1
309 // key 2: value 2
310 //
311 // Tokens:
312 //
313 // STREAM-START(utf-8)
314 // BLOCK-SEQUENCE-START
315 // BLOCK-ENTRY
316 // SCALAR("item 1",plain)
317 // BLOCK-ENTRY
318 // SCALAR("item 2",plain)
319 // BLOCK-ENTRY
320 // BLOCK-SEQUENCE-START
321 // BLOCK-ENTRY
322 // SCALAR("item 3.1",plain)
323 // BLOCK-ENTRY
324 // SCALAR("item 3.2",plain)
325 // BLOCK-END
326 // BLOCK-ENTRY
327 // BLOCK-MAPPING-START
328 // KEY
329 // SCALAR("key 1",plain)
330 // VALUE
331 // SCALAR("value 1",plain)
332 // KEY
333 // SCALAR("key 2",plain)
334 // VALUE
335 // SCALAR("value 2",plain)
336 // BLOCK-END
337 // BLOCK-END
338 // STREAM-END
339 //
340 // 2. Block mappings:
341 //
342 // a simple key: a value # The KEY token is produced here.
343 // ? a complex key
344 // : another value
345 // a mapping:
346 // key 1: value 1
347 // key 2: value 2
348 // a sequence:
349 // - item 1
350 // - item 2
351 //
352 // Tokens:
353 //
354 // STREAM-START(utf-8)
355 // BLOCK-MAPPING-START
356 // KEY
357 // SCALAR("a simple key",plain)
358 // VALUE
359 // SCALAR("a value",plain)
360 // KEY
361 // SCALAR("a complex key",plain)
362 // VALUE
363 // SCALAR("another value",plain)
364 // KEY
365 // SCALAR("a mapping",plain)
366 // BLOCK-MAPPING-START
367 // KEY
368 // SCALAR("key 1",plain)
369 // VALUE
370 // SCALAR("value 1",plain)
371 // KEY
372 // SCALAR("key 2",plain)
373 // VALUE
374 // SCALAR("value 2",plain)
375 // BLOCK-END
376 // KEY
377 // SCALAR("a sequence",plain)
378 // VALUE
379 // BLOCK-SEQUENCE-START
380 // BLOCK-ENTRY
381 // SCALAR("item 1",plain)
382 // BLOCK-ENTRY
383 // SCALAR("item 2",plain)
384 // BLOCK-END
385 // BLOCK-END
386 // STREAM-END
387 //
388 // YAML does not always require to start a new block collection from a new
389 // line. If the current line contains only '-', '?', and ':' indicators, a new
390 // block collection may start at the current line. The following examples
391 // illustrate this case:
392 //
393 // 1. Collections in a sequence:
394 //
395 // - - item 1
396 // - item 2
397 // - key 1: value 1
398 // key 2: value 2
399 // - ? complex key
400 // : complex value
401 //
402 // Tokens:
403 //
404 // STREAM-START(utf-8)
405 // BLOCK-SEQUENCE-START
406 // BLOCK-ENTRY
407 // BLOCK-SEQUENCE-START
408 // BLOCK-ENTRY
409 // SCALAR("item 1",plain)
410 // BLOCK-ENTRY
411 // SCALAR("item 2",plain)
412 // BLOCK-END
413 // BLOCK-ENTRY
414 // BLOCK-MAPPING-START
415 // KEY
416 // SCALAR("key 1",plain)
417 // VALUE
418 // SCALAR("value 1",plain)
419 // KEY
420 // SCALAR("key 2",plain)
421 // VALUE
422 // SCALAR("value 2",plain)
423 // BLOCK-END
424 // BLOCK-ENTRY
425 // BLOCK-MAPPING-START
426 // KEY
427 // SCALAR("complex key")
428 // VALUE
429 // SCALAR("complex value")
430 // BLOCK-END
431 // BLOCK-END
432 // STREAM-END
433 //
434 // 2. Collections in a mapping:
435 //
436 // ? a sequence
437 // : - item 1
438 // - item 2
439 // ? a mapping
440 // : key 1: value 1
441 // key 2: value 2
442 //
443 // Tokens:
444 //
445 // STREAM-START(utf-8)
446 // BLOCK-MAPPING-START
447 // KEY
448 // SCALAR("a sequence",plain)
449 // VALUE
450 // BLOCK-SEQUENCE-START
451 // BLOCK-ENTRY
452 // SCALAR("item 1",plain)
453 // BLOCK-ENTRY
454 // SCALAR("item 2",plain)
455 // BLOCK-END
456 // KEY
457 // SCALAR("a mapping",plain)
458 // VALUE
459 // BLOCK-MAPPING-START
460 // KEY
461 // SCALAR("key 1",plain)
462 // VALUE
463 // SCALAR("value 1",plain)
464 // KEY
465 // SCALAR("key 2",plain)
466 // VALUE
467 // SCALAR("value 2",plain)
468 // BLOCK-END
469 // BLOCK-END
470 // STREAM-END
471 //
472 // YAML also permits non-indented sequences if they are included into a block
473 // mapping. In this case, the token BLOCK-SEQUENCE-START is not produced:
474 //
475 // key:
476 // - item 1 # BLOCK-SEQUENCE-START is NOT produced here.
477 // - item 2
478 //
479 // Tokens:
480 //
481 // STREAM-START(utf-8)
482 // BLOCK-MAPPING-START
483 // KEY
484 // SCALAR("key",plain)
485 // VALUE
486 // BLOCK-ENTRY
487 // SCALAR("item 1",plain)
488 // BLOCK-ENTRY
489 // SCALAR("item 2",plain)
490 // BLOCK-END
491 //
492
493 // Buffer sizes and internal constants
494 const (
495 // The size of the input raw buffer.
496 input_raw_buffer_size = 512
497
498 // The size of the input buffer.
499 // It should be possible to decode the whole raw buffer.
500 input_buffer_size = input_raw_buffer_size * 3
501
502 // The size of the output buffer.
503 output_buffer_size = 128
504
505 // The size of other stacks and queues.
506 initial_stack_size = 16
507 initial_queue_size = 16
508 initial_string_size = 16
509 )
510
511 // Character classification functions
512
513 // Check if the character at the specified position is an alphabetical
514 // character, a digit, '_', or '-'.
515 func isAlpha(b []byte, i int) bool {
516 return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' ||
517 b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-'
518 }
519
520 // Check if the character at the specified position is a flow indicator as
521 // defined by spec production [23] c-flow-indicator ::=
522 // c-collect-entry | c-sequence-start | c-sequence-end |
523 // c-mapping-start | c-mapping-end
524 func isFlowIndicator(b []byte, i int) bool {
525 return b[i] == '[' || b[i] == ']' ||
526 b[i] == '{' || b[i] == '}' || b[i] == ','
527 }
528
529 // Check if the character at the specified position is valid for anchor names
530 // as defined by spec production [102] ns-anchor-char ::= ns-char -
531 // c-flow-indicator.
532 // This includes all printable characters except: CR, LF, BOM, space, tab, '[',
533 // ']', '{', '}', ','.
534 // We further limit it to ascii chars only, which is a subset of the spec
535 // production but is usually what most people expect.
536 func isAnchorChar(b []byte, i int) bool {
537 if isColon(b, i) {
538 // [Go] we exclude colons from anchor/alias names.
539 //
540 // A colon is a valid anchor character according to the YAML 1.2 specification,
541 // but it can lead to ambiguity.
542 // https://github.com/yaml/go-yaml/issues/109
543 //
544 // Also, it would have been a breaking change to support it, as go.yaml.in/yaml/v3 ignores it.
545 // Supporting it could lead to unexpected behavior.
546 return false
547 }
548
549 return isPrintable(b, i) &&
550 !isLineBreak(b, i) &&
551 !isBlank(b, i) &&
552 !isBOM(b, i) &&
553 !isFlowIndicator(b, i) &&
554 isASCII(b, i)
555 }
556
557 // isColon checks whether the character at the specified position is a colon.
558 func isColon(b []byte, i int) bool {
559 return b[i] == ':'
560 }
561
562 // Check if the character at the specified position is valid in a tag URI.
563 //
564 // The set of valid characters is:
565 //
566 // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&',
567 // '=', '+', '$', '.', '!', '~', '*', '\'', '(', ')', '%'.
568 //
569 // If verbatim is true, flow indicators (',', '[', ']', '{', '}') are also
570 // allowed.
571 func isTagURIChar(b []byte, i int, verbatim bool) bool {
572 c := b[i]
573 // isAlpha covers: 0-9, A-Z, a-z, _, -
574 if isAlpha(b, i) {
575 return true
576 }
577 // Check special URI characters
578 switch c {
579 case ';', '/', '?', ':', '@', '&', '=', '+', '$', '.', '!', '~', '*', '\'', '(', ')', '%':
580 return true
581 case ',', '[', ']', '{', '}':
582 return verbatim
583 }
584 return false
585 }
586
587 // Check if the character at the specified position is a digit.
588 func isDigit(b []byte, i int) bool {
589 return b[i] >= '0' && b[i] <= '9'
590 }
591
592 // Get the value of a digit.
593 func asDigit(b []byte, i int) int {
594 return int(b[i]) - '0'
595 }
596
597 // Check if the character at the specified position is a hex-digit.
598 func isHex(b []byte, i int) bool {
599 return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' ||
600 b[i] >= 'a' && b[i] <= 'f'
601 }
602
603 // Get the value of a hex-digit.
604 func asHex(b []byte, i int) int {
605 bi := b[i]
606 if bi >= 'A' && bi <= 'F' {
607 return int(bi) - 'A' + 10
608 }
609 if bi >= 'a' && bi <= 'f' {
610 return int(bi) - 'a' + 10
611 }
612 return int(bi) - '0'
613 }
614
615 // Check if the character is ASCII.
616 func isASCII(b []byte, i int) bool {
617 return b[i] <= 0x7F
618 }
619
620 // Check if the character at the start of the buffer can be printed unescaped.
621 func isPrintable(b []byte, i int) bool {
622 return ((b[i] == 0x0A) || // . == #x0A
623 (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E
624 (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF
625 (b[i] > 0xC2 && b[i] < 0xED) ||
626 (b[i] == 0xED && b[i+1] < 0xA0) ||
627 (b[i] == 0xEE) ||
628 (b[i] == 0xEF && // #xE000 <= . <= #xFFFD
629 !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF
630 !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF))))
631 }
632
633 // Check if the character at the specified position is NUL.
634 func isZeroChar(b []byte, i int) bool {
635 return b[i] == 0x00
636 }
637
638 // Check if the beginning of the buffer is a BOM.
639 func isBOM(b []byte, i int) bool {
640 return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF
641 }
642
643 // Check if the character at the specified position is space.
644 func isSpace(b []byte, i int) bool {
645 return b[i] == ' '
646 }
647
648 // Check if the character at the specified position is tab.
649 func isTab(b []byte, i int) bool {
650 return b[i] == '\t'
651 }
652
653 // Check if the character at the specified position is blank (space or tab).
654 func isBlank(b []byte, i int) bool {
655 // return isSpace(b, i) || isTab(b, i)
656 return b[i] == ' ' || b[i] == '\t'
657 }
658
659 // Check if the character at the specified position is a line break.
660 func isLineBreak(b []byte, i int) bool {
661 return (b[i] == '\r' || // CR (#xD)
662 b[i] == '\n' || // LF (#xA)
663 b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
664 b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
665 b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029)
666 }
667
668 // isCRLF checks if the position contains a CR LF sequence.
669 func isCRLF(b []byte, i int) bool {
670 return b[i] == '\r' && b[i+1] == '\n'
671 }
672
673 // Check if the character is a line break or NUL.
674 func isBreakOrZero(b []byte, i int) bool {
675 // return isLineBreak(b, i) || isZeroChar(b, i)
676 return (
677 // isBreak:
678 b[i] == '\r' || // CR (#xD)
679 b[i] == '\n' || // LF (#xA)
680 b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
681 b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
682 b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029)
683 // isZeroChar:
684 b[i] == 0)
685 }
686
687 // Check if the character is a line break, space, or NUL.
688 func isSpaceOrZero(b []byte, i int) bool {
689 // return isSpace(b, i) || isBreakOrZero(b, i)
690 return (
691 // isSpace:
692 b[i] == ' ' ||
693 // isBreakOrZero:
694 b[i] == '\r' || // CR (#xD)
695 b[i] == '\n' || // LF (#xA)
696 b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
697 b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
698 b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029)
699 b[i] == 0)
700 }
701
702 // Check if the character is a line break, space, tab, or NUL.
703 func isBlankOrZero(b []byte, i int) bool {
704 // return isBlank(b, i) || isBreakOrZero(b, i)
705 return (
706 // isBlank:
707 b[i] == ' ' || b[i] == '\t' ||
708 // isBreakOrZero:
709 b[i] == '\r' || // CR (#xD)
710 b[i] == '\n' || // LF (#xA)
711 b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
712 b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
713 b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029)
714 b[i] == 0)
715 }
716
717 func isEndOfScalarInFlowContentChar(b []byte, i int) bool {
718 switch b[i] {
719 // ",", "[", "]", "{" and "}"
720 case ',', '[', ']', '{', '}':
721 return true
722 // "? "
723 case '?':
724 return isBlankOrZero(b, i+1)
725 // ": ", ":,", ":]" and ":}"
726 case ':':
727 return b[i+1] == ' ' || b[i+1] == ',' ||
728 b[i+1] == ']' || b[i+1] == '}'
729 default:
730 return false
731 }
732 }
733
734 // Determine the width of the character.
735 func width(b byte) int {
736 // Don't replace these by a switch without first
737 // confirming that it is being inlined.
738 if b&0x80 == 0x00 {
739 return 1
740 }
741 if b&0xE0 == 0xC0 {
742 return 2
743 }
744 if b&0xF0 == 0xE0 {
745 return 3
746 }
747 if b&0xF8 == 0xF0 {
748 return 4
749 }
750 return 0
751 }
752
753 // Scan advances the buffer pointer and reads the next token.
754 func (parser *Parser) Scan(token *Token) error {
755 // Erase the token object.
756 *token = Token{} // [Go] Is this necessary?
757
758 if parser.lastError != nil {
759 return parser.lastError
760 }
761
762 // No tokens after STREAM-END or error.
763 if parser.stream_end_produced {
764 return io.EOF
765 }
766
767 // Ensure that the tokens queue contains enough tokens.
768 if !parser.token_available {
769 if err := parser.fetchMoreTokens(); err != nil {
770 parser.lastError = err
771 return err
772 }
773 }
774
775 // Fetch the next token from the queue.
776 *token = parser.tokens[parser.tokens_head]
777 parser.tokens_head++
778 parser.tokens_parsed++
779 parser.token_available = false
780
781 if token.Type == STREAM_END_TOKEN {
782 parser.stream_end_produced = true
783 }
784 return nil
785 }
786
787 // formatScannerError creates a ScannerError with the given problem message
788 // and mark position.
789
790 // max_number_length is the maximum length of a number suffix in a scalar tag.
791 const max_number_length = 2
792
793 // fetchMoreTokens ensures the token queue has at least one token for lookahead.
794 func (parser *Parser) fetchMoreTokens() error {
795 // While we need more tokens to fetch, do it.
796 for {
797 // [Go] The comment parsing logic requires a lookahead of two tokens
798 // so that foot comments may be parsed in time of associating them
799 // with the tokens that are parsed before them, and also for line
800 // comments to be transformed into head comments in some edge cases.
801 if parser.tokens_head < len(parser.tokens)-2 {
802 // If a potential simple key is at the head position, we need to fetch
803 // the next token to disambiguate it.
804
805 var first_key int
806 found_potential_key := false
807
808 if len(parser.simple_key_stack) > 0 {
809 // Found a simple key on the stack
810 first_key = parser.simple_key_stack[0].token_number
811 found_potential_key = true
812 } else if parser.simple_key_possible {
813 // Found a 'current' simple key (which was not pushed to the stack yet)
814 first_key = parser.simple_key.token_number
815 found_potential_key = true
816 }
817
818 if !found_potential_key {
819 // We don't have any potential simple keys
820 break
821 } else if parser.tokens_parsed != first_key {
822 // We have not reached the potential simple key yet.
823 break
824 }
825 }
826 // Fetch the next token.
827 if err := parser.fetchNextToken(); err != nil {
828 return err
829 }
830 }
831
832 parser.token_available = true
833 return nil
834 }
835
836 // The dispatcher for token fetchers.
837 func (parser *Parser) fetchNextToken() (err error) {
838 // Ensure that the buffer is initialized.
839 if parser.unread < 1 {
840 if err := parser.updateBuffer(1); err != nil {
841 return err
842 }
843 }
844
845 // Check if we just started scanning. Fetch STREAM-START then.
846 if !parser.stream_start_produced {
847 return parser.fetchStreamStart()
848 }
849
850 scan_mark := parser.mark
851
852 // Eat whitespaces and comments until we reach the next token.
853 if err := parser.scanToNextToken(); err != nil {
854 return err
855 }
856
857 // [Go] While unrolling indents, transform the head comments of prior
858 // indentation levels observed after scan_start into foot comments at
859 // the respective indexes.
860
861 // Check the indentation level against the current column.
862 if err := parser.unrollIndent(parser.mark.Column, scan_mark); err != nil {
863 return err
864 }
865
866 // Ensure that the buffer contains at least 4 characters. 4 is the length
867 // of the longest indicators ('--- ' and '... ').
868 if parser.unread < 4 {
869 if err := parser.updateBuffer(4); err != nil {
870 return err
871 }
872 }
873
874 // Is it the end of the stream?
875 if isZeroChar(parser.buffer, parser.buffer_pos) {
876 return parser.fetchStreamEnd()
877 }
878
879 // Is it a directive?
880 if parser.mark.Column == 1 && parser.buffer[parser.buffer_pos] == '%' {
881 return parser.fetchDirective()
882 }
883
884 buf := parser.buffer
885 pos := parser.buffer_pos
886
887 // Is it the document start indicator?
888 if parser.mark.Column == 1 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && isBlankOrZero(buf, pos+3) {
889 return parser.fetchDocumentIndicator(DOCUMENT_START_TOKEN)
890 }
891
892 // Is it the document end indicator?
893 if parser.mark.Column == 1 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && isBlankOrZero(buf, pos+3) {
894 return parser.fetchDocumentIndicator(DOCUMENT_END_TOKEN)
895 }
896
897 comment_mark := parser.mark
898 if len(parser.tokens) > 0 && (parser.flow_level == 0 && buf[pos] == ':' || parser.flow_level > 0 && buf[pos] == ',') {
899 // Associate any following comments with the prior token.
900 comment_mark = parser.tokens[len(parser.tokens)-1].StartMark
901 }
902 defer func() {
903 if err != nil {
904 return
905 }
906 if parser.skip_comments {
907 return
908 }
909 if len(parser.tokens) > 0 && parser.tokens[len(parser.tokens)-1].Type == BLOCK_ENTRY_TOKEN {
910 // Sequence indicators alone have no line comments. It becomes
911 // a head comment for whatever follows.
912 return
913 }
914 err = parser.scanLineComment(comment_mark)
915 }()
916
917 // Is it the flow sequence start indicator?
918 if buf[pos] == '[' {
919 return parser.fetchFlowCollectionStart(FLOW_SEQUENCE_START_TOKEN)
920 }
921
922 // Is it the flow mapping start indicator?
923 if parser.buffer[parser.buffer_pos] == '{' {
924 return parser.fetchFlowCollectionStart(FLOW_MAPPING_START_TOKEN)
925 }
926
927 // Is it the flow sequence end indicator?
928 if parser.buffer[parser.buffer_pos] == ']' {
929 return parser.fetchFlowCollectionEnd(
930 FLOW_SEQUENCE_END_TOKEN)
931 }
932
933 // Is it the flow mapping end indicator?
934 if parser.buffer[parser.buffer_pos] == '}' {
935 return parser.fetchFlowCollectionEnd(
936 FLOW_MAPPING_END_TOKEN)
937 }
938
939 // Is it the flow entry indicator?
940 if parser.buffer[parser.buffer_pos] == ',' {
941 return parser.fetchFlowEntry()
942 }
943
944 // Is it the block entry indicator?
945 if parser.buffer[parser.buffer_pos] == '-' && isBlankOrZero(parser.buffer, parser.buffer_pos+1) {
946 return parser.fetchBlockEntry()
947 }
948
949 // Is it the key indicator?
950 if parser.buffer[parser.buffer_pos] == '?' && isBlankOrZero(parser.buffer, parser.buffer_pos+1) {
951 return parser.fetchKey()
952 }
953
954 // Is it the value indicator?
955 if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 &&
956 !parser.isFlowSequence() || isBlankOrZero(parser.buffer, parser.buffer_pos+1)) {
957 return parser.fetchValue()
958 }
959
960 // Is it an alias?
961 if parser.buffer[parser.buffer_pos] == '*' {
962 return parser.fetchAnchor(ALIAS_TOKEN)
963 }
964
965 // Is it an anchor?
966 if parser.buffer[parser.buffer_pos] == '&' {
967 return parser.fetchAnchor(ANCHOR_TOKEN)
968 }
969
970 // Is it a tag?
971 if parser.buffer[parser.buffer_pos] == '!' {
972 return parser.fetchTag()
973 }
974
975 // Is it a literal scalar?
976 if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 {
977 return parser.fetchBlockScalar(true)
978 }
979
980 // Is it a folded scalar?
981 if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 {
982 return parser.fetchBlockScalar(false)
983 }
984
985 // Is it a single-quoted scalar?
986 if parser.buffer[parser.buffer_pos] == '\'' {
987 return parser.fetchFlowScalar(true)
988 }
989
990 // Is it a double-quoted scalar?
991 if parser.buffer[parser.buffer_pos] == '"' {
992 return parser.fetchFlowScalar(false)
993 }
994
995 // Is it a plain scalar?
996 //
997 // A plain scalar may start with any non-blank characters except
998 //
999 // '-', '?', ':', ',', '[', ']', '{', '}',
1000 // '#', '&', '*', '!', '|', '>', '\'', '\"',
1001 // '%', '@', '`'.
1002 //
1003 // In the block context (and, for the '-' indicator, in the flow context
1004 // too), it may also start with the characters
1005 //
1006 // '-', '?', ':'
1007 //
1008 // if it is followed by a non-space character.
1009 //
1010 // The last rule is more restrictive than the specification requires.
1011 // [Go] TODO Make this logic more reasonable.
1012 //switch parser.buffer[parser.buffer_pos] {
1013 //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`':
1014 //}
1015 if !(isBlankOrZero(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' ||
1016 parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' ||
1017 parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' ||
1018 parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' ||
1019 parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' ||
1020 parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' ||
1021 parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' ||
1022 parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' ||
1023 parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' ||
1024 parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') ||
1025 (parser.buffer[parser.buffer_pos] == '-' && !isBlank(parser.buffer, parser.buffer_pos+1)) ||
1026 ((parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') &&
1027 !isBlankOrZero(parser.buffer, parser.buffer_pos+1)) {
1028 return parser.fetchPlainScalar()
1029 }
1030
1031 // If we don't determine the token type so far, it is an error.
1032 return formatScannerErrorContext(
1033 "while scanning for the next token", parser.mark,
1034 "found character that cannot start any token", parser.mark)
1035 }
1036
1037 // isFlowSequence checks if the previous token indicates we're in a flow
1038 // sequence context.
1039 func (parser *Parser) fetchAnchor(typ TokenType) error {
1040 // An anchor or an alias could be a simple key.
1041 if err := parser.saveSimpleKey(); err != nil {
1042 return err
1043 }
1044
1045 // A simple key cannot follow an anchor or an alias.
1046 parser.simple_key_allowed = false
1047
1048 // Create the ALIAS or ANCHOR token and append it to the queue.
1049 var token Token
1050 if err := parser.scanAnchor(&token, typ); err != nil {
1051 return err
1052 }
1053 parser.insertToken(-1, &token)
1054 return nil
1055 }
1056
1057 // Produce the TAG token.
1058 func (parser *Parser) fetchBlockEntry() error {
1059 // Check if the scanner is in the block context.
1060 if parser.flow_level == 0 {
1061 // Check if we are allowed to start a new entry.
1062 if !parser.simple_key_allowed {
1063 return formatScannerError("block sequence entries are not allowed in this context", parser.mark)
1064 }
1065 // Add the BLOCK-SEQUENCE-START token if needed.
1066 if err := parser.rollIndent(parser.mark.Column, -1, BLOCK_SEQUENCE_START_TOKEN, parser.mark); err != nil {
1067 return err
1068 }
1069 } else { //nolint:staticcheck // there is no problem with this empty branch as it's documentation.
1070
1071 // It is an error for the '-' indicator to occur in the flow context,
1072 // but we let the Parser detect and report about it because the Parser
1073 // is able to point to the context.
1074 }
1075
1076 // Reset any potential simple keys on the current flow level.
1077 if err := parser.removeSimpleKey(); err != nil {
1078 return err
1079 }
1080
1081 // Simple keys are allowed after '-'.
1082 parser.simple_key_allowed = true
1083
1084 // Consume the token.
1085 start_mark := parser.mark
1086 parser.skip()
1087 end_mark := parser.mark
1088
1089 // Create the BLOCK-ENTRY token and append it to the queue.
1090 token := Token{
1091 Type: BLOCK_ENTRY_TOKEN,
1092 StartMark: start_mark,
1093 EndMark: end_mark,
1094 }
1095 parser.insertToken(-1, &token)
1096 return nil
1097 }
1098
1099 // Produce the KEY token.
1100 func (parser *Parser) fetchBlockScalar(literal bool) error {
1101 // Remove any potential simple keys.
1102 if err := parser.removeSimpleKey(); err != nil {
1103 return err
1104 }
1105
1106 // A simple key may follow a block scalar.
1107 parser.simple_key_allowed = true
1108
1109 // Create the SCALAR token and append it to the queue.
1110 var token Token
1111 if err := parser.scanBlockScalar(&token, literal); err != nil {
1112 return err
1113 }
1114 parser.insertToken(-1, &token)
1115 return nil
1116 }
1117
1118 // Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens.
1119 func (parser *Parser) fetchDirective() error {
1120 // Reset the indentation level.
1121 if err := parser.unrollIndent(-1, parser.mark); err != nil {
1122 return err
1123 }
1124
1125 // Reset simple keys.
1126 if err := parser.removeSimpleKey(); err != nil {
1127 return err
1128 }
1129
1130 parser.simple_key_allowed = false
1131
1132 // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token.
1133 token := Token{}
1134 if err := parser.scanDirective(&token); err != nil {
1135 return err
1136 }
1137 // Append the token to the queue.
1138 parser.insertToken(-1, &token)
1139 return nil
1140 }
1141
1142 // Produce the DOCUMENT-START or DOCUMENT-END token.
1143 func (parser *Parser) fetchDocumentIndicator(typ TokenType) error {
1144 // Reset the indentation level.
1145 if err := parser.unrollIndent(-1, parser.mark); err != nil {
1146 return err
1147 }
1148
1149 // Reset simple keys.
1150 if err := parser.removeSimpleKey(); err != nil {
1151 return err
1152 }
1153
1154 parser.simple_key_allowed = false
1155
1156 // Consume the token.
1157 start_mark := parser.mark
1158
1159 parser.skip()
1160 parser.skip()
1161 parser.skip()
1162
1163 end_mark := parser.mark
1164
1165 // Create the DOCUMENT-START or DOCUMENT-END token.
1166 token := Token{
1167 Type: typ,
1168 StartMark: start_mark,
1169 EndMark: end_mark,
1170 }
1171 // Append the token to the queue.
1172 parser.insertToken(-1, &token)
1173 return nil
1174 }
1175
1176 // Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token.
1177 func (parser *Parser) fetchFlowCollectionEnd(typ TokenType) error {
1178 // Reset any potential simple key on the current flow level.
1179 if err := parser.removeSimpleKey(); err != nil {
1180 return err
1181 }
1182
1183 // Decrease the flow level.
1184 if err := parser.decreaseFlowLevel(); err != nil {
1185 return err
1186 }
1187
1188 // No simple keys after the indicators ']' and '}'.
1189 parser.simple_key_allowed = false
1190
1191 // Consume the token.
1192
1193 start_mark := parser.mark
1194 parser.skip()
1195 end_mark := parser.mark
1196
1197 // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token.
1198 token := Token{
1199 Type: typ,
1200 StartMark: start_mark,
1201 EndMark: end_mark,
1202 }
1203 // Append the token to the queue.
1204 parser.insertToken(-1, &token)
1205 return nil
1206 }
1207
1208 // Produce the FLOW-ENTRY token.
1209 func (parser *Parser) fetchFlowCollectionStart(typ TokenType) error {
1210 // The indicators '[' and '{' may start a simple key.
1211 if err := parser.saveSimpleKey(); err != nil {
1212 return err
1213 }
1214
1215 // Increase the flow level.
1216 if err := parser.increaseFlowLevel(); err != nil {
1217 return err
1218 }
1219
1220 // A simple key may follow the indicators '[' and '{'.
1221 parser.simple_key_allowed = true
1222
1223 // Consume the token.
1224 start_mark := parser.mark
1225 parser.skip()
1226 end_mark := parser.mark
1227
1228 // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token.
1229 token := Token{
1230 Type: typ,
1231 StartMark: start_mark,
1232 EndMark: end_mark,
1233 }
1234 // Append the token to the queue.
1235 parser.insertToken(-1, &token)
1236 return nil
1237 }
1238
1239 // Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token.
1240 func (parser *Parser) fetchFlowEntry() error {
1241 // Reset any potential simple keys on the current flow level.
1242 if err := parser.removeSimpleKey(); err != nil {
1243 return err
1244 }
1245
1246 // Simple keys are allowed after ','.
1247 parser.simple_key_allowed = true
1248
1249 // Consume the token.
1250 start_mark := parser.mark
1251 parser.skip()
1252 end_mark := parser.mark
1253
1254 // Create the FLOW-ENTRY token and append it to the queue.
1255 token := Token{
1256 Type: FLOW_ENTRY_TOKEN,
1257 StartMark: start_mark,
1258 EndMark: end_mark,
1259 }
1260 parser.insertToken(-1, &token)
1261 return nil
1262 }
1263
1264 // Produce the BLOCK-ENTRY token.
1265 func (parser *Parser) fetchFlowScalar(single bool) error {
1266 // A plain scalar could be a simple key.
1267 if err := parser.saveSimpleKey(); err != nil {
1268 return err
1269 }
1270
1271 // A simple key cannot follow a flow scalar.
1272 parser.simple_key_allowed = false
1273
1274 // Create the SCALAR token and append it to the queue.
1275 var token Token
1276 if err := parser.scanFlowScalar(&token, single); err != nil {
1277 return err
1278 }
1279 parser.insertToken(-1, &token)
1280 return nil
1281 }
1282
1283 // Produce the SCALAR(...,plain) token.
1284 func (parser *Parser) fetchKey() error {
1285 // In the block context, additional checks are required.
1286 if parser.flow_level == 0 {
1287 // Check if we are allowed to start a new key (not necessary simple).
1288 if !parser.simple_key_allowed {
1289 return formatScannerError("mapping keys are not allowed in this context", parser.mark)
1290 }
1291 // Add the BLOCK-MAPPING-START token if needed.
1292 if err := parser.rollIndent(parser.mark.Column, -1, BLOCK_MAPPING_START_TOKEN, parser.mark); err != nil {
1293 return err
1294 }
1295 }
1296
1297 // Reset any potential simple keys on the current flow level.
1298 if err := parser.removeSimpleKey(); err != nil {
1299 return err
1300 }
1301
1302 // Simple keys are allowed after '?' in the block context.
1303 parser.simple_key_allowed = parser.flow_level == 0
1304
1305 // Consume the token.
1306 start_mark := parser.mark
1307 parser.skip()
1308 end_mark := parser.mark
1309
1310 // Create the KEY token and append it to the queue.
1311 token := Token{
1312 Type: KEY_TOKEN,
1313 StartMark: start_mark,
1314 EndMark: end_mark,
1315 }
1316 parser.insertToken(-1, &token)
1317 return nil
1318 }
1319
1320 // Produce the VALUE token.
1321 func (parser *Parser) fetchPlainScalar() error {
1322 // A plain scalar could be a simple key.
1323 if err := parser.saveSimpleKey(); err != nil {
1324 return err
1325 }
1326
1327 // A simple key cannot follow a flow scalar.
1328 parser.simple_key_allowed = false
1329
1330 // Create the SCALAR token and append it to the queue.
1331 var token Token
1332 if err := parser.scanPlainScalar(&token); err != nil {
1333 return err
1334 }
1335 parser.insertToken(-1, &token)
1336 return nil
1337 }
1338
1339 // Eat whitespaces and comments until the next token is found.
1340 func (parser *Parser) fetchStreamEnd() error {
1341 // Force new line.
1342 if parser.mark.Column != 1 {
1343 parser.mark.Column = 1
1344 parser.mark.Line++
1345 }
1346
1347 // Reset the indentation level.
1348 if err := parser.unrollIndent(-1, parser.mark); err != nil {
1349 return err
1350 }
1351
1352 // Reset simple keys.
1353 if err := parser.removeSimpleKey(); err != nil {
1354 return err
1355 }
1356 parser.simple_key = SimpleKey{}
1357 parser.simple_key_stack = []SimpleKey{}
1358 parser.simple_key_allowed = false
1359
1360 // Create the STREAM-END token and append it to the queue.
1361 token := Token{
1362 Type: STREAM_END_TOKEN,
1363 StartMark: parser.mark,
1364 EndMark: parser.mark,
1365 }
1366 parser.insertToken(-1, &token)
1367 return nil
1368 }
1369
1370 // Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token.
1371 func (parser *Parser) fetchStreamStart() error {
1372 // Set the initial indentation.
1373 parser.indent = -1
1374
1375 // Initialize the simple key stack.
1376 parser.simple_key = SimpleKey{}
1377 parser.simple_key_stack = []SimpleKey{}
1378
1379 // A simple key is allowed at the beginning of the stream.
1380 parser.simple_key_allowed = true
1381
1382 // We have started.
1383 parser.stream_start_produced = true
1384
1385 // Create the STREAM-START token and append it to the queue.
1386 token := Token{
1387 Type: STREAM_START_TOKEN,
1388 StartMark: parser.mark,
1389 EndMark: parser.mark,
1390 encoding: parser.encoding,
1391 }
1392 parser.insertToken(-1, &token)
1393 return nil
1394 }
1395
1396 // Produce the STREAM-END token and shut down the scanner.
1397 func (parser *Parser) fetchTag() error {
1398 // A tag could be a simple key.
1399 if err := parser.saveSimpleKey(); err != nil {
1400 return err
1401 }
1402
1403 // A simple key cannot follow a tag.
1404 parser.simple_key_allowed = false
1405
1406 // Create the TAG token and append it to the queue.
1407 var token Token
1408 if err := parser.scanTag(&token); err != nil {
1409 return err
1410 }
1411 parser.insertToken(-1, &token)
1412 return nil
1413 }
1414
1415 // Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens.
1416 func (parser *Parser) fetchValue() error {
1417 simple_key := &parser.simple_key
1418
1419 // Have we found a simple key?
1420 if parser.simple_key_possible && simple_key.mark.Line == parser.mark.Line {
1421 // Create the KEY token and insert it into the queue.
1422 token := Token{
1423 Type: KEY_TOKEN,
1424 StartMark: simple_key.mark,
1425 EndMark: simple_key.mark,
1426 }
1427 parser.insertToken(simple_key.token_number-parser.tokens_parsed, &token)
1428
1429 // In the block context, we may need to add the BLOCK-MAPPING-START token.
1430 if err := parser.rollIndent(simple_key.mark.Column,
1431 simple_key.token_number,
1432 BLOCK_MAPPING_START_TOKEN, simple_key.mark); err != nil {
1433 return err
1434 }
1435
1436 // Remove the simple key.
1437 parser.simple_key_possible = false
1438 simple_key.required = false
1439
1440 // A simple key cannot follow another simple key.
1441 parser.simple_key_allowed = false
1442
1443 } else {
1444 // The ':' indicator follows a complex key.
1445
1446 // In the block context, extra checks are required.
1447 if parser.flow_level == 0 {
1448
1449 // Check if we are allowed to start a complex value.
1450 if !parser.simple_key_allowed {
1451 return formatScannerError("mapping values are not allowed in this context", parser.mark)
1452 }
1453
1454 // Add the BLOCK-MAPPING-START token if needed.
1455 if err := parser.rollIndent(parser.mark.Column, -1, BLOCK_MAPPING_START_TOKEN, parser.mark); err != nil {
1456 return err
1457 }
1458 }
1459
1460 // Simple keys after ':' are allowed in the block context.
1461 parser.simple_key_allowed = parser.flow_level == 0
1462 }
1463
1464 // Consume the token.
1465 start_mark := parser.mark
1466 parser.skip()
1467 end_mark := parser.mark
1468
1469 // Create the VALUE token and append it to the queue.
1470 token := Token{
1471 Type: VALUE_TOKEN,
1472 StartMark: start_mark,
1473 EndMark: end_mark,
1474 }
1475 parser.insertToken(-1, &token)
1476 return nil
1477 }
1478
1479 // Produce the ALIAS or ANCHOR token.
1480 func (parser *Parser) scanAnchor(token *Token, typ TokenType) error {
1481 var s []byte
1482
1483 // Eat the indicator character.
1484 start_mark := parser.mark
1485 parser.skip()
1486
1487 // Consume the value.
1488 if parser.unread < 1 {
1489 if err := parser.updateBuffer(1); err != nil {
1490 return err
1491 }
1492 }
1493
1494 for isAnchorChar(parser.buffer, parser.buffer_pos) {
1495 s = parser.read(s)
1496 if parser.unread < 1 {
1497 if err := parser.updateBuffer(1); err != nil {
1498 return err
1499 }
1500 }
1501 }
1502
1503 end_mark := parser.mark
1504
1505 /*
1506 * Check if length of the anchor is greater than 0 and it is followed by
1507 * a whitespace character or one of the indicators:
1508 *
1509 * '?', ':', ',', ']', '}', '%', '@', '`'.
1510 */
1511
1512 if len(s) == 0 ||
1513 !(isBlankOrZero(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' ||
1514 parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' ||
1515 parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' ||
1516 parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' ||
1517 parser.buffer[parser.buffer_pos] == '`') {
1518 context := "while scanning an alias"
1519 if typ == ANCHOR_TOKEN {
1520 context = "while scanning an anchor"
1521 }
1522 return formatScannerErrorContext(context, start_mark,
1523 "did not find expected alphabetic or numeric character", parser.mark)
1524 }
1525
1526 // Create a token.
1527 *token = Token{
1528 Type: typ,
1529 StartMark: start_mark,
1530 EndMark: end_mark,
1531 Value: s,
1532 }
1533
1534 return nil
1535 }
1536
1537 // scanTag scans a TAG token.
1538 func (parser *Parser) scanBlockScalar(token *Token, literal bool) error {
1539 // Eat the indicator '|' or '>'.
1540 start_mark := parser.mark
1541 parser.skip()
1542
1543 // Scan the additional block scalar indicators.
1544 if parser.unread < 1 {
1545 if err := parser.updateBuffer(1); err != nil {
1546 return err
1547 }
1548 }
1549
1550 // Check for a chomping indicator.
1551 var chomping, increment int
1552 if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' {
1553 // Set the chomping method and eat the indicator.
1554 if parser.buffer[parser.buffer_pos] == '+' {
1555 chomping = +1
1556 } else {
1557 chomping = -1
1558 }
1559 parser.skip()
1560
1561 // Check for an indentation indicator.
1562 if parser.unread < 1 {
1563 if err := parser.updateBuffer(1); err != nil {
1564 return err
1565 }
1566 }
1567 if isDigit(parser.buffer, parser.buffer_pos) {
1568 // Check that the indentation is greater than 0.
1569 if parser.buffer[parser.buffer_pos] == '0' {
1570 return formatScannerErrorContext("while scanning a block scalar", start_mark,
1571 "found an indentation indicator equal to 0", parser.mark)
1572 }
1573
1574 // Get the indentation level and eat the indicator.
1575 increment = asDigit(parser.buffer, parser.buffer_pos)
1576 parser.skip()
1577 }
1578
1579 } else if isDigit(parser.buffer, parser.buffer_pos) {
1580 // Do the same as above, but in the opposite order.
1581
1582 if parser.buffer[parser.buffer_pos] == '0' {
1583 return formatScannerErrorContext("while scanning a block scalar", start_mark,
1584 "found an indentation indicator equal to 0", parser.mark)
1585 }
1586 increment = asDigit(parser.buffer, parser.buffer_pos)
1587 parser.skip()
1588
1589 if parser.unread < 1 {
1590 if err := parser.updateBuffer(1); err != nil {
1591 return err
1592 }
1593 }
1594 if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' {
1595 if parser.buffer[parser.buffer_pos] == '+' {
1596 chomping = +1
1597 } else {
1598 chomping = -1
1599 }
1600 parser.skip()
1601 }
1602 }
1603
1604 // Eat whitespaces and comments to the end of the line.
1605 if parser.unread < 1 {
1606 if err := parser.updateBuffer(1); err != nil {
1607 return err
1608 }
1609 }
1610 for isBlank(parser.buffer, parser.buffer_pos) {
1611 parser.skip()
1612 if parser.unread < 1 {
1613 if err := parser.updateBuffer(1); err != nil {
1614 return err
1615 }
1616 }
1617 }
1618 if parser.buffer[parser.buffer_pos] == '#' {
1619 if err := parser.scanLineComment(start_mark); err != nil {
1620 return err
1621 }
1622 for !isBreakOrZero(parser.buffer, parser.buffer_pos) {
1623 parser.skip()
1624 if parser.unread < 1 {
1625 if err := parser.updateBuffer(1); err != nil {
1626 return err
1627 }
1628 }
1629 }
1630 }
1631
1632 // Check if we are at the end of the line.
1633 if !isBreakOrZero(parser.buffer, parser.buffer_pos) {
1634 return formatScannerErrorContext("while scanning a block scalar", start_mark,
1635 "did not find expected comment or line break", parser.mark)
1636 }
1637
1638 // Eat a line break.
1639 if isLineBreak(parser.buffer, parser.buffer_pos) {
1640 if parser.unread < 2 {
1641 if err := parser.updateBuffer(2); err != nil {
1642 return err
1643 }
1644 }
1645 parser.skipLine()
1646 }
1647
1648 end_mark := parser.mark
1649
1650 // Set the indentation level if it was specified.
1651 var indent int
1652 if increment > 0 {
1653 if parser.indent >= 0 {
1654 indent = parser.indent + increment
1655 } else {
1656 // With 1-based columns, the line start is column 1, so an
1657 // explicit indent indicator of n means column n+1.
1658 indent = increment + 1
1659 }
1660 }
1661
1662 // Scan the leading line breaks and determine the indentation level if
1663 // needed.
1664 var s, leading_break, trailing_breaks []byte
1665 if err := parser.scanBlockScalarBreaks(&indent, &trailing_breaks, start_mark, &end_mark); err != nil {
1666 return err
1667 }
1668
1669 // Scan the block scalar content.
1670 if parser.unread < 1 {
1671 if err := parser.updateBuffer(1); err != nil {
1672 return err
1673 }
1674 }
1675 var leading_blank, trailing_blank bool
1676 for parser.mark.Column == indent && !isZeroChar(parser.buffer, parser.buffer_pos) {
1677 // We are at the beginning of a non-empty line.
1678
1679 // Is it a trailing whitespace?
1680 trailing_blank = isBlank(parser.buffer, parser.buffer_pos)
1681
1682 // Check if we need to fold the leading line break.
1683 if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' {
1684 // Do we need to join the lines by space?
1685 if len(trailing_breaks) == 0 {
1686 s = append(s, ' ')
1687 }
1688 } else {
1689 s = append(s, leading_break...)
1690 }
1691 leading_break = leading_break[:0]
1692
1693 // Append the remaining line breaks.
1694 s = append(s, trailing_breaks...)
1695 trailing_breaks = trailing_breaks[:0]
1696
1697 // Is it a leading whitespace?
1698 leading_blank = isBlank(parser.buffer, parser.buffer_pos)
1699
1700 // Consume the current line.
1701 for !isBreakOrZero(parser.buffer, parser.buffer_pos) {
1702 s = parser.read(s)
1703 if parser.unread < 1 {
1704 if err := parser.updateBuffer(1); err != nil {
1705 return err
1706 }
1707 }
1708 }
1709
1710 // Consume the line break.
1711 if parser.unread < 2 {
1712 if err := parser.updateBuffer(2); err != nil {
1713 return err
1714 }
1715 }
1716
1717 leading_break = parser.readLine(leading_break)
1718
1719 // Eat the following indentation spaces and line breaks.
1720 if err := parser.scanBlockScalarBreaks(&indent, &trailing_breaks, start_mark, &end_mark); err != nil {
1721 return err
1722 }
1723 }
1724
1725 // Chomp the tail.
1726 if chomping != -1 {
1727 s = append(s, leading_break...)
1728 }
1729 if chomping == 1 {
1730 s = append(s, trailing_breaks...)
1731 }
1732
1733 // Create a token.
1734 *token = Token{
1735 Type: SCALAR_TOKEN,
1736 StartMark: start_mark,
1737 EndMark: end_mark,
1738 Value: s,
1739 Style: LITERAL_SCALAR_STYLE,
1740 }
1741 if !literal {
1742 token.Style = FOLDED_SCALAR_STYLE
1743 }
1744 return nil
1745 }
1746
1747 // Scan indentation spaces and line breaks for a block scalar.
1748 // Determine the indentation level if needed.
1749 func (parser *Parser) scanBlockScalarBreaks(indent *int, breaks *[]byte, start_mark Mark, end_mark *Mark) error {
1750 *end_mark = parser.mark
1751
1752 // Eat the indentation spaces and line breaks.
1753 max_indent := 0
1754 for {
1755 // Eat the indentation spaces.
1756 if parser.unread < 1 {
1757 if err := parser.updateBuffer(1); err != nil {
1758 return err
1759 }
1760 }
1761 for (*indent == 0 || parser.mark.Column < *indent) && isSpace(parser.buffer, parser.buffer_pos) {
1762 parser.skip()
1763 if parser.unread < 1 {
1764 if err := parser.updateBuffer(1); err != nil {
1765 return err
1766 }
1767 }
1768 }
1769 if parser.mark.Column > max_indent {
1770 max_indent = parser.mark.Column
1771 }
1772
1773 // Check for a tab character messing the indentation.
1774 if (*indent == 0 || parser.mark.Column < *indent) && isTab(parser.buffer, parser.buffer_pos) {
1775 return formatScannerErrorContext("while scanning a block scalar", start_mark,
1776 "found a tab character where an indentation space is expected", parser.mark)
1777 }
1778
1779 // Have we found a non-empty line?
1780 if !isLineBreak(parser.buffer, parser.buffer_pos) {
1781 break
1782 }
1783
1784 // Consume the line break.
1785 if parser.unread < 2 {
1786 if err := parser.updateBuffer(2); err != nil {
1787 return err
1788 }
1789 }
1790 // [Go] Should really be returning breaks instead.
1791 *breaks = parser.readLine(*breaks)
1792 *end_mark = parser.mark
1793 }
1794
1795 // Determine the indentation level if needed.
1796 if *indent == 0 {
1797 *indent = max_indent
1798 if *indent < parser.indent+1 {
1799 *indent = parser.indent + 1
1800 }
1801 if *indent < 1 {
1802 *indent = 1
1803 }
1804 }
1805 return nil
1806 }
1807
1808 // Scan a quoted scalar.
1809 func (parser *Parser) scanComments(scan_mark Mark) error {
1810 token := parser.tokens[len(parser.tokens)-1]
1811
1812 if token.Type == FLOW_ENTRY_TOKEN && len(parser.tokens) > 1 {
1813 token = parser.tokens[len(parser.tokens)-2]
1814 }
1815
1816 token_mark := token.StartMark
1817 var start_mark Mark
1818 next_indent := parser.indent
1819 if next_indent < 0 {
1820 next_indent = 0
1821 }
1822
1823 recent_empty := false
1824 first_empty := parser.newlines <= 1
1825
1826 line := parser.mark.Line
1827 column := parser.mark.Column
1828
1829 var text []byte
1830
1831 // The foot line is the place where a comment must start to
1832 // still be considered as a foot of the prior content.
1833 // If there's some content in the currently parsed line, then
1834 // the foot is the line below it.
1835 foot_line := -1
1836 if scan_mark.Line > 0 {
1837 foot_line = parser.mark.Line - parser.newlines + 1
1838 if parser.newlines == 0 && parser.mark.Column > 1 {
1839 foot_line++
1840 }
1841 }
1842
1843 peek := 0
1844 for ; peek < 512; peek++ {
1845 if parser.unread < peek+1 {
1846 if parser.updateBuffer(peek+1) != nil {
1847 break
1848 }
1849 }
1850 column++
1851 if isBlank(parser.buffer, parser.buffer_pos+peek) {
1852 continue
1853 }
1854 c := parser.buffer[parser.buffer_pos+peek]
1855 close_flow := parser.flow_level > 0 && (c == ']' || c == '}')
1856 if close_flow || isBreakOrZero(parser.buffer, parser.buffer_pos+peek) {
1857 // Got line break or terminator.
1858 if close_flow || !recent_empty {
1859 if close_flow || first_empty && (start_mark.Line == foot_line && token.Type != VALUE_TOKEN || start_mark.Column-1 < next_indent) {
1860 // This is the first empty line and there were no empty lines before,
1861 // so this initial part of the comment is a foot of the prior token
1862 // instead of being a head for the following one. Split it up.
1863 // Alternatively, this might also be the last comment inside a flow
1864 // scope, so it must be a footer.
1865 if len(text) > 0 {
1866 if start_mark.Column-1 < next_indent {
1867 // If dedented it's unrelated to the prior token.
1868 token_mark = start_mark
1869 }
1870 parser.comments = append(parser.comments, Comment{
1871 ScanMark: scan_mark,
1872 TokenMark: token_mark,
1873 StartMark: start_mark,
1874 EndMark: Mark{parser.mark.Index + peek, line, column},
1875 Foot: text,
1876 })
1877 scan_mark = Mark{parser.mark.Index + peek, line, column}
1878 token_mark = scan_mark
1879 text = nil
1880 }
1881 } else {
1882 if len(text) > 0 && parser.buffer[parser.buffer_pos+peek] != 0 {
1883 text = append(text, '\n')
1884 }
1885 }
1886 }
1887 if !isLineBreak(parser.buffer, parser.buffer_pos+peek) {
1888 break
1889 }
1890 first_empty = false
1891 recent_empty = true
1892 column = 1
1893 line++
1894 continue
1895 }
1896
1897 if len(text) > 0 && (close_flow || column-1 < next_indent && column != start_mark.Column) {
1898 // The comment at the different indentation is a foot of the
1899 // preceding data rather than a head of the upcoming one.
1900 parser.comments = append(parser.comments, Comment{
1901 ScanMark: scan_mark,
1902 TokenMark: token_mark,
1903 StartMark: start_mark,
1904 EndMark: Mark{parser.mark.Index + peek, line, column},
1905 Foot: text,
1906 })
1907 scan_mark = Mark{parser.mark.Index + peek, line, column}
1908 token_mark = scan_mark
1909 text = nil
1910 }
1911
1912 if parser.buffer[parser.buffer_pos+peek] != '#' {
1913 break
1914 }
1915
1916 if len(text) == 0 {
1917 start_mark = Mark{parser.mark.Index + peek, line, column}
1918 } else {
1919 text = append(text, '\n')
1920 }
1921
1922 recent_empty = false
1923
1924 // Consume until after the consumed comment line.
1925 seen := parser.mark.Index + peek
1926 for {
1927 if parser.unread < 1 {
1928 if err := parser.updateBuffer(1); err != nil {
1929 return err
1930 }
1931 }
1932 if isBreakOrZero(parser.buffer, parser.buffer_pos) {
1933 if parser.mark.Index >= seen {
1934 break
1935 }
1936 if parser.unread < 2 {
1937 if err := parser.updateBuffer(2); err != nil {
1938 return err
1939 }
1940 }
1941 parser.skipLine()
1942 } else if parser.mark.Index >= seen {
1943 text = parser.read(text)
1944 } else {
1945 parser.skip()
1946 }
1947 }
1948
1949 peek = 0
1950 column = 1
1951 line = parser.mark.Line
1952 next_indent = parser.indent
1953 if next_indent < 0 {
1954 next_indent = 0
1955 }
1956 }
1957
1958 if len(text) > 0 {
1959 parser.comments = append(parser.comments, Comment{
1960 ScanMark: scan_mark,
1961 TokenMark: start_mark,
1962 StartMark: start_mark,
1963 EndMark: Mark{parser.mark.Index + peek - 1, line, column},
1964 Head: text,
1965 })
1966 }
1967 return nil
1968 }
1969
1970 // scanDirective scans a directive (%YAML or %TAG).
1971 func (parser *Parser) scanDirective(token *Token) error {
1972 // Eat '%'.
1973 start_mark := parser.mark
1974 parser.skip()
1975
1976 // Scan the directive name.
1977 var name []byte
1978 if err := parser.scanDirectiveName(start_mark, &name); err != nil {
1979 return err
1980 }
1981
1982 // Is it a YAML directive?
1983 if bytes.Equal(name, []byte("YAML")) {
1984 // Scan the VERSION directive value.
1985 var major, minor int8
1986 if err := parser.scanVersionDirectiveValue(start_mark, &major, &minor); err != nil {
1987 return err
1988 }
1989 end_mark := parser.mark
1990
1991 // Create a VERSION-DIRECTIVE token.
1992 *token = Token{
1993 Type: VERSION_DIRECTIVE_TOKEN,
1994 StartMark: start_mark,
1995 EndMark: end_mark,
1996 major: major,
1997 minor: minor,
1998 }
1999
2000 // Is it a TAG directive?
2001 } else if bytes.Equal(name, []byte("TAG")) {
2002 // Scan the TAG directive value.
2003 var handle, prefix []byte
2004 if err := parser.scanTagDirectiveValue(start_mark, &handle, &prefix); err != nil {
2005 return err
2006 }
2007 end_mark := parser.mark
2008
2009 // Create a TAG-DIRECTIVE token.
2010 *token = Token{
2011 Type: TAG_DIRECTIVE_TOKEN,
2012 StartMark: start_mark,
2013 EndMark: end_mark,
2014 Value: handle,
2015 prefix: prefix,
2016 }
2017
2018 // Unknown directive.
2019 } else {
2020 return formatScannerErrorContext("while scanning a directive", start_mark,
2021 "found unknown directive name", parser.mark)
2022 }
2023
2024 // Eat the rest of the line including any comments.
2025 if parser.unread < 1 {
2026 if err := parser.updateBuffer(1); err != nil {
2027 return err
2028 }
2029 }
2030
2031 for isBlank(parser.buffer, parser.buffer_pos) {
2032 parser.skip()
2033 if parser.unread < 1 {
2034 if err := parser.updateBuffer(1); err != nil {
2035 return err
2036 }
2037 }
2038 }
2039
2040 if parser.buffer[parser.buffer_pos] == '#' {
2041 // [Go] Discard this inline comment for the time being.
2042 //if !parser.ScanLineComment(start_mark) {
2043 // return false
2044 //}
2045 for !isBreakOrZero(parser.buffer, parser.buffer_pos) {
2046 parser.skip()
2047 if parser.unread < 1 {
2048 if err := parser.updateBuffer(1); err != nil {
2049 return err
2050 }
2051 }
2052 }
2053 }
2054
2055 // Check if we are at the end of the line.
2056 if !isBreakOrZero(parser.buffer, parser.buffer_pos) {
2057 return formatScannerErrorContext("while scanning a directive", start_mark,
2058 "did not find expected comment or line break", parser.mark)
2059 }
2060
2061 // Eat a line break.
2062 if isLineBreak(parser.buffer, parser.buffer_pos) {
2063 if parser.unread < 2 {
2064 if err := parser.updateBuffer(2); err != nil {
2065 return err
2066 }
2067 }
2068 parser.skipLine()
2069 }
2070
2071 return nil
2072 }
2073
2074 // Scan the directive name.
2075 //
2076 // Scope:
2077 //
2078 // %YAML 1.1 # a comment \n
2079 // ^^^^
2080 // %TAG !yaml! tag:yaml.org,2002: \n
2081 // ^^^
2082 func (parser *Parser) scanDirectiveName(start_mark Mark, name *[]byte) error {
2083 // Consume the directive name.
2084 if parser.unread < 1 {
2085 if err := parser.updateBuffer(1); err != nil {
2086 return err
2087 }
2088 }
2089
2090 var s []byte
2091 for isAlpha(parser.buffer, parser.buffer_pos) {
2092 s = parser.read(s)
2093 if parser.unread < 1 {
2094 if err := parser.updateBuffer(1); err != nil {
2095 return err
2096 }
2097 }
2098 }
2099
2100 // Check if the name is empty.
2101 if len(s) == 0 {
2102 return formatScannerErrorContext("while scanning a directive", start_mark,
2103 "could not find expected directive name", parser.mark)
2104 }
2105
2106 // Check for an blank character after the name.
2107 if !isBlankOrZero(parser.buffer, parser.buffer_pos) {
2108 return formatScannerErrorContext("while scanning a directive", start_mark,
2109 "found unexpected non-alphabetical character", parser.mark)
2110 }
2111 *name = s
2112 return nil
2113 }
2114
2115 // Scan the value of VERSION-DIRECTIVE.
2116 //
2117 // Scope:
2118 //
2119 // %YAML 1.1 # a comment \n
2120 // ^^^^^^
2121 func (parser *Parser) scanFlowScalar(token *Token, single bool) error {
2122 // Eat the left quote.
2123 start_mark := parser.mark
2124 parser.skip()
2125
2126 // Consume the content of the quoted scalar.
2127 var s, leading_break, trailing_breaks, whitespaces []byte
2128 for {
2129 // Check that there are no document indicators at the beginning
2130 // of the line.
2131 if parser.unread < 4 {
2132 if err := parser.updateBuffer(4); err != nil {
2133 return err
2134 }
2135 }
2136
2137 if parser.mark.Column == 1 &&
2138 ((parser.buffer[parser.buffer_pos+0] == '-' &&
2139 parser.buffer[parser.buffer_pos+1] == '-' &&
2140 parser.buffer[parser.buffer_pos+2] == '-') ||
2141 (parser.buffer[parser.buffer_pos+0] == '.' &&
2142 parser.buffer[parser.buffer_pos+1] == '.' &&
2143 parser.buffer[parser.buffer_pos+2] == '.')) &&
2144 isBlankOrZero(parser.buffer, parser.buffer_pos+3) {
2145 return formatScannerErrorContext("while scanning a quoted scalar", start_mark,
2146 "found unexpected document indicator", parser.mark)
2147 }
2148
2149 // Check for EOF.
2150 if isZeroChar(parser.buffer, parser.buffer_pos) {
2151 return formatScannerErrorContext("while scanning a quoted scalar", start_mark,
2152 "found unexpected end of stream", parser.mark)
2153 }
2154
2155 // Consume non-blank characters.
2156 leading_blanks := false
2157 for !isBlankOrZero(parser.buffer, parser.buffer_pos) {
2158 if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' {
2159 // Is is an escaped single quote.
2160 s = append(s, '\'')
2161 parser.skip()
2162 parser.skip()
2163
2164 } else if single && parser.buffer[parser.buffer_pos] == '\'' {
2165 // It is a right single quote.
2166 break
2167 } else if !single && parser.buffer[parser.buffer_pos] == '"' {
2168 // It is a right double quote.
2169 break
2170 } else if !single && parser.buffer[parser.buffer_pos] == '\\' && isLineBreak(parser.buffer, parser.buffer_pos+1) {
2171 // It is an escaped line break.
2172 if parser.unread < 3 {
2173 if err := parser.updateBuffer(3); err != nil {
2174 return err
2175 }
2176 }
2177 parser.skip()
2178 parser.skipLine()
2179 leading_blanks = true
2180 break
2181
2182 } else if !single && parser.buffer[parser.buffer_pos] == '\\' {
2183 // It is an escape sequence.
2184 code_length := 0
2185
2186 // Check the escape character.
2187 switch parser.buffer[parser.buffer_pos+1] {
2188 case '0':
2189 s = append(s, 0)
2190 case 'a':
2191 s = append(s, '\x07')
2192 case 'b':
2193 s = append(s, '\x08')
2194 case 't', '\t':
2195 s = append(s, '\x09')
2196 case 'n':
2197 s = append(s, '\x0A')
2198 case 'v':
2199 s = append(s, '\x0B')
2200 case 'f':
2201 s = append(s, '\x0C')
2202 case 'r':
2203 s = append(s, '\x0D')
2204 case 'e':
2205 s = append(s, '\x1B')
2206 case ' ':
2207 s = append(s, '\x20')
2208 case '"':
2209 s = append(s, '"')
2210 case '\'':
2211 s = append(s, '\'')
2212 case '\\':
2213 s = append(s, '\\')
2214 case 'N': // NEL (#x85)
2215 s = append(s, '\xC2')
2216 s = append(s, '\x85')
2217 case '_': // #xA0
2218 s = append(s, '\xC2')
2219 s = append(s, '\xA0')
2220 case 'L': // LS (#x2028)
2221 s = append(s, '\xE2')
2222 s = append(s, '\x80')
2223 s = append(s, '\xA8')
2224 case 'P': // PS (#x2029)
2225 s = append(s, '\xE2')
2226 s = append(s, '\x80')
2227 s = append(s, '\xA9')
2228 case 'x':
2229 code_length = 2
2230 case 'u':
2231 code_length = 4
2232 case 'U':
2233 code_length = 8
2234 default:
2235 return formatScannerErrorContext("while scanning a quoted scalar", start_mark,
2236 "found unknown escape character", parser.mark)
2237 }
2238
2239 parser.skip()
2240 parser.skip()
2241
2242 // Consume an arbitrary escape code.
2243 if code_length > 0 {
2244 var value int
2245
2246 // Scan the character value.
2247 if parser.unread < code_length {
2248 if err := parser.updateBuffer(code_length); err != nil {
2249 return err
2250 }
2251 }
2252 for k := 0; k < code_length; k++ {
2253 if !isHex(parser.buffer, parser.buffer_pos+k) {
2254 return formatScannerErrorContext("while scanning a quoted scalar", start_mark,
2255 "did not find expected hexadecimal number", parser.mark)
2256 }
2257 value = (value << 4) + asHex(parser.buffer, parser.buffer_pos+k)
2258 }
2259
2260 // Check the value and write the character.
2261 if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF {
2262 return formatScannerErrorContext("while scanning a quoted scalar", start_mark,
2263 "found invalid Unicode character escape code", parser.mark)
2264 }
2265 if value <= 0x7F {
2266 s = append(s, byte(value))
2267 } else if value <= 0x7FF {
2268 s = append(s, byte(0xC0+(value>>6)))
2269 s = append(s, byte(0x80+(value&0x3F)))
2270 } else if value <= 0xFFFF {
2271 s = append(s, byte(0xE0+(value>>12)))
2272 s = append(s, byte(0x80+((value>>6)&0x3F)))
2273 s = append(s, byte(0x80+(value&0x3F)))
2274 } else {
2275 s = append(s, byte(0xF0+(value>>18)))
2276 s = append(s, byte(0x80+((value>>12)&0x3F)))
2277 s = append(s, byte(0x80+((value>>6)&0x3F)))
2278 s = append(s, byte(0x80+(value&0x3F)))
2279 }
2280
2281 // Advance the pointer.
2282 for k := 0; k < code_length; k++ {
2283 parser.skip()
2284 }
2285 }
2286 } else {
2287 // It is a non-escaped non-blank character.
2288 s = parser.read(s)
2289 }
2290 if parser.unread < 2 {
2291 if err := parser.updateBuffer(2); err != nil {
2292 return err
2293 }
2294 }
2295 }
2296
2297 if parser.unread < 1 {
2298 if err := parser.updateBuffer(1); err != nil {
2299 return err
2300 }
2301 }
2302
2303 // Check if we are at the end of the scalar.
2304 if single {
2305 if parser.buffer[parser.buffer_pos] == '\'' {
2306 break
2307 }
2308 } else {
2309 if parser.buffer[parser.buffer_pos] == '"' {
2310 break
2311 }
2312 }
2313
2314 // Consume blank characters.
2315 for isBlank(parser.buffer, parser.buffer_pos) || isLineBreak(parser.buffer, parser.buffer_pos) {
2316 if isBlank(parser.buffer, parser.buffer_pos) {
2317 // Consume a space or a tab character.
2318 if !leading_blanks {
2319 whitespaces = parser.read(whitespaces)
2320 } else {
2321 parser.skip()
2322 }
2323 } else {
2324 if parser.unread < 2 {
2325 if err := parser.updateBuffer(2); err != nil {
2326 return err
2327 }
2328 }
2329
2330 // Check if it is a first line break.
2331 if !leading_blanks {
2332 whitespaces = whitespaces[:0]
2333 leading_break = parser.readLine(leading_break)
2334 leading_blanks = true
2335 } else {
2336 trailing_breaks = parser.readLine(trailing_breaks)
2337 }
2338 }
2339 if parser.unread < 1 {
2340 if err := parser.updateBuffer(1); err != nil {
2341 return err
2342 }
2343 }
2344 }
2345
2346 // Join the whitespaces or fold line breaks.
2347 if leading_blanks {
2348 // Do we need to fold line breaks?
2349 if len(leading_break) > 0 && leading_break[0] == '\n' {
2350 if len(trailing_breaks) == 0 {
2351 s = append(s, ' ')
2352 } else {
2353 s = append(s, trailing_breaks...)
2354 }
2355 } else {
2356 s = append(s, leading_break...)
2357 s = append(s, trailing_breaks...)
2358 }
2359 trailing_breaks = trailing_breaks[:0]
2360 leading_break = leading_break[:0]
2361 } else {
2362 s = append(s, whitespaces...)
2363 whitespaces = whitespaces[:0]
2364 }
2365 }
2366
2367 // Eat the right quote.
2368 parser.skip()
2369 end_mark := parser.mark
2370
2371 // Create a token.
2372 *token = Token{
2373 Type: SCALAR_TOKEN,
2374 StartMark: start_mark,
2375 EndMark: end_mark,
2376 Value: s,
2377 Style: SINGLE_QUOTED_SCALAR_STYLE,
2378 }
2379 if !single {
2380 token.Style = DOUBLE_QUOTED_SCALAR_STYLE
2381 }
2382 return nil
2383 }
2384
2385 // Scan a plain scalar.
2386 func (parser *Parser) scanLineComment(token_mark Mark) error {
2387 if parser.newlines > 0 {
2388 return nil
2389 }
2390
2391 var start_mark Mark
2392 var text []byte
2393
2394 for peek := 0; peek < 512; peek++ {
2395 if parser.unread < peek+1 {
2396 if parser.updateBuffer(peek+1) != nil {
2397 break
2398 }
2399 }
2400 if isBlank(parser.buffer, parser.buffer_pos+peek) {
2401 continue
2402 }
2403 if parser.buffer[parser.buffer_pos+peek] == '#' {
2404 seen := parser.mark.Index + peek
2405 for {
2406 if parser.unread < 1 {
2407 if err := parser.updateBuffer(1); err != nil {
2408 return err
2409 }
2410 }
2411 if isBreakOrZero(parser.buffer, parser.buffer_pos) {
2412 if parser.mark.Index >= seen {
2413 break
2414 }
2415 if parser.unread < 2 {
2416 if err := parser.updateBuffer(2); err != nil {
2417 return err
2418 }
2419 }
2420 parser.skipLine()
2421 } else if parser.mark.Index >= seen {
2422 if len(text) == 0 {
2423 start_mark = parser.mark
2424 }
2425 text = parser.read(text)
2426 } else {
2427 parser.skip()
2428 }
2429 }
2430 }
2431 break
2432 }
2433 if len(text) > 0 {
2434 parser.comments = append(parser.comments, Comment{
2435 ScanMark: token_mark,
2436 TokenMark: token_mark,
2437 StartMark: start_mark,
2438 EndMark: parser.mark,
2439 Line: text,
2440 })
2441 }
2442 return nil
2443 }
2444
2445 // scanComments scans and associates comments with tokens, handling head, line,
2446 // and foot comments based on their position relative to tokens.
2447 func (parser *Parser) scanPlainScalar(token *Token) error {
2448 var s, leading_break, trailing_breaks, whitespaces []byte
2449 var leading_blanks bool
2450 indent := parser.indent + 1
2451
2452 start_mark := parser.mark
2453 end_mark := parser.mark
2454
2455 // Consume the content of the plain scalar.
2456 for {
2457 // Check for a document indicator.
2458 if parser.unread < 4 {
2459 if err := parser.updateBuffer(4); err != nil {
2460 return err
2461 }
2462 }
2463 if parser.mark.Column == 1 &&
2464 ((parser.buffer[parser.buffer_pos+0] == '-' &&
2465 parser.buffer[parser.buffer_pos+1] == '-' &&
2466 parser.buffer[parser.buffer_pos+2] == '-') ||
2467 (parser.buffer[parser.buffer_pos+0] == '.' &&
2468 parser.buffer[parser.buffer_pos+1] == '.' &&
2469 parser.buffer[parser.buffer_pos+2] == '.')) &&
2470 isBlankOrZero(parser.buffer, parser.buffer_pos+3) {
2471 break
2472 }
2473
2474 // Check for a comment.
2475 if parser.buffer[parser.buffer_pos] == '#' {
2476 break
2477 }
2478
2479 // Consume non-blank characters.
2480 for !isBlankOrZero(parser.buffer, parser.buffer_pos) {
2481
2482 // Check for indicators that may end a plain scalar.
2483 // Check for ": " or isEndOfScalarInFlowContentChar in flow context.
2484 if (parser.buffer[parser.buffer_pos] == ':' && isBlankOrZero(parser.buffer, parser.buffer_pos+1)) ||
2485 (parser.flow_level > 0 && isEndOfScalarInFlowContentChar(parser.buffer, parser.buffer_pos)) {
2486 break
2487 }
2488
2489 // Check if we need to join whitespaces and breaks.
2490 if leading_blanks || len(whitespaces) > 0 {
2491 if leading_blanks {
2492 // Do we need to fold line breaks?
2493 if leading_break[0] == '\n' {
2494 if len(trailing_breaks) == 0 {
2495 s = append(s, ' ')
2496 } else {
2497 s = append(s, trailing_breaks...)
2498 }
2499 } else {
2500 s = append(s, leading_break...)
2501 s = append(s, trailing_breaks...)
2502 }
2503 trailing_breaks = trailing_breaks[:0]
2504 leading_break = leading_break[:0]
2505 leading_blanks = false
2506 } else {
2507 s = append(s, whitespaces...)
2508 whitespaces = whitespaces[:0]
2509 }
2510 }
2511
2512 // Copy the character.
2513 s = parser.read(s)
2514
2515 end_mark = parser.mark
2516 if parser.unread < 2 {
2517 if err := parser.updateBuffer(2); err != nil {
2518 return err
2519 }
2520 }
2521 }
2522
2523 // Is it the end?
2524 if !(isBlank(parser.buffer, parser.buffer_pos) || isLineBreak(parser.buffer, parser.buffer_pos)) {
2525 break
2526 }
2527
2528 // Consume blank characters.
2529 if parser.unread < 1 {
2530 if err := parser.updateBuffer(1); err != nil {
2531 return err
2532 }
2533 }
2534
2535 for isBlank(parser.buffer, parser.buffer_pos) || isLineBreak(parser.buffer, parser.buffer_pos) {
2536 if isBlank(parser.buffer, parser.buffer_pos) {
2537
2538 // Check for tab characters that abuse indentation.
2539 if leading_blanks && parser.mark.Column < indent && isTab(parser.buffer, parser.buffer_pos) {
2540 return formatScannerErrorContext("while scanning a plain scalar", start_mark,
2541 "found a tab character that violates indentation", parser.mark)
2542 }
2543
2544 // Consume a space or a tab character.
2545 if !leading_blanks {
2546 whitespaces = parser.read(whitespaces)
2547 } else {
2548 parser.skip()
2549 }
2550 } else {
2551 if parser.unread < 2 {
2552 if err := parser.updateBuffer(2); err != nil {
2553 return err
2554 }
2555 }
2556
2557 // Check if it is a first line break.
2558 if !leading_blanks {
2559 whitespaces = whitespaces[:0]
2560 leading_break = parser.readLine(leading_break)
2561 leading_blanks = true
2562 } else {
2563 trailing_breaks = parser.readLine(trailing_breaks)
2564 }
2565 }
2566 if parser.unread < 1 {
2567 if err := parser.updateBuffer(1); err != nil {
2568 return err
2569 }
2570 }
2571 }
2572
2573 // Check indentation level.
2574 if parser.flow_level == 0 && parser.mark.Column < indent {
2575 break
2576 }
2577 }
2578
2579 // Create a token.
2580 *token = Token{
2581 Type: SCALAR_TOKEN,
2582 StartMark: start_mark,
2583 EndMark: end_mark,
2584 Value: s,
2585 Style: PLAIN_SCALAR_STYLE,
2586 }
2587
2588 // Note that we change the 'simple_key_allowed' flag.
2589 if leading_blanks {
2590 parser.simple_key_allowed = true
2591 }
2592 return nil
2593 }
2594
2595 // scanLineComment scans a comment on the same line as a token.
2596 func (parser *Parser) scanTag(token *Token) error {
2597 var handle, suffix []byte
2598
2599 start_mark := parser.mark
2600
2601 // Check if the tag is in the canonical form.
2602 if parser.unread < 2 {
2603 if err := parser.updateBuffer(2); err != nil {
2604 return err
2605 }
2606 }
2607
2608 if parser.buffer[parser.buffer_pos+1] == '<' {
2609 // Keep the handle as ''
2610
2611 // Eat '!<'
2612 parser.skip()
2613 parser.skip()
2614
2615 // Consume the tag value (verbatim tag - flow indicators allowed).
2616 if err := parser.scanTagURI(false, true, nil, start_mark, &suffix); err != nil {
2617 return err
2618 }
2619
2620 // Check for '>' and eat it.
2621 if parser.buffer[parser.buffer_pos] != '>' {
2622 return formatScannerErrorContext("while scanning a tag", start_mark,
2623 "did not find the expected '>'", parser.mark)
2624 }
2625
2626 parser.skip()
2627 } else {
2628 // The tag has either the '!suffix' or the '!handle!suffix' form.
2629
2630 // First, try to scan a handle.
2631 if err := parser.scanTagHandle(false, start_mark, &handle); err != nil {
2632 return err
2633 }
2634
2635 // Check if it is, indeed, handle.
2636 if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' {
2637 // Scan the suffix now (short form - flow indicators
2638 // not allowed).
2639 if err := parser.scanTagURI(false, false, nil, start_mark, &suffix); err != nil {
2640 return err
2641 }
2642 } else {
2643 // It wasn't a handle after all. Scan the rest of the
2644 // tag (short form).
2645 if err := parser.scanTagURI(false, false, handle, start_mark, &suffix); err != nil {
2646 return err
2647 }
2648
2649 // Set the handle to '!'.
2650 handle = []byte{'!'}
2651
2652 // A special case: the '!' tag. Set the handle to ''
2653 // and the suffix to '!'.
2654 if len(suffix) == 0 {
2655 handle, suffix = suffix, handle
2656 }
2657 }
2658 }
2659
2660 // Check the character which ends the tag.
2661 if parser.unread < 1 {
2662 if err := parser.updateBuffer(1); err != nil {
2663 return err
2664 }
2665 }
2666 if !isBlankOrZero(parser.buffer, parser.buffer_pos) {
2667 return formatScannerErrorContext("while scanning a tag", start_mark,
2668 "did not find expected whitespace or line break", parser.mark)
2669 }
2670
2671 end_mark := parser.mark
2672
2673 // Create a token.
2674 *token = Token{
2675 Type: TAG_TOKEN,
2676 StartMark: start_mark,
2677 EndMark: end_mark,
2678 Value: handle,
2679 suffix: suffix,
2680 }
2681 return nil
2682 }
2683
2684 // Scan a tag handle.
2685 func (parser *Parser) scanTagDirectiveValue(start_mark Mark, handle, prefix *[]byte) error {
2686 var handle_value, prefix_value []byte
2687
2688 // Eat whitespaces.
2689 if parser.unread < 1 {
2690 if err := parser.updateBuffer(1); err != nil {
2691 return err
2692 }
2693 }
2694
2695 for isBlank(parser.buffer, parser.buffer_pos) {
2696 parser.skip()
2697 if parser.unread < 1 {
2698 if err := parser.updateBuffer(1); err != nil {
2699 return err
2700 }
2701 }
2702 }
2703
2704 // Scan a handle.
2705 if err := parser.scanTagHandle(true, start_mark, &handle_value); err != nil {
2706 return err
2707 }
2708
2709 // Expect a whitespace.
2710 if parser.unread < 1 {
2711 if err := parser.updateBuffer(1); err != nil {
2712 return err
2713 }
2714 }
2715 if !isBlank(parser.buffer, parser.buffer_pos) {
2716 return formatScannerErrorContext("while scanning a %TAG directive", start_mark,
2717 "did not find expected whitespace", parser.mark)
2718 }
2719
2720 // Eat whitespaces.
2721 for isBlank(parser.buffer, parser.buffer_pos) {
2722 parser.skip()
2723 if parser.unread < 1 {
2724 if err := parser.updateBuffer(1); err != nil {
2725 return err
2726 }
2727 }
2728 }
2729
2730 // Scan a prefix (TAG directive URI - flow indicators allowed).
2731 if err := parser.scanTagURI(true, true, nil, start_mark, &prefix_value); err != nil {
2732 return err
2733 }
2734
2735 // Expect a whitespace or line break.
2736 if parser.unread < 1 {
2737 if err := parser.updateBuffer(1); err != nil {
2738 return err
2739 }
2740 }
2741 if !isBlankOrZero(parser.buffer, parser.buffer_pos) {
2742 return formatScannerErrorContext("while scanning a %TAG directive", start_mark,
2743 "did not find expected whitespace or line break", parser.mark)
2744 }
2745
2746 *handle = handle_value
2747 *prefix = prefix_value
2748 return nil
2749 }
2750
2751 // scanAnchor scans an ANCHOR or ALIAS token.
2752 func (parser *Parser) scanTagHandle(directive bool, start_mark Mark, handle *[]byte) error {
2753 // Check the initial '!' character.
2754 if parser.unread < 1 {
2755 if err := parser.updateBuffer(1); err != nil {
2756 return err
2757 }
2758 }
2759 if parser.buffer[parser.buffer_pos] != '!' {
2760 return parser.setScannerTagError(directive,
2761 start_mark, "did not find expected '!'")
2762 }
2763
2764 var s []byte
2765
2766 // Copy the '!' character.
2767 s = parser.read(s)
2768
2769 // Copy all subsequent alphabetical and numerical characters.
2770 if parser.unread < 1 {
2771 if err := parser.updateBuffer(1); err != nil {
2772 return err
2773 }
2774 }
2775 for isAlpha(parser.buffer, parser.buffer_pos) {
2776 s = parser.read(s)
2777 if parser.unread < 1 {
2778 if err := parser.updateBuffer(1); err != nil {
2779 return err
2780 }
2781 }
2782 }
2783
2784 // Check if the trailing character is '!' and copy it.
2785 if parser.buffer[parser.buffer_pos] == '!' {
2786 s = parser.read(s)
2787 } else {
2788 // It's either the '!' tag or not really a tag handle.
2789 // If it's a %TAG directive, it's an error.
2790 // If it's a tag token, it must be a part of URI.
2791 if directive && string(s) != "!" {
2792 return parser.setScannerTagError(directive,
2793 start_mark, "did not find expected '!'")
2794 }
2795 }
2796
2797 *handle = s
2798 return nil
2799 }
2800
2801 // Scan a tag URI.
2802 // directive: true if scanning a %TAG directive URI
2803 // verbatim: true if scanning a verbatim tag !<...> or TAG directive (flow indicators allowed)
2804 func (parser *Parser) scanTagURI(directive bool, verbatim bool, head []byte, start_mark Mark, uri *[]byte) error {
2805 // size_t length = head ? strlen((char *)head) : 0
2806 var s []byte
2807 hasTag := len(head) > 0
2808
2809 // Copy the head if needed.
2810 //
2811 // Note that we don't copy the leading '!' character.
2812 if len(head) > 1 {
2813 s = append(s, head[1:]...)
2814 }
2815
2816 // Scan the tag.
2817 if parser.unread < 1 {
2818 if err := parser.updateBuffer(1); err != nil {
2819 return err
2820 }
2821 }
2822
2823 // The set of characters that may appear in URI is as follows:
2824 //
2825 // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@',
2826 // '&', '=', '+', '$', '.', '!', '~', '*', '\'', '(', ')', '%'.
2827 //
2828 // Note: Flow indicators (',', '[', ']', '{', '}') are only allowed in
2829 // verbatim tags.
2830 for isTagURIChar(parser.buffer, parser.buffer_pos, verbatim) {
2831 // Check if it is a URI-escape sequence.
2832 if parser.buffer[parser.buffer_pos] == '%' {
2833 if err := parser.scanURIEscapes(directive, start_mark, &s); err != nil {
2834 return err
2835 }
2836 } else {
2837 s = parser.read(s)
2838 }
2839 if parser.unread < 1 {
2840 if err := parser.updateBuffer(1); err != nil {
2841 return err
2842 }
2843 }
2844 hasTag = true
2845 }
2846
2847 // Check for characters which are not allowed in tags.
2848 // For non-verbatim tags, if we stopped at a printable character that
2849 // isn't whitespace, it's an invalid tag character - give a specific
2850 // error.
2851 // For verbatim tags, the caller will check for the expected '>'
2852 // delimiter.
2853 if !verbatim {
2854 c := parser.buffer[parser.buffer_pos]
2855 if !isBlankOrZero(parser.buffer, parser.buffer_pos) &&
2856 c >= 0x20 && c <= 0x7E {
2857 return parser.setScannerTagError(directive, start_mark,
2858 fmt.Sprintf("found character '%c' that is not allowed in a YAML tag", c))
2859 }
2860 }
2861
2862 if !hasTag {
2863 return parser.setScannerTagError(directive,
2864 start_mark, "did not find expected tag URI")
2865 }
2866 *uri = s
2867 return nil
2868 }
2869
2870 // Decode an URI-escape sequence corresponding to a single UTF-8 character.
2871 func (parser *Parser) scanToNextToken() error {
2872 scan_mark := parser.mark
2873
2874 // Until the next token is not found.
2875 for {
2876 // Allow the BOM mark to start a line.
2877 if parser.unread < 1 {
2878 if err := parser.updateBuffer(1); err != nil {
2879 return err
2880 }
2881 }
2882 if parser.mark.Column == 1 && isBOM(parser.buffer, parser.buffer_pos) {
2883 parser.skip()
2884 }
2885
2886 // Eat whitespaces.
2887 // Tabs are allowed:
2888 // - in the flow context
2889 // - in the block context, but not at the beginning of the line or
2890 // after '-', '?', or ':' (complex value).
2891 if parser.unread < 1 {
2892 if err := parser.updateBuffer(1); err != nil {
2893 return err
2894 }
2895 }
2896
2897 for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') {
2898 parser.skip()
2899 if parser.unread < 1 {
2900 if err := parser.updateBuffer(1); err != nil {
2901 return err
2902 }
2903 }
2904 }
2905
2906 // Check if we just had a line comment under a sequence entry that
2907 // looks more like a header to the following content. Similar to this:
2908 //
2909 // - # The comment
2910 // - Some data
2911 //
2912 // If so, transform the line comment to a head comment and reposition.
2913 if len(parser.comments) > 0 && len(parser.tokens) > 1 {
2914 tokenA := parser.tokens[len(parser.tokens)-2]
2915 tokenB := parser.tokens[len(parser.tokens)-1]
2916 comment := &parser.comments[len(parser.comments)-1]
2917 if tokenA.Type == BLOCK_SEQUENCE_START_TOKEN && tokenB.Type == BLOCK_ENTRY_TOKEN && len(comment.Line) > 0 && !isLineBreak(parser.buffer, parser.buffer_pos) {
2918 // If it was in the prior line, reposition so it becomes a
2919 // header of the follow up token. Otherwise, keep it in place
2920 // so it becomes a header of the former.
2921 comment.Head = comment.Line
2922 comment.Line = nil
2923 if comment.StartMark.Line == parser.mark.Line-1 {
2924 comment.TokenMark = parser.mark
2925 }
2926 }
2927 }
2928
2929 // Eat a comment until a line break.
2930 if parser.buffer[parser.buffer_pos] == '#' {
2931 if parser.skip_comments {
2932 // Skip comment without storing it
2933 for !isLineBreak(parser.buffer, parser.buffer_pos) && !isZeroChar(parser.buffer, parser.buffer_pos) {
2934 parser.skip()
2935 if parser.unread < 1 {
2936 if err := parser.updateBuffer(1); err != nil {
2937 return err
2938 }
2939 }
2940 }
2941 } else {
2942 if err := parser.scanComments(scan_mark); err != nil {
2943 return err
2944 }
2945 }
2946 }
2947
2948 // If it is a line break, eat it.
2949 if isLineBreak(parser.buffer, parser.buffer_pos) {
2950 if parser.unread < 2 {
2951 if err := parser.updateBuffer(2); err != nil {
2952 return err
2953 }
2954 }
2955 parser.skipLine()
2956
2957 // In the block context, a new line may start a simple key.
2958 if parser.flow_level == 0 {
2959 parser.simple_key_allowed = true
2960 }
2961 } else {
2962 break // We have found a token.
2963 }
2964 }
2965
2966 return nil
2967 }
2968
2969 // Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token.
2970 //
2971 // Scope:
2972 //
2973 // %YAML 1.1 # a comment \n
2974 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2975 // %TAG !yaml! tag:yaml.org,2002: \n
2976 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2977 func (parser *Parser) scanURIEscapes(directive bool, start_mark Mark, s *[]byte) error {
2978 // Decode the required number of characters.
2979 w := 1024
2980 for w > 0 {
2981 // Check for a URI-escaped octet.
2982 if parser.unread < 3 {
2983 if err := parser.updateBuffer(3); err != nil {
2984 return err
2985 }
2986 }
2987
2988 if !(parser.buffer[parser.buffer_pos] == '%' &&
2989 isHex(parser.buffer, parser.buffer_pos+1) &&
2990 isHex(parser.buffer, parser.buffer_pos+2)) {
2991 return parser.setScannerTagError(directive,
2992 start_mark, "did not find URI escaped octet")
2993 }
2994
2995 // Get the octet.
2996 octet := byte((asHex(parser.buffer, parser.buffer_pos+1) << 4) + asHex(parser.buffer, parser.buffer_pos+2))
2997
2998 // If it is the leading octet, determine the length of the
2999 // UTF-8 sequence.
3000 if w == 1024 {
3001 w = width(octet)
3002 if w == 0 {
3003 return parser.setScannerTagError(directive,
3004 start_mark, "found an incorrect leading UTF-8 octet")
3005 }
3006 } else {
3007 // Check if the trailing octet is correct.
3008 if octet&0xC0 != 0x80 {
3009 return parser.setScannerTagError(directive,
3010 start_mark, "found an incorrect trailing UTF-8 octet")
3011 }
3012 }
3013
3014 // Copy the octet and move the pointers.
3015 *s = append(*s, octet)
3016 parser.skip()
3017 parser.skip()
3018 parser.skip()
3019 w--
3020 }
3021 return nil
3022 }
3023
3024 // Scan a block scalar.
3025 func (parser *Parser) scanVersionDirectiveNumber(start_mark Mark, number *int8) error {
3026 // Repeat while the next character is digit.
3027 if parser.unread < 1 {
3028 if err := parser.updateBuffer(1); err != nil {
3029 return err
3030 }
3031 }
3032 var value, length int8
3033 for isDigit(parser.buffer, parser.buffer_pos) {
3034 // Check if the number is too long.
3035 length++
3036 if length > max_number_length {
3037 return formatScannerErrorContext("while scanning a %YAML directive", start_mark,
3038 "found extremely long version number", parser.mark)
3039 }
3040 value = value*10 + int8(asDigit(parser.buffer, parser.buffer_pos))
3041 parser.skip()
3042 if parser.unread < 1 {
3043 if err := parser.updateBuffer(1); err != nil {
3044 return err
3045 }
3046 }
3047 }
3048
3049 // Check if the number was present.
3050 if length == 0 {
3051 return formatScannerErrorContext("while scanning a %YAML directive", start_mark,
3052 "did not find expected version number", parser.mark)
3053 }
3054 *number = value
3055 return nil
3056 }
3057
3058 // Scan the value of a TAG-DIRECTIVE token.
3059 //
3060 // Scope:
3061 //
3062 // %TAG !yaml! tag:yaml.org,2002: \n
3063 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3064 func (parser *Parser) scanVersionDirectiveValue(start_mark Mark, major, minor *int8) error {
3065 // Eat whitespaces.
3066 if parser.unread < 1 {
3067 if err := parser.updateBuffer(1); err != nil {
3068 return err
3069 }
3070 }
3071 for isBlank(parser.buffer, parser.buffer_pos) {
3072 parser.skip()
3073 if parser.unread < 1 {
3074 if err := parser.updateBuffer(1); err != nil {
3075 return err
3076 }
3077 }
3078 }
3079
3080 // Consume the major version number.
3081 if err := parser.scanVersionDirectiveNumber(start_mark, major); err != nil {
3082 return err
3083 }
3084
3085 // Eat '.'.
3086 if parser.buffer[parser.buffer_pos] != '.' {
3087 return formatScannerErrorContext("while scanning a %YAML directive", start_mark,
3088 "did not find expected digit or '.' character", parser.mark)
3089 }
3090
3091 parser.skip()
3092
3093 // Consume the minor version number.
3094 if err := parser.scanVersionDirectiveNumber(start_mark, minor); err != nil {
3095 return err
3096 }
3097 return nil
3098 }
3099
3100 // max_number_length limits the length of version number components in
3101 // %YAML directives.
3102 func (parser *Parser) saveSimpleKey() error {
3103 // A simple key is required at the current position if the scanner is in
3104 // the block context and the current column coincides with the indentation
3105 // level.
3106
3107 required := parser.flow_level == 0 && parser.indent == parser.mark.Column
3108
3109 //
3110 // If the current position may start a simple key, save it.
3111 //
3112 if parser.simple_key_allowed {
3113 if err := parser.removeSimpleKey(); err != nil {
3114 return err
3115 }
3116
3117 parser.simple_key_possible = true
3118 parser.simple_key = SimpleKey{
3119 required: required,
3120 flow_level: parser.flow_level,
3121 token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head),
3122 mark: parser.mark,
3123 }
3124 }
3125 return nil
3126 }
3127
3128 // Remove a potential simple key at the current flow level.
3129 func (parser *Parser) removeSimpleKey() error {
3130 // If the key is required, it is an error.
3131 if parser.simple_key.required {
3132 return formatScannerErrorContext(
3133 "while scanning a simple key", parser.simple_key.mark,
3134 "could not find expected ':'", parser.mark)
3135 }
3136
3137 parser.simple_key_possible = false // disable the key
3138 return nil
3139 }
3140
3141 func (parser *Parser) isFlowSequence() bool {
3142 if len(parser.tokens) == 0 {
3143 return false
3144 }
3145 previousToken := parser.tokens[len(parser.tokens)-1]
3146 return previousToken.Type == FLOW_ENTRY_TOKEN || previousToken.Type == FLOW_SEQUENCE_START_TOKEN
3147 }
3148
3149 // Check if a simple key may start at the current position and add it if
3150 // needed.
3151 func (parser *Parser) increaseFlowLevel() error {
3152 // Increase the flow level.
3153 parser.flow_level++
3154 if err := parser.depthCheck(parser.flow_level, &DepthContext{Kind: DepthKindFlow}); err != nil {
3155 return formatScannerErrorContext(
3156 "while increasing flow level", parser.simple_key.mark,
3157 err.Error(), parser.mark)
3158 }
3159
3160 // If a simple key was possible, push it to the stack before resetting the key.
3161 if parser.simple_key_possible {
3162 parser.simple_key_stack = append(parser.simple_key_stack, parser.simple_key)
3163 }
3164
3165 // Reset the simple key for the new flow level.
3166 parser.simple_key = SimpleKey{}
3167
3168 return nil
3169 }
3170
3171 // Decrease the flow level.
3172 func (parser *Parser) decreaseFlowLevel() error {
3173 if parser.flow_level > 0 {
3174 parser.flow_level--
3175
3176 if len(parser.simple_key_stack) == 0 {
3177 return nil
3178 }
3179
3180 last := len(parser.simple_key_stack) - 1
3181 if parser.simple_key_stack[last].flow_level == parser.flow_level {
3182 parser.simple_key = parser.simple_key_stack[last] // use last item
3183 parser.simple_key_stack = parser.simple_key_stack[:last] // remove last item
3184 parser.simple_key_possible = true // enable the key
3185 }
3186 }
3187 return nil
3188 }
3189
3190 func (parser *Parser) rollIndent(column, number int, typ TokenType, mark Mark) error {
3191 // In the flow context, do nothing.
3192 if parser.flow_level > 0 {
3193 return nil
3194 }
3195
3196 if parser.indent < column {
3197 // Push the current indentation level to the stack and set the new
3198 // indentation level.
3199 parser.indents = append(parser.indents, parser.indent)
3200 parser.indent = column
3201 if err := parser.depthCheck(len(parser.indents), &DepthContext{Kind: DepthKindBlock}); err != nil {
3202 return formatScannerErrorContext(
3203 "while increasing indent level", parser.simple_key.mark,
3204 err.Error(), parser.mark)
3205 }
3206
3207 // Create a token and insert it into the queue.
3208 token := Token{
3209 Type: typ,
3210 StartMark: mark,
3211 EndMark: mark,
3212 }
3213 if number > -1 {
3214 number -= parser.tokens_parsed
3215 }
3216 parser.insertToken(number, &token)
3217 }
3218 return nil
3219 }
3220
3221 // Pop indentation levels from the indents stack until the current level
3222 // becomes less or equal to the column. For each indentation level, append
3223 // the BLOCK-END token.
3224 func (parser *Parser) unrollIndent(column int, scan_mark Mark) error {
3225 // In the flow context, do nothing.
3226 if parser.flow_level > 0 {
3227 return nil
3228 }
3229
3230 block_mark := scan_mark
3231 block_mark.Index--
3232
3233 // Loop through the indentation levels in the stack.
3234 for parser.indent > column {
3235
3236 // [Go] Reposition the end token before potential following
3237 // foot comments of parent blocks. For that, search
3238 // backwards for recent comments that were at the same
3239 // indent as the block that is ending now.
3240 stop_index := block_mark.Index
3241 for i := len(parser.comments) - 1; i >= 0; i-- {
3242 comment := &parser.comments[i]
3243
3244 if comment.EndMark.Index < stop_index {
3245 // Don't go back beyond the start of the
3246 // comment/whitespace scan, unless column < 0.
3247 // If requested indent column is < 0, then the
3248 // document is over and everything else is a
3249 // foot anyway.
3250 break
3251 }
3252 if comment.StartMark.Column == parser.indent+1 {
3253 // This is a good match.
3254 // But maybe there's a former comment at that
3255 // same indent level, so keep searching.
3256 block_mark = comment.StartMark
3257 }
3258
3259 // While the end of the former comment matches with
3260 // the start of the following one, we know there's
3261 // nothing in between and scanning is still safe.
3262 stop_index = comment.ScanMark.Index
3263 }
3264
3265 // Create a token and append it to the queue.
3266 token := Token{
3267 Type: BLOCK_END_TOKEN,
3268 StartMark: block_mark,
3269 EndMark: block_mark,
3270 }
3271 parser.insertToken(-1, &token)
3272
3273 // Pop the indentation level.
3274 parser.indent = parser.indents[len(parser.indents)-1]
3275 parser.indents = parser.indents[:len(parser.indents)-1]
3276 }
3277 return nil
3278 }
3279
3280 // insertToken inserts a token into the queue at the specified position.
3281 func (parser *Parser) insertToken(pos int, token *Token) {
3282 // fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens))
3283
3284 // Check if we can move the queue at the beginning of the buffer.
3285 if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) {
3286 if parser.tokens_head != len(parser.tokens) {
3287 copy(parser.tokens, parser.tokens[parser.tokens_head:])
3288 }
3289 parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head]
3290 parser.tokens_head = 0
3291 }
3292 parser.tokens = append(parser.tokens, *token)
3293 if pos < 0 {
3294 return
3295 }
3296 copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:])
3297 parser.tokens[parser.tokens_head+pos] = *token
3298 }
3299
3300 // Initialize the scanner and produce the STREAM-START token.
3301 func (parser *Parser) skip() {
3302 if !isBlank(parser.buffer, parser.buffer_pos) {
3303 parser.newlines = 0
3304 }
3305 parser.mark.Index++
3306 parser.mark.Column++
3307 parser.unread--
3308 parser.buffer_pos += width(parser.buffer[parser.buffer_pos])
3309 }
3310
3311 // skipLine advances the parser position past the current line break.
3312 func (parser *Parser) skipLine() {
3313 if isCRLF(parser.buffer, parser.buffer_pos) {
3314 parser.mark.Index += 2
3315 parser.mark.Column = 1
3316 parser.mark.Line++
3317 parser.unread -= 2
3318 parser.buffer_pos += 2
3319 parser.newlines++
3320 } else if isLineBreak(parser.buffer, parser.buffer_pos) {
3321 parser.mark.Index++
3322 parser.mark.Column = 1
3323 parser.mark.Line++
3324 parser.unread--
3325 parser.buffer_pos += width(parser.buffer[parser.buffer_pos])
3326 parser.newlines++
3327 }
3328 }
3329
3330 // Copy a character to a string buffer and advance pointers.
3331 func (parser *Parser) read(s []byte) []byte {
3332 if !isBlank(parser.buffer, parser.buffer_pos) {
3333 parser.newlines = 0
3334 }
3335 w := width(parser.buffer[parser.buffer_pos])
3336 if w == 0 {
3337 panic("invalid character sequence")
3338 }
3339 if len(s) == 0 {
3340 s = make([]byte, 0, 32)
3341 }
3342 if w == 1 && len(s)+w <= cap(s) {
3343 s = s[:len(s)+1]
3344 s[len(s)-1] = parser.buffer[parser.buffer_pos]
3345 parser.buffer_pos++
3346 } else {
3347 s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...)
3348 parser.buffer_pos += w
3349 }
3350 parser.mark.Index++
3351 parser.mark.Column++
3352 parser.unread--
3353 return s
3354 }
3355
3356 // Copy a line break character to a string buffer and advance pointers.
3357 func (parser *Parser) readLine(s []byte) []byte {
3358 buf := parser.buffer
3359 pos := parser.buffer_pos
3360 switch {
3361 case buf[pos] == '\r' && buf[pos+1] == '\n':
3362 // CR LF . LF
3363 s = append(s, '\n')
3364 parser.buffer_pos += 2
3365 parser.mark.Index++
3366 parser.unread--
3367 case buf[pos] == '\r' || buf[pos] == '\n':
3368 // CR|LF . LF
3369 s = append(s, '\n')
3370 parser.buffer_pos += 1
3371 case buf[pos] == '\xC2' && buf[pos+1] == '\x85':
3372 // NEL . LF
3373 s = append(s, '\n')
3374 parser.buffer_pos += 2
3375 case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'):
3376 // LS|PS . LS|PS
3377 s = append(s, buf[parser.buffer_pos:pos+3]...)
3378 parser.buffer_pos += 3
3379 default:
3380 return s
3381 }
3382 parser.mark.Index++
3383 parser.mark.Column = 1
3384 parser.mark.Line++
3385 parser.unread--
3386 parser.newlines++
3387 return s
3388 }
3389
3390 // formatScannerError creates a LoadError for scanner-stage errors.
3391 func formatScannerError(problem string, problemMark Mark) *LoadError {
3392 return &LoadError{
3393 Stage: ScannerStage,
3394 Mark: problemMark,
3395 Message: problem,
3396 }
3397 }
3398
3399 // formatScannerErrorContext creates a LoadError with both context and
3400 // problem information, each with their own mark positions.
3401 func formatScannerErrorContext(context string, contextMark Mark, problem string, problemMark Mark) *LoadError {
3402 return &LoadError{
3403 Stage: ScannerStage,
3404 ContextMark: contextMark,
3405 ContextMsg: context,
3406 Mark: problemMark,
3407 Message: problem,
3408 }
3409 }
3410
3411 // setScannerTagError creates a tag-related scanner error with appropriate
3412 // context based on whether it's from a directive or tag parsing.
3413 func (parser *Parser) setScannerTagError(directive bool, contextMark Mark, problem string) error {
3414 context := "while parsing a tag"
3415 if directive {
3416 context = "while parsing a %TAG directive"
3417 }
3418 return formatScannerErrorContext(context, contextMark, problem, parser.mark)
3419 }
3420
3421 // trace is a debug utility that prints entry/exit messages for function calls.
3422 func trace(args ...any) func() {
3423 pargs := append([]any{"+++"}, args...)
3424 fmt.Println(pargs...)
3425 pargs = append([]any{"---"}, args...)
3426 return func() { fmt.Println(pargs...) }
3427 }
3428
3429 // Ensure that the tokens queue contains at least one token which can be
3430 // returned to the Parser.