1#![forbid(unsafe_code)]
24#![allow(clippy::result_large_err)]
27
28use std::cell::RefCell;
29use std::rc::Rc;
30use std::sync::{Arc, OnceLock};
31
32use indexmap::IndexMap;
33use serde_json::json;
34use tabnas::{
35 Context, GrammarSpec, Plugin, PluginError, Rule, Tabnas, Token, Value, TIN_NR, TIN_ST, TIN_TX,
36 TIN_VL,
37};
38
39mod lex;
40mod source;
41mod state;
42mod text;
43
44#[cfg(doctest)]
46#[doc = include_str!("../README.md")]
47mod readme_examples {}
48
49pub const VERSION: &str = "0.5.34";
54
55const PLUGIN_NAME: &str = "yaml";
57
58pub(crate) const UNDEFINED_ALIAS: &str = "yaml_undefined_alias";
61
62pub(crate) const RECURSIVE_ALIAS: &str = "yaml_recursive_alias";
64
65const INSTALLED: &str = "yaml-installed";
70
71pub use tabnas::TabnasError as YamlError;
74
75const GRAMMAR_TEXT: &str = r##"
77# YAML Grammar Definition
78# Parsed by a standard Tabnas instance and passed to tabnas.grammar()
79# Function references (@ prefixed) are resolved against the refs map.
80# State handlers (bo/ao/bc/ac) remain wired in code, since they use
81# closures over per-parse state (anchors, pendingAnchors, etc.).
82
83{
84 # Amend val rule: YAML indent/element-marker handling.
85 rule: val: open: {
86 alts: [
87 # Doc-frame markers between docs mean an empty value here; back up so
88 # the stream rule consumes the marker and starts the next document.
89 { s: '#DS' b: 1 a: '@val-set-null' g: yaml }
90 { s: '#DE' b: 1 a: '@val-set-null' g: yaml }
91 { s: '#DR' b: 1 a: '@val-set-null' g: yaml }
92 # Indent followed by content: push indent rule.
93 { s: '#IN' c: '@val-indent-deeper' p: indent a: '@val-set-in-from-o0' g: yaml }
94 # Same indent followed by element marker: list value at map level.
95 { s: ['#IN' '#EL'] c: '@val-indent-eq-parent' p: yamlBlockList a: '@val-set-in-from-o0' g: yaml }
96 # End of input means empty value.
97 { s: '#ZZ' b: 1 a: '@val-set-null' g: yaml }
98 # Same or lesser indent after a colon means empty value — backtrack.
99 { s: '#IN' b: 1 u: { yamlEmpty: true } g: yaml }
100 # This value is a list: a sequence's entry, or a document's root. A
101 # block sequence cannot start on the line of the key it is the value
102 # of (key: - a), so a pair's value is not one here.
103 { s: '#EL' c: '@val-not-pair-value' p: yamlBlockList a: '@val-set-el-in' g: yaml }
104 ]
105 inject: { append: false }
106 }
107 rule: val: close: {
108 alts: [
109 # Doc-frame markers terminate val; back up for the stream rule.
110 { s: '#DS' b: 1 g: 'yaml,end' }
111 { s: '#DE' b: 1 g: 'yaml,end' }
112 { s: '#DR' b: 1 g: 'yaml,end' }
113 { s: '#IN' b: 1 g: 'yaml,close' }
114 ]
115 inject: { append: false }
116 }
117
118 # Indent rule: start for block content at a given indent.
119 rule: indent: open: [
120 # Key pair => map.
121 { s: ['#KEY' '#CL'] p: map b: 2 g: yaml }
122 # Element marker => block sequence. yamlBlockList, not jsonic's list:
123 # list reads a '[' as its own opening bracket, so a flow sequence as the
124 # first item (k:\n - [1, 2]) became the block sequence itself, or
125 # failed at the next item (tabnas/yaml#88).
126 { s: '#EL' p: yamlBlockList g: yaml }
127 # Flow collection as a block-mapping value on the FOLLOWING line:
128 # required:
129 # [a, b, c]
130 # Valid YAML 1.2, and the inline spelling has always worked. The
131 # indent rule opens at the deeper indent and meets a
132 # flow opener, which only the val rule knows how to read, so hand it back
133 # one token so val sees the bracket or brace itself.
134 { s: '#OS' p: val b: 1 g: yaml }
135 { s: '#OB' p: val b: 1 g: yaml }
136 # Plain value after indent (for nested scalars).
137 { s: '#KEY' a: '@indent-plain-value' g: yaml }
138 ]
139
140 # YAML block list: handles "- " sequences without consuming "[".
141 rule: yamlBlockList: open: [
142 # Element value is a key-value map: - key: val
143 { s: ['#KEY' '#CL'] p: yamlElemMap b: 2 a: '@set-map-in' g: yaml }
144 # Default: push to val for the element's value.
145 { p: val g: yaml }
146 ]
147 rule: yamlBlockList: close: [
148 # Doc-frame markers terminate list; back up for the stream rule.
149 { s: '#DS' b: 1 g: 'yaml,end' }
150 { s: '#DE' b: 1 g: 'yaml,end' }
151 { s: '#DR' b: 1 g: 'yaml,end' }
152 # Indent followed by element marker: next element at same level.
153 { s: ['#IN' '#EL'] c: '@t0-eq-in' r: yamlBlockElem g: 'yaml,comma' }
154 # Same or lesser indent: close list.
155 { s: '#IN' c: '@t0-le-in' b: 1 g: 'yaml,close' }
156 # Element marker at top level (no preceding newline).
157 { s: '#EL' r: yamlBlockElem g: 'yaml,comma' }
158 { s: '#ZZ' b: 1 g: 'yaml,end' }
159 ]
160
161 # Subsequent elements in a yamlBlockList (via rotation).
162 rule: yamlBlockElem: open: [
163 { s: ['#KEY' '#CL'] p: yamlElemMap b: 2 a: '@set-map-in' g: yaml }
164 { p: val g: yaml }
165 ]
166 rule: yamlBlockElem: close: [
167 # Doc-frame markers terminate elem; back up for the stream rule.
168 { s: '#DS' b: 1 g: 'yaml,end' }
169 { s: '#DE' b: 1 g: 'yaml,end' }
170 { s: '#DR' b: 1 g: 'yaml,end' }
171 { s: ['#IN' '#EL'] c: '@t0-eq-in' r: yamlBlockElem g: 'yaml,comma' }
172 { s: '#IN' c: '@t0-le-in' b: 1 g: 'yaml,close' }
173 { s: '#EL' r: yamlBlockElem g: 'yaml,comma' }
174 { s: '#ZZ' b: 1 g: 'yaml,end' }
175 ]
176
177 # Amend list rule: close on dedent or same-indent non-element.
178 rule: list: close: {
179 alts: [
180 # Doc-frame markers terminate list; back up for the stream rule.
181 { s: '#DS' b: 1 g: 'yaml,end' }
182 { s: '#DE' b: 1 g: 'yaml,end' }
183 { s: '#DR' b: 1 g: 'yaml,end' }
184 { s: '#IN' c: '@t0-le-in' b: 1 g: 'yaml,close' }
185 ]
186 inject: { append: false }
187 }
188
189 # Amend map rule: same-indent indent continues map with pair.
190 rule: map: open: {
191 alts: [
192 { s: '#IN' c: '@o0-eq-in' r: pair g: yaml }
193 ]
194 inject: { append: false }
195 }
196 rule: map: close: {
197 alts: [
198 # Doc-frame markers terminate map; back up for the stream rule.
199 { s: '#DS' b: 1 g: 'yaml,end' }
200 { s: '#DE' b: 1 g: 'yaml,end' }
201 { s: '#DR' b: 1 g: 'yaml,end' }
202 { s: '#IN' c: '@t0-lt-in' b: 1 g: 'yaml,close' }
203 ]
204 inject: { append: false }
205 }
206
207 # Amend pair rule: end of input ends pair; dedent closes, same-indent repeats.
208 # Also handle YAML flow-mapping shapes Tabnas doesn't have natively:
209 # - implicit null values: {a, b: c} — KEY followed directly by CA or CB
210 # - explicit-key marker: {? k : v} — leading #QM is consumed
211 rule: pair: open: {
212 alts: [
213 { s: ['#KEY' '#CA'] a: '@implicit-null-pair' b: 1 g: yaml }
214 { s: ['#KEY' '#CB'] a: '@implicit-null-pair' b: 1 g: yaml }
215 { s: ['#QM' '#KEY' '#CL'] p: val u: { pair: true } a: '@qm-pairkey' g: yaml }
216 { s: ['#QM' '#KEY' '#CA'] a: '@qm-implicit-null-pair' b: 1 g: yaml }
217 { s: ['#QM' '#KEY' '#CB'] a: '@qm-implicit-null-pair' b: 1 g: yaml }
218 { s: '#ZZ' b: 1 g: 'yaml,end' }
219 ]
220 inject: { append: false }
221 }
222 rule: pair: close: {
223 alts: [
224 # Doc-frame markers terminate pair; back up for the stream rule.
225 { s: '#DS' b: 1 g: 'yaml,end' }
226 { s: '#DE' b: 1 g: 'yaml,end' }
227 { s: '#DR' b: 1 g: 'yaml,end' }
228 { s: '#IN' c: '@t0-eq-in' r: pair g: 'yaml,comma' }
229 { s: '#IN' c: '@t0-lt-in' b: 1 g: 'yaml,close' }
230 ]
231 inject: { append: false }
232 }
233
234 # yamlElemMap: a mapping that starts in a sequence entry, "- key: val",
235 # or "[key: val]" in a flow sequence. It only opens the mapping (its
236 # before-open action makes the node) and hands the first pair, unread,
237 # to yamlElemPair, which reads every pair. A pair rule opening on the
238 # open mapping names the member in u.key before it pushes the value's
239 # rule, so a consumer that follows rule events has the key before a
240 # value that is a collection opens. When the rule that opened the
241 # mapping named the first member as well, that consumer was never told
242 # the key, and the first member's value opened ahead of it
243 # (tabnas/yaml#105).
244 rule: yamlElemMap: open: [
245 { s: ['#KEY' '#CL'] r: yamlElemPair b: 2 g: yaml }
246 ]
247
248 # Every pair in a yamlElemMap, the first included.
249 rule: yamlElemPair: open: [
250 { s: ['#KEY' '#CL'] p: val a: '@elem-key' g: yaml }
251 ]
252 rule: yamlElemPair: close: [
253 # Doc-frame markers terminate elem-pair; back up for the stream rule.
254 { s: '#DS' b: 1 g: 'yaml,end' }
255 { s: '#DE' b: 1 g: 'yaml,end' }
256 { s: '#DR' b: 1 g: 'yaml,end' }
257 { s: '#IN' c: '@t0-eq-map-in' r: yamlElemPair g: 'yaml,comma' }
258 { s: '#IN' b: 1 g: 'yaml,close' }
259 { s: '#CA' b: 1 g: 'yaml,comma' }
260 { s: '#CS' b: 1 g: 'yaml,close' }
261 { s: '#CB' b: 1 g: 'yaml,close' }
262 { s: '#ZZ' g: 'yaml,end' }
263 ]
264
265 # Amend elem rule for YAML sequences ("- key: val" at top level of [ ... ]).
266 # Also handle flow-sequence explicit-key entries: [? k : v] is a single-pair
267 # map element. Eat the leading #QM, then back up KEY+CL so yamlElemMap
268 # consumes them as a normal pair.
269 rule: elem: open: {
270 alts: [
271 { s: ['#KEY' '#CL'] p: yamlElemMap b: 2 a: '@set-map-in' g: yaml }
272 { s: ['#QM' '#KEY' '#CL'] p: yamlElemMap b: 2 a: '@set-map-in' g: yaml }
273 ]
274 inject: { append: false }
275 }
276 rule: elem: close: {
277 alts: [
278 # Doc-frame markers terminate elem; back up for the stream rule.
279 { s: '#DS' b: 1 g: 'yaml,end' }
280 { s: '#DE' b: 1 g: 'yaml,end' }
281 { s: '#DR' b: 1 g: 'yaml,end' }
282 { s: ['#IN' '#EL'] c: '@t0-eq-in' r: elem g: 'yaml,comma' }
283 { s: '#IN' c: '@t0-eq-in' b: 1 g: 'yaml,close' }
284 { s: '#IN' c: '@t0-lt-in' b: 1 g: 'yaml,close' }
285 { s: '#EL' r: elem g: 'yaml,comma' }
286 ]
287 inject: { append: false }
288 }
289}
290"##;
291#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
295pub struct YamlOptions {
296 pub meta: bool,
300 pub schema: Option<Schema>,
304}
305
306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub enum Schema {
309 Core,
313}
314
315impl Schema {
316 fn name(self) -> &'static str {
318 match self {
319 Schema::Core => "core",
320 }
321 }
322}
323
324impl YamlOptions {
325 fn to_value(self) -> Value {
327 let mut map = IndexMap::new();
328 map.insert("meta".to_string(), Value::Bool(self.meta));
329 if let Some(schema) = self.schema {
330 map.insert(
331 "schema".to_string(),
332 Value::String(schema.name().to_string()),
333 );
334 }
335 Value::object(map)
336 }
337}
338
339fn schema_option(options: &Value) -> Result<Option<Schema>, PluginError> {
343 let named = match options {
344 Value::Object(map) => map.get("schema").cloned(),
345 _ => None,
346 };
347 match named {
348 None | Some(Value::Null | Value::Undefined) => Ok(None),
349 Some(Value::String(name)) if name == "core" => Ok(Some(Schema::Core)),
350 Some(other) => Err(PluginError(format!(
351 "yaml: unknown schema {}, expected 'core'",
352 other.to_json()
353 ))),
354 }
355}
356
357pub(crate) fn core_schema(context: &Context) -> bool {
359 matches!(
360 context.options.plugin.get(PLUGIN_NAME),
361 Some(Value::Object(map)) if matches!(map.get("schema"), Some(Value::String(name)) if name == "core")
362 )
363}
364
365fn set_node(rule: &mut Rule, value: Value) {
376 rule.node = Rc::new(RefCell::new(value));
377}
378
379fn map_insert(node: &mut Value, key: String, value: Value) {
380 match node {
381 Value::Object(map) => {
382 Arc::make_mut(map).insert(key, value);
383 }
384 Value::MapRef(map) => {
385 Arc::make_mut(map).value.insert(key, value);
386 }
387 _ => {}
388 }
389}
390
391fn store_member(rule: &mut Rule, context: &mut Context, key: String, value: Value) {
400 let previous = map_entries(&rule.node.borrow()).and_then(|map| map.get(&key).cloned());
401 let value = match previous {
402 None | Some(Value::Null) | Some(Value::Undefined) => value,
403 Some(previous) => {
404 if let Some(merge) = context.options.map.merge.clone() {
405 merge(previous, value, rule, context)
406 } else if context.options.map.extend {
407 tabnas_jsonic::deep_merge(previous, value)
408 } else {
409 value
410 }
411 }
412 };
413 map_insert(&mut rule.node.borrow_mut(), key, value);
414}
415
416fn map_entries(node: &Value) -> Option<&IndexMap<String, Value>> {
417 match node {
418 Value::Object(map) => Some(map),
419 Value::MapRef(map) => Some(&map.value),
420 _ => None,
421 }
422}
423
424fn list_push(node: &mut Value, value: Value) {
425 match node {
426 Value::Array(items) => Arc::make_mut(items).push(value),
427 Value::ListRef(list) => Arc::make_mut(list).value.push(value),
428 _ => {}
429 }
430}
431
432fn is_container(value: &Value) -> bool {
435 matches!(
436 value,
437 Value::Object(_) | Value::Array(_) | Value::MapRef(_) | Value::ListRef(_) | Value::Text(_)
438 )
439}
440
441fn deep_copy(value: &Value) -> Value {
449 match value {
450 Value::Object(map) => {
451 let mut out = IndexMap::new();
452 for (key, entry) in map.iter() {
453 out.insert(key.clone(), deep_copy(entry));
454 }
455 Value::object(out)
456 }
457 Value::MapRef(map) => {
458 let mut out = IndexMap::new();
459 for (key, entry) in map.value.iter() {
460 out.insert(key.clone(), deep_copy(entry));
461 }
462 Value::object(out)
463 }
464 Value::Array(items) => Value::array(items.iter().map(deep_copy).collect()),
465 Value::ListRef(list) => Value::array(list.value.iter().map(deep_copy).collect()),
466 Value::Text(text) => Value::String(text.string.clone()),
467 other => other.clone(),
468 }
469}
470
471pub(crate) fn string_of(value: &Value) -> String {
474 match value {
475 Value::Undefined => "undefined".to_string(),
476 Value::Null => "null".to_string(),
477 Value::Bool(flag) => flag.to_string(),
478 Value::Number(number) => js_number_to_string(*number),
479 Value::String(text) => text.clone(),
480 Value::Text(text) => text.string.clone(),
481 Value::Array(items) => items
482 .iter()
483 .map(|item| match item {
484 Value::Undefined | Value::Null => String::new(),
485 other => string_of(other),
486 })
487 .collect::<Vec<_>>()
488 .join(","),
489 Value::ListRef(list) => string_of(&Value::array(list.value.clone())),
490 Value::Object(_) | Value::MapRef(_) => "[object Object]".to_string(),
491 }
492}
493
494fn js_number_to_string(number: f64) -> String {
498 if number.is_nan() {
499 return "NaN".to_string();
500 }
501 if number == 0.0 {
503 return "0".to_string();
504 }
505 if number < 0.0 {
506 return format!("-{}", js_number_to_string(-number));
507 }
508 if number.is_infinite() {
509 return "Infinity".to_string();
510 }
511 let shortest = format!("{number:e}");
512 let shortest_k = shortest
513 .split_once('e')
514 .map(|(mantissa, _)| mantissa.chars().filter(char::is_ascii_digit).count())
515 .expect("a finite f64 always formats with an exponent");
516 let exponential = format!("{:.*e}", shortest_k - 1, number);
517 let (mantissa, exponent) = exponential
518 .split_once('e')
519 .expect("a finite f64 always formats with an exponent");
520 let digits = mantissa
521 .chars()
522 .filter(|digit| *digit != '.')
523 .collect::<String>();
524 let digits = digits.trim_end_matches('0');
525 let digits = if digits.is_empty() { "0" } else { digits };
526 let k = digits.len() as i32;
527 let n = exponent
528 .parse::<i32>()
529 .expect("a formatted exponent is an integer")
530 + 1;
531 if (k..=21).contains(&n) {
532 let mut text = digits.to_string();
533 text.push_str(&"0".repeat((n - k) as usize));
534 text
535 } else if (1..=21).contains(&n) {
536 let point = n as usize;
537 format!("{}.{}", &digits[..point], &digits[point..])
538 } else if (-5..=0).contains(&n) {
539 format!("0.{}{}", "0".repeat(-n as usize), digits)
540 } else {
541 let sign = if n - 1 < 0 { '-' } else { '+' };
542 let power = (n - 1).abs();
543 if k == 1 {
544 format!("{digits}e{sign}{power}")
545 } else {
546 format!("{}.{}e{sign}{power}", &digits[..1], &digits[1..])
547 }
548 }
549}
550
551pub(crate) fn js_to_number(text: &str) -> Option<f64> {
555 let trimmed = text.trim_matches(js_space);
556 if trimmed.is_empty() {
557 return Some(0.0);
558 }
559 if let Some(radix) = match trimmed.get(..2) {
560 Some("0x" | "0X") => Some(16u32),
561 Some("0o" | "0O") => Some(8),
562 Some("0b" | "0B") => Some(2),
563 _ => None,
564 } {
565 let digits = &trimmed[2..];
566 if digits.is_empty() || !digits.chars().all(|d| d.is_digit(radix)) {
567 return None;
568 }
569 let mut value = 0.0f64;
570 for digit in digits.chars() {
571 value = value * f64::from(radix) + f64::from(digit.to_digit(radix).unwrap_or(0));
572 }
573 return Some(value);
574 }
575 let (sign, body) = match trimmed.strip_prefix('-') {
576 Some(rest) => (-1.0, rest),
577 None => (1.0, trimmed.strip_prefix('+').unwrap_or(trimmed)),
578 };
579 if body == "Infinity" {
580 return Some(sign * f64::INFINITY);
581 }
582 if !is_decimal_literal(body) {
583 return None;
584 }
585 body.parse::<f64>().ok().map(|value| sign * value)
586}
587
588pub(crate) fn js_space(character: char) -> bool {
594 matches!(
595 character,
596 '\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'
597 ..='\u{200a}'
598 | '\u{2028}'
599 | '\u{2029}'
600 | '\u{202f}'
601 | '\u{205f}'
602 | '\u{3000}'
603 | '\u{feff}'
604 )
605}
606
607fn is_decimal_literal(body: &str) -> bool {
611 let bytes = body.as_bytes();
612 let mut index = 0;
613 let mut integral = 0;
614 while index < bytes.len() && bytes[index].is_ascii_digit() {
615 index += 1;
616 integral += 1;
617 }
618 let mut fractional = 0;
619 if index < bytes.len() && bytes[index] == b'.' {
620 index += 1;
621 while index < bytes.len() && bytes[index].is_ascii_digit() {
622 index += 1;
623 fractional += 1;
624 }
625 }
626 if integral == 0 && fractional == 0 {
627 return false;
628 }
629 if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
630 index += 1;
631 if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
632 index += 1;
633 }
634 let mut exponent = 0;
635 while index < bytes.len() && bytes[index].is_ascii_digit() {
636 index += 1;
637 exponent += 1;
638 }
639 if exponent == 0 {
640 return false;
641 }
642 }
643 index == bytes.len()
644}
645
646pub(crate) fn core_number(text: &str) -> Option<f64> {
653 if let Some(digits) = text.strip_prefix("0o") {
654 if !digits.is_empty() && digits.bytes().all(|b| (b'0'..=b'7').contains(&b)) {
655 return Some(text::radix_to_f64(digits, 8));
656 }
657 return None;
658 }
659 if let Some(digits) = text.strip_prefix("0x") {
660 if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_hexdigit()) {
661 return Some(text::radix_to_f64(digits, 16));
662 }
663 return None;
664 }
665 let body = text.strip_prefix(['-', '+']).unwrap_or(text);
666 let bytes = body.as_bytes();
667 let mut index = 0;
668 let digits = |index: &mut usize| {
669 let from = *index;
670 while *index < bytes.len() && bytes[*index].is_ascii_digit() {
671 *index += 1;
672 }
673 *index - from
674 };
675 if bytes.first() == Some(&b'.') {
676 index = 1;
677 if digits(&mut index) == 0 {
678 return None;
679 }
680 } else {
681 if digits(&mut index) == 0 {
682 return None;
683 }
684 if bytes.get(index) == Some(&b'.') {
685 index += 1;
686 digits(&mut index);
687 }
688 }
689 if matches!(bytes.get(index), Some(b'e' | b'E')) {
690 index += 1;
691 if matches!(bytes.get(index), Some(b'-' | b'+')) {
692 index += 1;
693 }
694 if digits(&mut index) == 0 {
695 return None;
696 }
697 }
698 if index != bytes.len() {
699 return None;
700 }
701 js_to_number(text)
702}
703
704pub(crate) fn parse_int(text: &str) -> f64 {
708 let trimmed = text.trim_start_matches(js_space);
709 let bytes = trimmed.as_bytes();
710 let mut index = 0;
711 if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
712 index += 1;
713 }
714 let start = index;
715 while index < bytes.len() && bytes[index].is_ascii_digit() {
716 index += 1;
717 }
718 if index == start {
719 return f64::NAN;
720 }
721 trimmed[..index].parse::<f64>().unwrap_or(f64::NAN)
722}
723
724pub(crate) fn parse_float(text: &str) -> f64 {
727 let trimmed = text.trim_start_matches(js_space);
728 let bytes = trimmed.as_bytes();
729 let mut index = 0;
730 if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
731 index += 1;
732 }
733 if trimmed[index..].starts_with("Infinity") {
734 return if bytes.first() == Some(&b'-') {
735 f64::NEG_INFINITY
736 } else {
737 f64::INFINITY
738 };
739 }
740 let mut digits = 0;
741 while index < bytes.len() && bytes[index].is_ascii_digit() {
742 index += 1;
743 digits += 1;
744 }
745 if index < bytes.len() && bytes[index] == b'.' {
746 index += 1;
747 while index < bytes.len() && bytes[index].is_ascii_digit() {
748 index += 1;
749 digits += 1;
750 }
751 }
752 if digits == 0 {
753 return f64::NAN;
754 }
755 let mantissa_end = index;
756 if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
757 let mut probe = index + 1;
758 if probe < bytes.len() && (bytes[probe] == b'+' || bytes[probe] == b'-') {
759 probe += 1;
760 }
761 let exponent_start = probe;
762 while probe < bytes.len() && bytes[probe].is_ascii_digit() {
763 probe += 1;
764 }
765 if probe > exponent_start {
766 index = probe;
767 }
768 }
769 trimmed[..index.max(mantissa_end)]
770 .parse::<f64>()
771 .unwrap_or(f64::NAN)
772}
773
774pub(crate) fn parse_int_16(text: &str) -> f64 {
782 let trimmed = text.trim_start_matches(js_space);
783 let bytes = trimmed.as_bytes();
784 let mut index = 0;
785 let negative = bytes.first() == Some(&b'-');
786 if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
787 index += 1;
788 }
789 if bytes.len() > index + 1
791 && bytes[index] == b'0'
792 && (bytes[index + 1] == b'x' || bytes[index + 1] == b'X')
793 {
794 index += 2;
795 }
796 let start = index;
797 let mut value = 0f64;
798 while index < bytes.len() && bytes[index].is_ascii_hexdigit() {
799 value = value * 16.0 + f64::from((bytes[index] as char).to_digit(16).expect("hex digit"));
800 index += 1;
801 }
802 if index == start {
803 return f64::NAN;
804 }
805 if negative {
806 -value
807 } else {
808 value
809 }
810}
811
812pub(crate) fn to_uint16(number: f64) -> u32 {
816 if !number.is_finite() {
817 return 0;
818 }
819 let truncated = number.trunc();
820 let wrapped = truncated.rem_euclid(65536.0);
821 wrapped as u32
822}
823
824pub(crate) fn from_code_point(number: f64) -> Option<u32> {
829 if !number.is_finite() || number.trunc() != number {
830 return None;
831 }
832 if !(0.0..=1_114_111.0).contains(&number) {
833 return None;
834 }
835 Some(number as u32)
836}
837
838pub(crate) fn yaml_keyword(text: &str, core: bool) -> Option<Value> {
842 Some(match text {
843 "true" | "True" | "TRUE" => Value::Bool(true),
844 "false" | "False" | "FALSE" => Value::Bool(false),
845 "yes" | "Yes" | "YES" | "on" | "On" | "ON" if !core => Value::Bool(true),
846 "no" | "No" | "NO" | "off" | "Off" | "OFF" if !core => Value::Bool(false),
847 "null" | "Null" | "NULL" | "~" => Value::Null,
848 ".inf" | ".Inf" | ".INF" | "+.inf" | "+.Inf" | "+.INF" => Value::Number(f64::INFINITY),
849 "-.inf" | "-.Inf" | "-.INF" => Value::Number(f64::NEG_INFINITY),
850 ".nan" | ".NaN" | ".NAN" => Value::Number(f64::NAN),
851 _ => return None,
852 })
853}
854
855fn extract_key(token: &Token, context: &Context) -> Value {
862 if token.tin == TIN_VL {
863 if let Value::Object(map) = &token.val {
864 if let Some(Value::String(name)) = map.get("__yamlAlias") {
865 return match state::map_get(context, state::ANCHORS, name) {
866 Some(value) if !matches!(value, Value::Undefined) => value,
867 _ => Value::String(format!("*{name}")),
868 };
869 }
870 }
871 }
872 if token.tin == TIN_ST || token.tin == TIN_TX {
873 token.val.clone()
874 } else {
875 Value::String(token.src.as_str().to_string())
876 }
877}
878
879fn token_key(rule: &Rule, index: usize, context: &Context) -> Value {
880 let token = if index == 0 { rule.o0() } else { rule.o1() };
881 token.map_or(Value::Undefined, |token| extract_key(token, context))
882}
883
884fn counter(rule: &Rule, name: &str) -> Option<i32> {
885 rule.n.get(name).copied()
886}
887
888fn token_number(value: &Value) -> Option<f64> {
889 match value {
890 Value::Number(number) => Some(*number),
891 _ => None,
892 }
893}
894
895fn entry_column(src: source::Src<'_>, at: usize) -> usize {
902 let at = src.clamp(at);
903 let mut line = src.line_start(at);
904 if line == 0 && src.starts_with(0, lex::BOM_TEXT) {
905 line = lex::BOM_TEXT.len();
906 }
907 let (mut column, mut index) = (0, line);
908 while index < at && src.is(index, b' ') {
909 column += 1;
910 index += 1;
911 }
912 while index < at && src.is(index, b'-') && matches!(src.at(index + 1), 0x20 | 0x09) {
913 column += 2;
914 index += 2;
915 while index < at && src.is(index, b' ') {
916 column += 1;
917 index += 1;
918 }
919 }
920 column
921}
922
923fn entry_map_in(rule: &Rule) -> Option<f64> {
928 let parent = rule.parent_rule.as_ref()?;
929 if parent.name.as_str() != "yamlElemPair" {
930 return None;
931 }
932 match rule.k.get("yamlMapIn") {
933 Some(Value::Number(column)) => Some(*column),
934 _ => None,
935 }
936}
937
938fn parent_name(rule: &Rule) -> Option<&str> {
940 rule.parent_rule.as_ref().map(|parent| parent.name.as_str())
941}
942
943fn alias_name(value: &Value) -> Option<&str> {
946 match value {
947 Value::Object(map) => match map.get("__yamlAlias") {
948 Some(Value::String(name)) => Some(name.as_str()),
949 _ => None,
950 },
951 _ => None,
952 }
953}
954
955fn recursive_alias(token: Option<&Token>, context: &Context) -> Option<Token> {
960 let token = token?;
961 if token.tin != TIN_VL {
962 return None;
963 }
964 let name = alias_name(&token.val)?;
965 if !state::anchor_open(context, name) {
966 return None;
967 }
968 let mut bad = token.clone();
969 bad.bad(RECURSIVE_ALIAS);
970 Some(bad)
971}
972
973fn first_key_column(context: &mut Context) -> i32 {
980 let Some(token) = context.t0() else {
981 return 0;
982 };
983 if !matches!(token.tin, TIN_TX | TIN_NR | TIN_ST | TIN_VL) {
984 return 0;
985 }
986 let at = token.site.si;
987 let windowed = context.source.is_empty();
988 let kept = source::Kept::load(context, windowed);
989 let touched = std::cell::Cell::new(false);
990 let column = {
991 let src = kept.src(&context.source, &touched);
992 let at = src.clamp(at);
993 let line = lex::line_start_of(src, at);
994 let mut index = line;
995 while index < at && src.is(index, b' ') {
996 index += 1;
997 }
998 let column = src.slice(line, index).len();
999 while index < at && (src.is(index, b'&') || src.is(index, b'!')) {
1000 while index < at && !lex::blank(src.at(index)) {
1001 index += 1;
1002 }
1003 while index < at && lex::blank(src.at(index)) {
1004 index += 1;
1005 }
1006 }
1007 if index == at {
1008 i32::try_from(column).unwrap_or(0)
1009 } else {
1010 0
1011 }
1012 };
1013 kept.store(context);
1014 column
1015}
1016
1017fn t0_number(context: &Context) -> Option<f64> {
1018 context.t0().and_then(|token| token_number(&token.val))
1019}
1020
1021fn register_refs(parser: &mut Tabnas) {
1022 parser.imperative_lex_match_ref(lex::MATCHER, lex::yaml_matcher);
1024 parser.imperative_lex_match_ref(text::MATCHER, text::yaml_text);
1025
1026 parser.alt_condition("@val-indent-deeper", |rule, context| {
1028 let Some(t0) = t0_number(context) else {
1029 return false;
1030 };
1031 if let Some(Value::Number(list_in)) = rule.k.get("yamlListIn") {
1032 if t0 <= *list_in {
1033 return false;
1034 }
1035 }
1036 if entry_map_in(rule).is_some_and(|map_in| t0 <= map_in) {
1037 return false;
1038 }
1039 match rule.k.get("yamlIn") {
1040 Some(Value::Number(parent)) => t0 > *parent,
1041 _ => true,
1042 }
1043 });
1044 parser.alt_condition("@val-indent-eq-parent", |rule, context| {
1051 let Some(t0) = t0_number(context) else {
1052 return false;
1053 };
1054 match parent_name(rule) {
1055 Some("yamlElemPair") => {
1056 matches!(rule.k.get("yamlMapIn"), Some(Value::Number(map_in)) if t0 == *map_in)
1057 }
1058 Some("yamlBlockList" | "yamlBlockElem") => false,
1059 _ => matches!(rule.k.get("yamlIn"), Some(Value::Number(parent)) if t0 == *parent),
1060 }
1061 });
1062 parser.alt_condition("@val-not-pair-value", |rule, _context| {
1066 !matches!(parent_name(rule), Some("pair" | "yamlElemPair"))
1067 });
1068 parser.alt_condition("@t0-eq-in", |rule, context| {
1069 matches!((t0_number(context), counter(rule, "in")),
1070 (Some(t0), Some(indent)) if t0 == f64::from(indent))
1071 });
1072 parser.alt_condition("@t0-le-in", |rule, context| {
1073 matches!((t0_number(context), counter(rule, "in")),
1074 (Some(t0), Some(indent)) if t0 <= f64::from(indent))
1075 });
1076 parser.alt_condition("@t0-lt-in", |rule, context| {
1077 matches!((t0_number(context), counter(rule, "in")),
1078 (Some(t0), Some(indent)) if t0 < f64::from(indent))
1079 });
1080 parser.alt_condition("@o0-eq-in", |rule, _context| {
1081 let open = rule.o0().and_then(|token| token_number(&token.val));
1082 matches!((open, counter(rule, "in")),
1083 (Some(value), Some(indent)) if value == f64::from(indent))
1084 });
1085 parser.alt_condition("@t0-eq-map-in", |rule, context| {
1086 matches!((t0_number(context), rule.k.get("yamlMapIn")),
1087 (Some(t0), Some(Value::Number(indent))) if t0 == *indent)
1088 });
1089
1090 parser.action_with_context("@val-set-in-from-o0", |rule, _context| {
1092 if let Some(value) = rule.o0().and_then(|token| token_number(&token.val)) {
1093 rule.n_mut().insert("in".to_string(), value as i32);
1094 }
1095 Ok(())
1096 });
1097 parser.action_with_context("@val-set-null", |rule, _context| {
1098 set_node(rule, Value::Null);
1099 Ok(())
1100 });
1101 parser.action_with_context("@val-set-el-in", |rule, _context| {
1102 let column = rule.o0().map_or(0, |token| token.site.ci);
1103 rule.n_mut().insert("in".to_string(), column as i32 - 1);
1104 Ok(())
1105 });
1106 parser.action_with_context("@indent-plain-value", |rule, _context| {
1110 let node = rule
1111 .o0()
1112 .map_or(Value::Undefined, |token| token.val.clone());
1113 set_node(rule, node);
1114 Ok(())
1115 });
1116 parser.action_with_context("@set-map-in", |rule, context| {
1117 let block = matches!(rule.name.as_str(), "yamlBlockList" | "yamlBlockElem");
1124 let indent = match rule.o0() {
1125 Some(token) if block => {
1126 let windowed = context.source.is_empty();
1129 let kept = source::Kept::load(context, windowed);
1130 let touched = std::cell::Cell::new(false);
1131 let column = entry_column(kept.src(&context.source, &touched), token.site.si);
1132 kept.store(context);
1133 column as f64
1134 }
1135 _ => counter(rule, "in").map_or(f64::NAN, |value| f64::from(value + 2)),
1136 };
1137 rule.k_mut()
1138 .insert("yamlMapIn".to_string(), Value::Number(indent));
1139 Ok(())
1140 });
1141 parser.action_with_match_ref("@elem-key", |rule, context, _alt| {
1144 if let Some(bad) = recursive_alias(rule.o0(), context) {
1145 return Ok(Some(bad));
1146 }
1147 let key = token_key(rule, 0, context);
1148 rule.u_mut().insert("key".to_string(), key);
1149 Ok(None)
1150 });
1151 parser.action_with_match_ref("@implicit-null-pair", |rule, context, _alt| {
1152 if let Some(bad) = recursive_alias(rule.o0(), context) {
1153 return Ok(Some(bad));
1154 }
1155 let key = token_key(rule, 0, context);
1156 rule.u_mut().insert("key".to_string(), key.clone());
1157 store_member(rule, context, string_of(&key), Value::Null);
1158 Ok(None)
1159 });
1160 parser.action_with_match_ref("@qm-pairkey", |rule, context, _alt| {
1161 if let Some(bad) = recursive_alias(rule.o1(), context) {
1162 return Ok(Some(bad));
1163 }
1164 let key = token_key(rule, 1, context);
1165 rule.u_mut().insert("key".to_string(), key);
1166 Ok(None)
1167 });
1168 parser.action_with_match_ref("@qm-implicit-null-pair", |rule, context, _alt| {
1169 if let Some(bad) = recursive_alias(rule.o1(), context) {
1170 return Ok(Some(bad));
1171 }
1172 let key = token_key(rule, 1, context);
1173 rule.u_mut().insert("key".to_string(), key.clone());
1174 store_member(rule, context, string_of(&key), Value::Null);
1175 Ok(None)
1176 });
1177
1178 parser.action_with_context("@yaml-apply-directive", |rule, context| {
1180 apply_directive(rule, context);
1181 Ok(())
1182 });
1183 parser.action_with_context("@yaml-mark-explicit", |_rule, context| {
1184 ensure_meta(context);
1185 set_meta_flag(context, "explicit", true);
1186 Ok(())
1187 });
1188 parser.action_with_context("@yaml-accum-doc", |rule, context| {
1189 accumulate_document(rule, context);
1190 Ok(())
1191 });
1192 parser.action_with_context("@yaml-accum-and-directive", |rule, context| {
1193 accumulate_document(rule, context);
1194 apply_directive(rule, context);
1195 Ok(())
1196 });
1197 parser.action_with_context("@yaml-finalize-stream", |rule, context| {
1198 finalize_stream(rule, context);
1199 Ok(())
1200 });
1201}
1202
1203fn ensure_meta(context: &mut Context) {
1208 if context.u.get(state::CUR_META).is_none() {
1209 let mut meta = IndexMap::new();
1210 meta.insert("directives".to_string(), Value::array(Vec::new()));
1211 meta.insert("explicit".to_string(), Value::Bool(false));
1212 meta.insert("ended".to_string(), Value::Bool(false));
1213 context
1214 .u
1215 .insert(state::CUR_META.to_string(), Value::object(meta));
1216 }
1217}
1218
1219fn set_meta_flag(context: &mut Context, field: &str, value: bool) {
1220 ensure_meta(context);
1221 state::map_set(
1222 context,
1223 state::CUR_META,
1224 field.to_string(),
1225 Value::Bool(value),
1226 );
1227}
1228
1229fn flush_meta(context: &mut Context, ended: bool) {
1230 ensure_meta(context);
1231 if ended {
1232 set_meta_flag(context, "ended", true);
1233 }
1234 let meta = context
1235 .u
1236 .shift_remove(state::CUR_META)
1237 .unwrap_or(Value::Undefined);
1238 state::list_push(context, state::METAS, meta);
1239}
1240
1241fn apply_directive(rule: &mut Rule, context: &mut Context) {
1242 let source = rule.o0().map_or(String::new(), |token| {
1243 let src = token.src.as_str();
1244 if src.is_empty() {
1245 match &token.val {
1246 Value::String(text) => text.clone(),
1247 _ => String::new(),
1248 }
1249 } else {
1250 src.to_string()
1251 }
1252 });
1253 if let Some((handle, prefix)) = tag_directive(&source) {
1254 state::map_set(context, state::TAG_HANDLES, handle, Value::String(prefix));
1255 }
1256 ensure_meta(context);
1257 let mut directives = match state::map_get(context, state::CUR_META, "directives") {
1258 Some(Value::Array(items)) => (*items).clone(),
1259 _ => Vec::new(),
1260 };
1261 directives.push(Value::String(source));
1262 state::map_set(
1263 context,
1264 state::CUR_META,
1265 "directives".to_string(),
1266 Value::array(directives),
1267 );
1268}
1269
1270fn tag_directive(source: &str) -> Option<(String, String)> {
1276 let rest = source.strip_prefix("%TAG")?;
1277 if !rest.starts_with(js_space) {
1278 return None;
1279 }
1280 let mut fields = rest.split(js_space).filter(|field| !field.is_empty());
1281 let handle = fields.next()?;
1282 let prefix = fields.next()?;
1283 Some((handle.to_string(), prefix.to_string()))
1284}
1285
1286fn child_document(rule: &Rule) -> Option<Value> {
1287 (!rule.child_node.is_undefined()).then(|| rule.child_node.clone())
1288}
1289
1290fn accumulate_document(rule: &mut Rule, context: &mut Context) {
1291 let value = child_document(rule).unwrap_or(Value::Null);
1292 state::list_push(context, state::DOCS, value);
1293 let ended = rule.c0().is_some_and(|token| token.name.as_ref() == "#DE");
1295 flush_meta(context, ended);
1296}
1297
1298fn finalize_stream(rule: &mut Rule, context: &mut Context) {
1299 if let Some(value) = child_document(rule) {
1300 state::list_push(context, state::DOCS, value);
1301 flush_meta(context, false);
1302 } else if context.u.get(state::CUR_META).is_some() {
1303 state::list_push(context, state::DOCS, Value::Null);
1308 flush_meta(context, false);
1309 }
1310
1311 let documents = state::list_all(context, state::DOCS);
1312 let content = match documents.len() {
1313 0 => Value::Undefined,
1314 1 => documents[0].clone(),
1315 _ => Value::array(documents),
1316 };
1317
1318 let want_meta = matches!(
1319 context
1320 .options
1321 .plugin
1322 .get(PLUGIN_NAME)
1323 .and_then(|options| match options {
1324 Value::Object(map) => map.get("meta").cloned(),
1325 _ => None,
1326 }),
1327 Some(Value::Bool(true))
1328 );
1329
1330 let result = if want_meta {
1331 let metas = state::list_all(context, state::METAS);
1332 let meta = match metas.len() {
1333 0 => Value::Undefined,
1334 1 => metas[0].clone(),
1335 _ => Value::array(metas),
1336 };
1337 let mut wrapper = IndexMap::new();
1338 wrapper.insert("meta".to_string(), meta);
1339 wrapper.insert("content".to_string(), content);
1340 Value::object(wrapper)
1341 } else {
1342 content
1343 };
1344
1345 *rule.node.borrow_mut() = result;
1349}
1350
1351fn wire_rules(parser: &mut Tabnas) {
1356 parser.define_rule("val", |spec| {
1357 spec.add_ao(|rule, context| {
1358 let pending = state::list_take(context, state::PENDING_ANCHORS);
1359 if !pending.is_empty() {
1360 let open_node = match &*rule.node.borrow() {
1365 node if is_container(node) => Value::Undefined,
1366 node => node.clone(),
1367 };
1368 name_anchors(rule, &pending, &open_node);
1369 for anchor in &pending {
1370 if let Value::Object(entry) = anchor {
1371 if let Some(Value::String(name)) = entry.get("n") {
1372 state::hold_anchor(context, name, 1.0);
1373 }
1374 }
1375 }
1376 rule.u_mut()
1377 .insert("yamlAnchors".to_string(), Value::array(pending));
1378 rule.u_mut()
1379 .insert("yamlAnchorOpenNode".to_string(), open_node);
1380 state::hold_pruning(context, 1.0);
1384 }
1385 let yaml_alt = matches!(
1398 rule.o0().map(|token| token.name.as_ref()),
1399 Some("#EL" | "#IN")
1400 );
1401 if yaml_alt && is_container(&rule.node.borrow()) {
1402 set_node(rule, Value::Undefined);
1403 }
1404 });
1405 spec.add_bc(|rule, _context| {
1406 if matches!(rule.u.get("yamlEmpty"), Some(Value::Bool(true))) {
1407 set_node(rule, Value::Undefined);
1408 }
1409 });
1410 spec.add_ac_with_state(Arc::new(|rule, context, _next, _out| {
1411 Ok(close_val(rule, context))
1412 }));
1413 });
1414
1415 parser.define_rule("indent", |spec| {
1416 spec.add_bc(|rule, _context| {
1417 if !rule.child_node.is_undefined() {
1418 let child = rule.child_node.clone();
1419 set_node(rule, child);
1420 }
1421 });
1422 });
1423
1424 parser.define_rule("yamlBlockList", |spec| {
1425 spec.add_bo(|rule, _context| {
1426 set_node(rule, Value::array(Vec::new()));
1431 set_indent_key(rule, "yamlListIn");
1432 });
1433 spec.add_bc(|rule, _context| {
1434 let value = if rule.child_node.is_undefined() {
1435 Value::Null
1436 } else {
1437 rule.child_node.clone()
1438 };
1439 list_push(&mut rule.node.borrow_mut(), value);
1440 });
1441 });
1442
1443 parser.define_rule("yamlBlockElem", |spec| {
1444 spec.add_bc(|rule, _context| {
1445 let value = if rule.child_node.is_undefined() {
1446 Value::Null
1447 } else {
1448 rule.child_node.clone()
1449 };
1450 list_push(&mut rule.node.borrow_mut(), value);
1451 });
1452 });
1453
1454 parser.define_rule("list", |spec| {
1455 spec.add_bo(|rule, _context| {
1456 set_indent_key(rule, "yamlListIn");
1457 if rule
1463 .parent_rule
1464 .as_ref()
1465 .is_some_and(|parent| parent.name.as_ref() == "indent")
1466 {
1467 set_node(rule, Value::array(Vec::new()));
1468 }
1469 });
1470 });
1471
1472 parser.define_rule("pair", |spec| {
1478 spec.add_ao_with_state(Arc::new(|rule, context, _next, _out| {
1479 let key = match rule.o0() {
1480 Some(token) if token.name.as_ref() == "#QM" => rule.o1(),
1481 other => other,
1482 };
1483 if let Some(bad) = recursive_alias(key, context) {
1484 return Ok(Some(bad));
1485 }
1486 hold_merge(rule, context);
1487 Ok(None)
1488 }));
1489 spec.add_bc(|rule, context| {
1490 note_literal_merge_key(rule, context);
1491 });
1492 spec.add_ac(|rule, context| {
1493 release_merge(rule, context);
1494 });
1495 });
1496
1497 parser.define_rule("map", |spec| {
1498 spec.add_bo(|rule, context| {
1499 if counter(rule, "in").is_none() {
1500 let column = first_key_column(context);
1506 rule.n_mut().insert("in".to_string(), column);
1507 }
1508 set_indent_key(rule, "yamlIn");
1509 });
1510 spec.add_ac(|rule, context| {
1511 if !state::map_take(context, state::LITERAL_MERGE, &cell_address(rule)) {
1512 for (key, source) in apply_merge_keys(rule) {
1520 rule.n_mut().insert(format!("<<{key}"), source);
1521 }
1522 }
1523 });
1524 });
1525
1526 parser.define_rule("yamlElemMap", |spec| {
1530 spec.add_bo(|rule, _context| {
1531 set_node(rule, Value::object(IndexMap::new()));
1532 });
1533 });
1534
1535 parser.define_rule("yamlElemPair", |spec| {
1536 spec.add_bc(|rule, context| {
1537 store_elem_pair(rule, context);
1538 });
1539 });
1540}
1541
1542fn close_val(rule: &mut Rule, context: &mut Context) -> Option<Token> {
1547 let alias = alias_name(&rule.node.borrow()).map(str::to_string);
1548 if let Some(name) = alias {
1549 if state::anchor_open(context, &name) {
1550 let node = rule.node.borrow().clone();
1553 let own = rule.o0().filter(|token| token.val == node).cloned();
1554 let child = rule
1555 .child_rule
1556 .as_ref()
1557 .and_then(|child| child.o.first().filter(|token| token.val == node).cloned());
1558 let mut token = own.or(child).or_else(|| rule.o0().cloned())?;
1559 token.bad(RECURSIVE_ALIAS);
1560 return Some(token);
1561 }
1562 let resolved =
1563 state::map_get(context, state::ANCHORS, &name).map_or(Value::Undefined, |value| {
1564 if is_container(&value) {
1565 deep_copy(&value)
1566 } else {
1567 value
1568 }
1569 });
1570 set_node(rule, resolved);
1571 }
1572
1573 let Some(Value::Array(anchors)) = rule.u.get("yamlAnchors").cloned() else {
1574 return None;
1575 };
1576 let open_node = rule
1577 .u
1578 .get("yamlAnchorOpenNode")
1579 .cloned()
1580 .unwrap_or(Value::Undefined);
1581 let node = rule.node.borrow().clone();
1582 for anchor in anchors.iter() {
1583 let Value::Object(entry) = anchor else {
1584 continue;
1585 };
1586 let inline = matches!(entry.get("i"), Some(Value::Bool(true)));
1587 let Some(Value::String(name)) = entry.get("n") else {
1588 continue;
1589 };
1590 if inline
1594 && !matches!(open_node, Value::Undefined | Value::Null)
1595 && !is_container(&open_node)
1596 && is_container(&node)
1597 {
1598 continue;
1599 }
1600 let value = if is_container(&node) {
1601 deep_copy(&node)
1602 } else {
1603 node.clone()
1604 };
1605 state::map_set(context, state::ANCHORS, name.clone(), value);
1606 }
1607 for anchor in anchors.iter() {
1609 if let Value::Object(entry) = anchor {
1610 if let Some(Value::String(name)) = entry.get("n") {
1611 state::hold_anchor(context, name, -1.0);
1612 }
1613 }
1614 }
1615 state::hold_pruning(context, -1.0);
1617 None
1618}
1619
1620fn set_indent_key(rule: &mut Rule, name: &str) {
1625 let indent =
1626 counter(rule, "in").map_or(Value::Undefined, |value| Value::Number(f64::from(value)));
1627 rule.k_mut().insert(name.to_string(), indent);
1628}
1629
1630fn store_elem_pair(rule: &mut Rule, context: &mut Context) {
1631 let Some(key) = rule.u.get("key").cloned() else {
1632 return;
1633 };
1634 if matches!(key, Value::Null | Value::Undefined) {
1635 return;
1636 }
1637 let child = if rule.child_node.is_undefined() {
1642 Value::Null
1643 } else {
1644 rule.child_node.clone()
1645 };
1646 store_member(rule, context, string_of(&key), child);
1647}
1648
1649fn name_anchors(rule: &mut Rule, anchors: &[Value], open_node: &Value) {
1659 let scalar = !matches!(open_node, Value::Undefined | Value::Null) && !is_container(open_node);
1660 let Ok(instance) = i32::try_from(rule.i) else {
1663 return;
1664 };
1665 for anchor in anchors {
1666 let Value::Object(entry) = anchor else {
1667 continue;
1668 };
1669 let inline = matches!(entry.get("i"), Some(Value::Bool(true)));
1670 let Some(Value::String(name)) = entry.get("n") else {
1671 continue;
1672 };
1673 if inline && scalar {
1674 continue;
1675 }
1676 rule.n_mut().insert(format!("&{name}"), instance);
1677 rule.n_mut().insert("yamlAnchored".to_string(), instance);
1678 }
1679}
1680
1681fn hold_merge(rule: &mut Rule, context: &mut Context) {
1686 let token = match rule.o0() {
1687 Some(token) if token.name.as_ref() == "#QM" => rule.o1(),
1688 other => other,
1689 };
1690 let plain = token.is_some_and(|token| token.tin != TIN_ST);
1691 if plain && matches!(rule.u.get("key"), Some(Value::String(key)) if key == "<<") {
1692 rule.u_mut()
1693 .insert("yamlMergeHold".to_string(), Value::Bool(true));
1694 state::hold_pruning(context, 1.0);
1695 }
1696}
1697
1698fn release_merge(rule: &mut Rule, context: &mut Context) {
1700 if matches!(rule.u.get("yamlMergeHold"), Some(Value::Bool(true))) {
1701 rule.u_mut()
1702 .insert("yamlMergeHold".to_string(), Value::Bool(false));
1703 state::hold_pruning(context, -1.0);
1704 }
1705}
1706
1707fn note_literal_merge_key(rule: &Rule, context: &mut Context) {
1711 let token = match rule.o0() {
1712 Some(token) if token.name.as_ref() == "#QM" => rule.o1(),
1713 other => other,
1714 };
1715 let quoted = token.is_some_and(|token| token.tin == TIN_ST);
1716 if quoted && matches!(rule.u.get("key"), Some(Value::String(key)) if key == "<<") {
1717 state::map_set(
1718 context,
1719 state::LITERAL_MERGE,
1720 cell_address(rule),
1721 Value::Bool(true),
1722 );
1723 }
1724}
1725
1726fn cell_address(rule: &Rule) -> String {
1730 format!("{:p}", Rc::as_ptr(&rule.node))
1731}
1732
1733fn apply_merge_keys(rule: &mut Rule) -> Vec<(String, i32)> {
1740 let mut merged = Vec::new();
1741 let mut node = rule.node.borrow_mut();
1742 let Some(entries) = map_entries(&node) else {
1743 return merged;
1744 };
1745 let Some(merge) = entries.get("<<").cloned() else {
1746 return merged;
1747 };
1748 let sources = match &merge {
1749 Value::Array(items) => (**items).clone(),
1750 Value::ListRef(list) => list.value.clone(),
1751 other => vec![other.clone()],
1752 };
1753 match &mut *node {
1754 Value::Object(map) => {
1755 Arc::make_mut(map).shift_remove("<<");
1756 }
1757 Value::MapRef(map) => {
1758 Arc::make_mut(map).value.shift_remove("<<");
1759 }
1760 _ => {}
1761 }
1762 let mut number = 0;
1763 for source in sources {
1764 let Some(source_entries) = map_entries(&source) else {
1765 continue;
1766 };
1767 number += 1;
1768 let additions: Vec<(String, Value)> = source_entries
1769 .iter()
1770 .filter(|(key, _)| {
1771 map_entries(&node).is_some_and(|entries| !entries.contains_key(*key))
1772 })
1773 .map(|(key, value)| (key.clone(), value.clone()))
1774 .collect();
1775 for (key, value) in additions {
1776 merged.push((key.clone(), number));
1777 map_insert(&mut node, key, value);
1778 }
1779 }
1780 merged
1781}
1782
1783fn options_document() -> serde_json::Value {
1791 json!({
1792 "rule": {
1793 "stream": {
1794 "open": [
1795 { "s": "#DR", "a": "@yaml-apply-directive", "r": "stream", "g": "yaml" },
1797 { "s": "#DS", "a": "@yaml-mark-explicit", "p": "val", "g": "yaml" },
1799 { "s": "#DE", "r": "stream", "g": "yaml" },
1802 { "s": "#ZZ", "b": 1, "g": "yaml" },
1804 { "p": "val", "g": "yaml" }
1806 ],
1807 "close": [
1808 { "s": "#ZZ", "a": "@yaml-finalize-stream", "g": "yaml" },
1809 { "s": "#DR", "a": "@yaml-accum-and-directive", "r": "stream", "g": "yaml" },
1810 { "s": "#DE", "a": "@yaml-accum-doc", "r": "stream", "g": "yaml" },
1811 { "s": "#DS", "b": 1, "a": "@yaml-accum-doc", "r": "stream", "g": "yaml" }
1812 ]
1813 }
1814 },
1815 "options": {
1816 "fixed": { "token": { "#CL": null } },
1819 "ender": ":",
1821 "string": { "chars": "" },
1824 "lex": {
1825 "match": {
1826 "yaml": { "order": 5e5, "make": "@yaml-matcher" },
1829 "yamlText": { "order": 7.5e6, "make": "@yaml-text" }
1832 }
1833 },
1834 "rule": { "start": "stream" },
1837 "error": {
1841 "yaml_undefined_alias": "undefined alias: {src}",
1842 "yaml_recursive_alias": "recursive alias: {src}",
1843 "yaml_tab_indent": "tab in indentation"
1844 },
1845 "hint": {
1846 "yaml_undefined_alias": "\nThe alias {src} names no anchor that occurs before it in the document.\nAn anchor is written &name on the node it names, and an alias can only\nname an anchor defined earlier.",
1847 "yaml_recursive_alias": "\nThe alias {src} names the anchor of a node it is inside, so the node\nwould hold itself. This parser gives a tree, which cannot. Anchor the\npart that repeats, and name that from outside it.",
1848 "yaml_tab_indent": "\nA tab stands in this line's indentation, before a mapping key or a\nsequence entry. YAML indents block structure with spaces alone, so the\nline's depth cannot be read. Indent the line with spaces."
1849 }
1850 }
1851 })
1852}
1853
1854fn integral_numbers(value: serde_json::Value) -> serde_json::Value {
1858 match value {
1859 serde_json::Value::Number(number) => match number.as_f64() {
1860 Some(float) if float.fract() == 0.0 && float.abs() < 9.0e15 => json!(float as i64),
1861 _ => serde_json::Value::Number(number),
1862 },
1863 serde_json::Value::Array(items) => {
1864 serde_json::Value::Array(items.into_iter().map(integral_numbers).collect())
1865 }
1866 serde_json::Value::Object(fields) => serde_json::Value::Object(
1867 fields
1868 .into_iter()
1869 .map(|(key, value)| (key, integral_numbers(value)))
1870 .collect(),
1871 ),
1872 other => other,
1873 }
1874}
1875
1876fn grammar_document() -> Result<serde_json::Value, PluginError> {
1879 let parsed = tabnas_jsonic::parse(GRAMMAR_TEXT)
1880 .map_err(|error| PluginError(format!("yaml: cannot parse the grammar text: {error}")))?;
1881 let document = integral_numbers(parsed.to_json());
1882 if document
1883 .get("rule")
1884 .and_then(serde_json::Value::as_object)
1885 .is_none()
1886 {
1887 return Err(PluginError(
1888 "yaml: the grammar text has no `rule` table".to_string(),
1889 ));
1890 }
1891 Ok(document)
1892}
1893
1894pub fn yaml(parser: &mut Tabnas, options: &YamlOptions) -> Result<(), PluginError> {
1905 if parser.decoration::<bool>(INSTALLED).is_some() && grammar_installed(parser) {
1916 return Ok(());
1917 }
1918 if !parser.rule_names().iter().any(|name| name == "val") {
1922 return Err(PluginError(
1923 "yaml: the jsonic grammar is not installed on this instance; \
1924 install tabnas_jsonic first"
1925 .to_string(),
1926 ));
1927 }
1928 parser.decorate(INSTALLED, true);
1929 parser.set_plugin_options(PLUGIN_NAME, options.to_value());
1930
1931 for name in ["#IN", "#EL", "#QM", "#DS", "#DE", "#DR"] {
1934 parser.token(name);
1935 }
1936
1937 register_refs(parser);
1938
1939 let spec = GrammarSpec::from_value(options_document())
1940 .map_err(|error| PluginError(format!("yaml: invalid option document: {error}")))?;
1941 parser
1942 .grammar(&spec)
1943 .map_err(|error| PluginError(format!("yaml: cannot apply the options: {error}")))?;
1944
1945 let spec = GrammarSpec::from_value(grammar_document()?)
1946 .map_err(|error| PluginError(format!("yaml: invalid grammar document: {error}")))?;
1947 parser
1948 .grammar(&spec)
1949 .map_err(|error| PluginError(format!("yaml: cannot apply the grammar: {error}")))?;
1950
1951 wire_rules(parser);
1952
1953 parser.parse_guard(DEPTH_GUARD, within_depth_limit);
1958 Ok(())
1959}
1960
1961fn grammar_installed(parser: &Tabnas) -> bool {
1967 parser
1968 .rule_names()
1969 .iter()
1970 .any(|name| name == "yamlBlockList")
1971}
1972
1973const DEPTH_LIMIT: usize = 127;
1984
1985const DEPTH_GUARD: &str = "depth";
1993
1994fn is_container_rule(name: &str) -> bool {
2003 matches!(
2004 name,
2005 "map" | "list" | "yamlBlockList" | "yamlBlockElem" | "yamlElemMap" | "yamlElemPair"
2006 )
2007}
2008
2009fn depth(context: &Context) -> usize {
2015 let ancestors = context
2016 .rule_stack
2017 .iter()
2018 .filter(|rule| is_container_rule(&rule.name))
2019 .count();
2020 let current = usize::from(
2021 context
2022 .rule
2023 .as_ref()
2024 .is_some_and(|rule| is_container_rule(&rule.name)),
2025 );
2026 ancestors + current
2027}
2028
2029fn within_depth_limit(context: &Context) -> bool {
2032 depth(context) <= DEPTH_LIMIT
2033}
2034
2035pub fn plugin() -> Plugin {
2048 Plugin::new(PLUGIN_NAME, |parser, options| {
2049 let meta = matches!(
2050 match options {
2051 Value::Object(map) => map.get("meta").cloned(),
2052 _ => None,
2053 },
2054 Some(Value::Bool(true))
2055 );
2056 let schema = schema_option(options)?;
2057 yaml(parser, &YamlOptions { meta, schema })
2058 })
2059 .with_defaults(YamlOptions::default().to_value())
2060}
2061
2062#[must_use]
2076pub fn make_with(options: YamlOptions) -> Tabnas {
2077 let mut parser = tabnas_jsonic::make();
2078 parser
2079 .use_plugin(plugin(), Some(options.to_value()))
2080 .expect("the yaml grammar documents are fixed and valid");
2081 parser
2089 .set_options(|options| options.lex.window = true)
2090 .expect("lex.window sets");
2091 parser
2092}
2093
2094#[must_use]
2104pub fn make() -> Tabnas {
2105 make_with(YamlOptions::default())
2106}
2107
2108pub fn parse(src: &str) -> Result<Value, YamlError> {
2123 static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
2124 DEFAULT.get_or_init(make).parse(src)
2125}
2126
2127#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2129pub struct TranslationPart {
2130 pub entry: &'static str,
2132 pub source: Option<&'static str>,
2134}
2135
2136#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2138pub struct TranslationParts {
2139 pub manifest: &'static str,
2141 pub lift: Option<TranslationPart>,
2143 pub embed: Option<TranslationPart>,
2145 pub render: Option<TranslationPart>,
2147 pub transduce: Option<TranslationPart>,
2150}
2151
2152const TRANSLATION: TranslationParts = TranslationParts {
2153 manifest: include_str!("../translate/manifest.json"),
2154 lift: None,
2155 embed: None,
2156 render: Some(TranslationPart {
2157 entry: "yaml-render",
2158 source: Some(include_str!("../translate/render.alc")),
2159 }),
2160 transduce: Some(TranslationPart {
2161 entry: "yaml-transduce",
2162 source: Some(include_str!("../translate/transduce.alc")),
2163 }),
2164};
2165
2166#[must_use]
2168pub const fn translate() -> Option<TranslationParts> {
2169 Some(TRANSLATION)
2170}
2171
2172pub fn manifest_text() -> &'static str {
2187 TRANSLATION.manifest
2188}
2189
2190pub fn render_text() -> &'static str {
2201 match TRANSLATION.render {
2202 Some(part) => part.source.unwrap_or_default(),
2203 None => "",
2204 }
2205}