use std::cell::Cell;
use tabnas::{Context, Lexer, Point, Rule, Site, Token, Value};
pub(crate) use crate::source::Src;
use crate::source::{self, Kept};
use crate::state;
use crate::text;
pub(crate) const MATCHER: &str = "@yaml-matcher";
pub(crate) struct Tok {
pub(crate) name: &'static str,
pub(crate) val: Value,
pub(crate) src: String,
pub(crate) si: usize,
}
impl Tok {
pub(crate) fn new(
name: &'static str,
val: Value,
src: impl Into<String>,
at: (usize, usize, usize),
) -> Self {
Tok {
name,
val,
src: src.into(),
si: at.0,
}
}
}
pub(crate) struct Act {
pub(crate) si: usize,
pub(crate) token: Option<Tok>,
pub(crate) bad: Option<Bad>,
}
#[derive(Clone, Copy)]
pub(crate) struct Bad {
pub(crate) code: &'static str,
pub(crate) chars: usize,
}
impl Act {
pub(crate) fn still(at: (usize, usize, usize)) -> Self {
Act {
si: at.0,
token: None,
bad: None,
}
}
pub(crate) fn moved(at: (usize, usize, usize), token: Option<Tok>) -> Self {
Act {
si: at.0,
token,
bad: None,
}
}
pub(crate) fn refuse(at: (usize, usize, usize)) -> Self {
Act {
si: at.0,
token: None,
bad: Some(Bad {
code: "unexpected",
chars: 0,
}),
}
}
pub(crate) fn undefined_alias(at: (usize, usize, usize), chars: usize) -> Self {
Act::bad(at, crate::UNDEFINED_ALIAS, chars)
}
pub(crate) fn bad(at: (usize, usize, usize), code: &'static str, chars: usize) -> Self {
Act {
si: at.0,
token: None,
bad: Some(Bad { code, chars }),
}
}
}
#[inline]
pub(crate) fn at(src: Src<'_>, index: usize) -> i32 {
src.at(index)
}
#[inline]
pub(crate) fn is(src: Src<'_>, index: usize, byte: u8) -> bool {
at(src, index) == i32::from(byte)
}
#[inline]
pub(crate) fn blank(value: i32) -> bool {
value == i32::from(b' ') || value == i32::from(b'\t')
}
#[inline]
pub(crate) fn line_end(value: i32) -> bool {
value == i32::from(b'\n') || value == i32::from(b'\r')
}
#[inline]
pub(crate) fn blank_line_end_or_eof(value: i32) -> bool {
blank(value) || line_end(value) || value < 0
}
pub(crate) fn trim_end(text: &str) -> &str {
text.trim_end_matches(crate::js_space)
}
#[inline]
pub(crate) fn floor_boundary(text: &str, index: usize) -> usize {
let mut index = index.min(text.len());
while !text.is_char_boundary(index) {
index -= 1;
}
index
}
pub(crate) fn js_substring(text: &str, from: usize, to: usize) -> &str {
let from = floor_boundary(text, from);
let to = floor_boundary(text, to);
&text[from.min(to)..from.max(to)]
}
pub(crate) fn js_substring_less_one_unit(text: &str, from: usize, to: usize) -> String {
let unit = to.saturating_sub(1);
let end = floor_boundary(text, unit);
let split_astral = unit < text.len()
&& end < unit
&& text[end..]
.chars()
.next()
.is_some_and(|character| character.len_utf8() == 4);
let from = floor_boundary(text, from);
let mut out = text[from.min(end)..from.max(end)].to_string();
if split_astral && from <= end {
out.push('\u{fffd}');
}
out
}
pub(crate) struct Window<'a> {
pub(crate) digits: &'a str,
pub(crate) end: usize,
pub(crate) split_low: Option<u32>,
}
pub(crate) fn take_units(text: &str, from: usize, count: usize) -> Window<'_> {
let from = floor_boundary(text, from);
let tail = &text[from..];
let mut units = 0usize;
let mut offset = 0usize;
for (index, character) in tail.char_indices() {
let width = character.len_utf16();
if units + width > count {
let mut pair = [0u16; 2];
let encoded = character.encode_utf16(&mut pair);
let split_low = (width == 2 && units < count).then(|| u32::from(encoded[1]));
return Window {
digits: &tail[..index],
end: from + index,
split_low,
};
}
units += width;
offset = index + character.len_utf8();
if units == count {
break;
}
}
Window {
digits: &tail[..offset],
end: from + offset,
split_low: None,
}
}
pub(crate) fn advance_cols(
src: Src<'_>,
at: (usize, usize, usize),
count: usize,
) -> (usize, usize, usize) {
let mut end = src.clamp(at.0 + count);
while src.has(end) && !src.is_char_boundary(end) {
end += 1;
}
let columns = src.slice(at.0, end).chars().count();
(end, at.1, at.2 + columns)
}
pub(crate) struct Ready {
act: Act,
token: Option<Token>,
characters: usize,
place: (usize, usize),
}
pub(crate) fn ready(src: Src<'_>, point: &Point, act: Act) -> Ready {
let start = point.site.si;
let start_pos = point.site.pos;
let length = point.len;
let end = src.read_end();
let token = {
act.token.as_ref().map(|token| {
let offset = token.si.clamp(start, end);
let pos = start_pos + src.slice(start, offset).chars().count();
let (ri, ci) = src.row_col(offset);
Token::new(
token.name,
-1,
token.val.clone(),
token.src.as_str(),
Point {
len: length,
site: Site {
si: offset,
pos,
ri,
ci,
},
},
)
})
};
let landed = act.si.clamp(start, end);
let characters = src.slice(start, landed).chars().count();
let place = if act.bad.is_some() {
src.row_col(landed)
} else {
(0, 0)
};
Ready {
act,
token,
characters,
place,
}
}
pub(crate) fn apply(lexer: &mut Lexer<'_>, ready: Ready) -> Option<Token> {
let Ready {
act,
token,
characters,
place,
} = ready;
let at = lexer.point().site.pos + characters;
if characters > 0 {
lexer.advance_chars(characters);
}
if let Some(bad) = act.bad {
let mut refusal = if bad.chars == 0 {
lexer.bad(bad.code)
} else {
lexer.bad_span(bad.code, at, at + bad.chars)
};
refusal.site.ri = place.0;
refusal.site.ci = place.1;
return Some(refusal);
}
token
}
pub(crate) fn yaml_matcher(
lexer: &mut Lexer<'_>,
_rule: &mut Rule,
context: &mut Context,
) -> Option<Token> {
let mut kept = Kept::load(context, lexer.windowed());
kept.extend(lexer);
let point = lexer.point();
let start = point.site.si;
let touched = Cell::new(false);
let again = kept.again(start, source::taken(context));
if again {
kept.restore(context);
} else {
kept.note(start, lexer);
kept.save(context);
}
let flow_from = state::usize_at(context, state::FLOW_POS);
let ready = {
let src = kept.src(lexer.source(), &touched);
if kept.windowed() {
state::update_flow(context, src, start);
}
let (row, column) = src.row_col(start);
let act = decide(src, (start, row, column), context);
let moved = act.token.is_none() && act.bad.is_none() && act.si != start;
state::set_flag(context, state::MOVED, moved);
ready(src, &point, act)
};
if !again {
kept.trim(flow_from);
}
let windowed = kept.windowed();
kept.store(context);
let token = apply(lexer, ready);
if windowed && touched.get() {
lexer.advance_chars(usize::MAX);
}
token
}
fn blank_source(src: Src<'_>) -> bool {
let mut at = 0;
let mut line_start = true;
loop {
if line_start {
let mut q = at;
while src.is(q, b' ') || src.is(q, b'\t') {
q += 1;
}
if src.is(q, b'#') {
while src.has(q) && !line_end(src.at(q)) {
q += 1;
}
if !src.has(q) {
return true;
}
at = q + 1;
continue;
}
}
let Some(character) = src.char_at(at) else {
return true;
};
if !crate::js_space(character) {
return false;
}
at += character.len_utf8();
line_start = matches!(character, '\n' | '\r' | '\u{2028}' | '\u{2029}');
}
}
#[allow(clippy::too_many_lines)]
fn decide(src: Src<'_>, start: (usize, usize, usize), context: &mut Context) -> Act {
if !state::flag(context, state::INIT) {
state::initialise(context);
if blank_source(src) {
return Act::moved(
(src.clamp(usize::MAX), start.1, start.2),
Some(Tok::new("#VL", Value::Null, "", start)),
);
}
}
if state::list_len(context, state::PENDING_TOKENS) > 0 {
if let Some(queued) = state::list_shift(context, state::PENDING_TOKENS) {
return Act::moved(start, Some(decode_token(&queued, start)));
}
}
let first = at(src, start.0);
let mut cursor = start;
if cursor.0 == 0 && src.starts_with(0, BOM_TEXT) {
cursor.0 = BOM.len_utf8();
let here = at(src, cursor.0);
if here == i32::from(b'[') || here == i32::from(b'{') {
let name = flow_punctuation(here).expect("an opener is flow punctuation");
let token = Tok::new(
name,
Value::Undefined,
src.slice(cursor.0, cursor.0 + 1),
cursor,
);
return Act::moved((cursor.0 + 1, cursor.1, cursor.2 + 1), Some(token));
}
if here == i32::from(b'#') {
while src.has(cursor.0) && !line_end(at(src, cursor.0)) {
cursor.0 += 1;
}
}
}
loop {
if !src.has(cursor.0) {
if state::flag(context, state::PENDING_CL) {
state::set_flag(context, state::PENDING_CL, false);
return Act::moved(
cursor,
Some(Tok::new("#CL", Value::Number(1.0), ": ", cursor)),
);
}
if cursor.0 != start.0 && state::flow_depth_at(context, src, cursor.0) == 0 {
return Act::moved(cursor, Some(Tok::new("#ZZ", Value::Undefined, "", cursor)));
}
return Act::refuse(cursor);
}
let fwd = src.from(cursor.0);
if blank(at(fwd, 0)) {
let mut run = 0;
let mut tab = false;
while blank(at(fwd, run)) {
tab |= is(fwd, run, b'\t');
run += 1;
}
let after = at(fwd, run);
if tab && (line_end(after) || after < 0) {
let skip = if !at_line_start(src, cursor.0) {
run
} else if after == i32::from(b'\r') && is(fwd, run + 1, b'\n') {
run + 2
} else if line_end(after) {
run + 1
} else {
run
};
cursor = (cursor.0 + skip, cursor.1, cursor.2);
continue;
}
if tab && at_line_start(src, cursor.0) && block_start_at(src, cursor.0 + run) {
return Act::bad(cursor, TAB_INDENT, run);
}
}
if state::flag(context, state::PENDING_CL) {
state::set_flag(context, state::PENDING_CL, false);
return Act::moved(
cursor,
Some(Tok::new("#CL", Value::Number(1.0), ": ", cursor)),
);
}
if is(fwd, 0, b'*') {
return alias(src, fwd, cursor, context);
}
if is(fwd, 0, b'&') {
match anchor(src, fwd, cursor, context) {
Ok(next) => {
cursor = next;
continue;
}
Err(act) => return *act,
}
}
if is(fwd, 0, b'%') && at_line_start(src, cursor.0) {
let mut pos = 0;
while fwd.has(pos) && !line_end(at(fwd, pos)) {
pos += 1;
}
let text = fwd.slice(0, pos).to_string();
let next = advance_cols(src, cursor, pos);
return Act::moved(
next,
Some(Tok::new("#DR", Value::String(text.clone()), text, cursor)),
);
}
if is(fwd, 0, b'!') && !is(fwd, 1, b'!') && at(fwd, 1) >= 0 {
if is(fwd, 1, b' ') {
let mut val_end = 2;
while fwd.has(val_end) && !line_end(at(fwd, val_end)) {
val_end += 1;
}
let raw = trim_end(fwd.slice(2, val_end)).to_string();
let source = fwd.slice(0, val_end).to_string();
let next = advance_cols(src, cursor, val_end);
return Act::moved(
next,
Some(Tok::new("#TX", Value::String(raw), source, cursor)),
);
}
cursor = local_tag(src, fwd, cursor);
continue;
}
if is(fwd, 0, b'!') && is(fwd, 1, b'!') && is_struct_tag(fwd) {
match struct_tag(src, fwd, cursor) {
Ok(next) => {
cursor = next;
continue;
}
Err(act) => return *act,
}
}
if is(fwd, 0, b'!') && is(fwd, 1, b'!') {
match text::type_tag(src, fwd, cursor, context) {
Ok(next) => {
if next.0 == cursor.0 {
return Act::still(cursor);
}
cursor = next;
continue;
}
Err(act) => return *act,
}
}
if is(fwd, 0, b'?') && blank(at(fwd, 1)) && state::flow_depth_at(context, src, cursor.0) > 0
{
let next = advance_cols(src, cursor, 1);
return Act::moved(next, Some(Tok::new("#QM", Value::Undefined, "?", cursor)));
}
if is(fwd, 0, b'?') && (blank(at(fwd, 1)) || line_end(at(fwd, 1)) || at(fwd, 1) < 0) {
return explicit_key(src, fwd, cursor, context);
}
if at_line_start(src, cursor.0) && is_doc_marker(fwd, 0) {
return doc_marker(src, fwd, cursor);
}
if is(fwd, 0, b'"') {
return double_quoted(src, fwd, cursor);
}
if is(fwd, 0, b'\'') {
return single_quoted(src, fwd, cursor);
}
let digit = |index: usize| at(fwd, index) >= 0 && (at(fwd, index) as u8).is_ascii_digit();
let lead = usize::from(is(fwd, 0, b'+') || is(fwd, 0, b'-'));
if digit(lead) || (is(fwd, lead, b'.') && digit(lead + 1)) {
if let Some(act) = numeric_plain(src, fwd, cursor, context) {
return act;
}
}
if is(fwd, 0, b'-') && blank_line_end_or_eof(at(fwd, 1)) {
let mut next = advance_cols(src, cursor, 1);
if blank(at(fwd, 1)) {
next = advance_cols(src, next, 1);
}
return Act::moved(next, Some(Tok::new("#EL", Value::Undefined, "- ", cursor)));
}
if is(fwd, 0, b':') {
let flow_colon = !blank_line_end_or_eof(at(fwd, 1)) && quoted_before(src, cursor.0);
if blank_line_end_or_eof(at(fwd, 1)) || flow_colon {
let token = Tok::new("#CL", Value::Number(1.0), ": ", cursor);
let next = if blank(at(fwd, 1)) {
(cursor.0 + 1, cursor.1, cursor.2 + 2)
} else if line_end(at(fwd, 1)) {
(cursor.0 + 1, cursor.1, cursor.2)
} else {
(cursor.0 + 1, cursor.1, cursor.2 + 1)
};
return Act::moved(next, Some(token));
}
}
if cursor.0 == start.0 && flow_punctuation(at(fwd, 0)).is_some() {
let name = flow_punctuation(at(fwd, 0)).expect("just tested");
let text = fwd.slice(0, 1);
let token = Tok::new(name, Value::String(text.to_string()), text, cursor);
return Act::moved(advance_cols(src, cursor, 1), Some(token));
}
if line_end(at(fwd, 0)) {
if state::flow_depth_at(context, src, cursor.0) > 0 {
match flow_newline(src, fwd, cursor) {
Ok(next) => {
cursor = next;
continue;
}
Err(act) => return *act,
}
}
match block_newline(src, fwd, cursor, context) {
Ok(next) => {
cursor = next;
continue;
}
Err(act) => return *act,
}
}
if cursor.0 != start.0 && !claimable_after_move(first, at(src, cursor.0)) {
return Act::refuse(cursor);
}
return Act::still(cursor);
}
}
fn dispatch_family(byte: i32) -> Option<u8> {
Some(match byte {
value if value == i32::from(b'{') => 0,
value if value == i32::from(b'}') => 0,
value if value == i32::from(b'[') => 0,
value if value == i32::from(b']') => 0,
value if value == i32::from(b',') => 0,
value if value == i32::from(b'\n') => 1,
value if value == i32::from(b'\r') => 1,
value if value == i32::from(b'#') => 2,
_ => return None,
})
}
fn claimable_after_move(first: i32, here: i32) -> bool {
match dispatch_family(here) {
None => true,
family => dispatch_family(first) == family,
}
}
fn flow_punctuation(byte: i32) -> Option<&'static str> {
Some(match byte {
value if value == i32::from(b'[') => "#OS",
value if value == i32::from(b']') => "#CS",
value if value == i32::from(b'{') => "#OB",
value if value == i32::from(b'}') => "#CB",
value if value == i32::from(b',') => "#CA",
_ => return None,
})
}
pub(crate) const BOM: char = '\u{FEFF}';
pub(crate) const BOM_TEXT: &str = "\u{FEFF}";
pub(crate) const TAB_INDENT: &str = "yaml_tab_indent";
fn yaml_space(value: i32) -> bool {
blank(value) || line_end(value)
}
pub(crate) fn block_start_at(src: Src<'_>, i: usize) -> bool {
let c = at(src, i);
if c < 0 || line_end(c) || c == i32::from(b'#') {
return false;
}
if c == i32::from(b'-') || c == i32::from(b'?') {
let n = at(src, i + 1);
if n < 0 || yaml_space(n) {
return true;
}
}
if c == i32::from(b'"') || c == i32::from(b'\'') {
return quoted_key_at(src, i);
}
if matches!(u8::try_from(c), Ok(b'{' | b'}' | b'[' | b']' | b',')) {
return false;
}
if c == i32::from(b':') && (at(src, i + 1) < 0 || yaml_space(at(src, i + 1))) {
return true;
}
is(src, state::plain_scalar_rest(src, i), b':')
}
fn at_line_start(src: Src<'_>, offset: usize) -> bool {
offset == 0
|| line_end(at(src, offset - 1))
|| (offset == BOM.len_utf8() && src.starts_with(0, BOM_TEXT))
}
pub(crate) fn line_start_of(src: Src<'_>, offset: usize) -> usize {
let mut index = src.line_start(offset);
if index == 0 && src.starts_with(0, BOM_TEXT) {
index = BOM.len_utf8();
}
index
}
fn doc_marker_run(src: Src<'_>, index: usize) -> bool {
let head = at(src, index);
if head != i32::from(b'-') && head != i32::from(b'.') {
return false;
}
at(src, index + 1) == head && at(src, index + 2) == head
}
pub(crate) fn is_doc_marker(src: Src<'_>, index: usize) -> bool {
doc_marker_run(src, index) && blank_line_end_or_eof(at(src, index + 3))
}
pub(crate) fn is_doc_marker_no_tab(src: Src<'_>, index: usize) -> bool {
let after = at(src, index + 3);
doc_marker_run(src, index) && (after == i32::from(b' ') || line_end(after) || after < 0)
}
fn starts_with_at(src: Src<'_>, index: usize, word: &str) -> bool {
word.bytes()
.enumerate()
.all(|(offset, byte)| at(src, index + offset) == i32::from(byte))
}
fn is_struct_tag(fwd: Src<'_>) -> bool {
for name in ["seq", "map", "omap", "set", "pairs", "binary", "ordered"] {
if starts_with_at(fwd, 2, name) {
let after = at(fwd, 2 + name.len());
let word =
after >= 0 && (after as u8).is_ascii_alphanumeric() || after == i32::from(b'_');
if !word {
return true;
}
}
}
if !starts_with_at(fwd, 2, "python/") {
return false;
}
let mut index = "!!python/".len();
while let Some(character) = fwd.char_at(index) {
if crate::js_space(character) {
return false;
}
if character.is_ascii_alphanumeric() || character == '_' {
return true;
}
index += character.len_utf8();
}
false
}
pub(crate) fn encode_token(token: &Tok) -> Value {
let mut map = indexmap::IndexMap::new();
map.insert("n".to_string(), Value::String(token.name.to_string()));
map.insert("v".to_string(), token.val.clone());
map.insert("s".to_string(), Value::String(token.src.clone()));
map.insert("i".to_string(), Value::Number(token.si as f64));
Value::object(map)
}
fn decode_token(value: &Value, fallback: (usize, usize, usize)) -> Tok {
let field = |key: &str| -> Option<Value> {
match value {
Value::Object(map) => map.get(key).cloned(),
_ => None,
}
};
let number = |key: &str, default: usize| -> usize {
match field(key) {
Some(Value::Number(number)) => number.max(0.0) as usize,
_ => default,
}
};
let name: &'static str = match field("n") {
Some(Value::String(name)) => match name.as_str() {
"#CL" => "#CL",
"#IN" => "#IN",
"#VL" => "#VL",
"#TX" => "#TX",
_ => "#TX",
},
_ => "#TX",
};
Tok {
name,
val: field("v").unwrap_or(Value::Undefined),
src: match field("s") {
Some(Value::String(text)) => text,
_ => String::new(),
},
si: number("i", fallback.0),
}
}
fn name_end(fwd: Src<'_>, alias: bool) -> usize {
let mut index = 1;
while fwd.has(index) {
let byte = at(fwd, index);
if blank(byte)
|| line_end(byte)
|| byte == i32::from(b',')
|| byte == i32::from(b'{')
|| byte == i32::from(b'}')
|| byte == i32::from(b'[')
|| byte == i32::from(b']')
{
break;
}
if alias && byte == i32::from(b':') && blank(at(fwd, index + 1)) {
break;
}
index += 1;
}
index
}
fn alias(src: Src<'_>, fwd: Src<'_>, cursor: (usize, usize, usize), context: &mut Context) -> Act {
let end = name_end(fwd, true);
let name = fwd.slice(1, end).to_string();
let source = fwd.slice(0, end).to_string();
if !state::anchor_declared(context, &name) {
return Act::undefined_alias(cursor, source.chars().count());
}
let mut after = end;
while blank(at(fwd, after)) {
after += 1;
}
let is_key = is(fwd, after, b':') && blank_line_end_or_eof(at(fwd, after + 1));
let recorded = state::map_get(context, state::ANCHORS, &name);
let next = advance_cols(src, cursor, end);
if is_key {
if let Some(value) = recorded.clone() {
if !matches!(value, Value::Undefined) {
return Act::moved(
next,
Some(Tok::new(
"#TX",
Value::String(crate::string_of(&value)),
source,
cursor,
)),
);
}
}
}
match recorded {
Some(value) if !matches!(value, Value::Undefined) => {
let (name_of, value) = match &value {
Value::String(_) => ("#TX", value.clone()),
Value::Number(_) => ("#NR", value.clone()),
Value::Object(_) | Value::Array(_) | Value::MapRef(_) | Value::ListRef(_) => {
("#VL", crate::deep_copy(&value))
}
_ => ("#VL", value.clone()),
};
Act::moved(next, Some(Tok::new(name_of, value, source, cursor)))
}
_ => {
let mut marker = indexmap::IndexMap::new();
marker.insert("__yamlAlias".to_string(), Value::String(name));
Act::moved(
next,
Some(Tok::new("#VL", Value::object(marker), source, cursor)),
)
}
}
}
fn anchor(
src: Src<'_>,
fwd: Src<'_>,
cursor: (usize, usize, usize),
context: &mut Context,
) -> Result<(usize, usize, usize), Box<Act>> {
let end = name_end(fwd, false);
let name = fwd.slice(1, end).to_string();
let mut skip = end;
if blank(at(fwd, skip)) {
skip += 1;
}
let mut standalone = true;
let mut indent = 0usize;
let mut back = cursor.0;
while back > 0 && !line_end(at(src, back - 1)) {
back -= 1;
if !blank(at(src, back)) {
standalone = false;
break;
}
indent += 1;
}
let mut next = advance_cols(src, cursor, skip);
{
let mut index = next.0;
while blank(at(src, index)) {
index += 1;
}
if is(src, index, b'#') {
while src.has(index) && !line_end(at(src, index)) {
index += 1;
}
next = advance_cols(src, next, index - next.0);
}
}
let inline = !(standalone && (line_end(at(src, next.0)) || !src.has(next.0)));
if inline {
let peek = src.from(src.clamp(next.0));
let head = at(peek, 0);
if head >= 0
&& head != i32::from(b'[')
&& head != i32::from(b'{')
&& head != i32::from(b'>')
&& head != i32::from(b'|')
&& !line_end(head)
{
if let Some(scalar) = inline_scalar(peek) {
state::map_set_in_cut(context, state::ANCHORS, name.clone(), Value::String(scalar));
}
}
}
let mut pending = indexmap::IndexMap::new();
pending.insert("n".to_string(), Value::String(name.clone()));
pending.insert("i".to_string(), Value::Bool(inline));
state::pend_anchor(context, &name, Value::object(pending));
let opener = at(src, next.0);
if opener == i32::from(b'[') || opener == i32::from(b'{') {
let (name_of, text) = if opener == i32::from(b'[') {
("#OS", "[")
} else {
("#OB", "{")
};
let token = Tok::new(name_of, Value::String(text.to_string()), text, next);
return Err(Box::new(Act::moved(
advance_cols(src, next, 1),
Some(token),
)));
}
if standalone && line_end(at(src, next.0)) {
let mut newline = next.0;
if is(src, newline, b'\r') {
newline += 1;
}
if is(src, newline, b'\n') {
newline += 1;
}
let mut spaces = 0;
while is(src, newline + spaces, b' ') {
spaces += 1;
}
let following = at(src, newline + spaces);
if following >= 0 && !line_end(following) && spaces >= indent {
next = (newline + spaces, next.1 + 1, spaces);
}
}
Ok(next)
}
fn inline_scalar(peek: Src<'_>) -> Option<String> {
match at(peek, 0) {
value if value == i32::from(b'"') => {
let mut index = 1;
while peek.has(index) && !is(peek, index, b'"') {
if is(peek, index, b'\\') {
index += 1;
}
index += 1;
}
let raw = peek.slice(1, peek.clamp(index));
Some(
raw.replace("\\n", "\n")
.replace("\\t", "\t")
.replace("\\\\", "\\")
.replace("\\\"", "\""),
)
}
value if value == i32::from(b'\'') => {
let mut index = 1;
while peek.has(index) && !is(peek, index, b'\'') {
if is(peek, index, b'\'') && is(peek, index + 1, b'\'') {
index += 1;
}
index += 1;
}
let raw = peek.slice(1, peek.clamp(index));
Some(raw.replace("''", "'"))
}
_ => {
let mut index = 0;
while peek.has(index) {
let byte = at(peek, index);
if line_end(byte)
|| byte == i32::from(b',')
|| byte == i32::from(b'}')
|| byte == i32::from(b']')
{
break;
}
if byte == i32::from(b':') && blank_line_end_or_eof(at(peek, index + 1)) {
break;
}
if byte == i32::from(b' ') && is(peek, index + 1, b'#') {
break;
}
index += 1;
}
let raw = peek.slice(0, index).trim_matches(crate::js_space);
if raw.is_empty() {
None
} else {
Some(raw.to_string())
}
}
}
}
fn local_tag(src: Src<'_>, fwd: Src<'_>, cursor: (usize, usize, usize)) -> (usize, usize, usize) {
let mut tag_end = 1;
while fwd.has(tag_end) && !is(fwd, tag_end, b' ') && !line_end(at(fwd, tag_end)) {
tag_end += 1;
}
if is(fwd, tag_end, b' ') {
tag_end += 1;
}
let mut next = advance_cols(src, cursor, tag_end);
if src.has(next.0) && line_end(at(src, next.0)) {
let mut standalone = true;
let mut back = cursor.0;
while back > 0 && !line_end(at(src, back - 1)) {
back -= 1;
if !blank(at(src, back)) {
standalone = false;
break;
}
}
if standalone {
let mut newline = next.0;
if is(src, newline, b'\r') {
newline += 1;
}
if is(src, newline, b'\n') {
newline += 1;
}
let mut spaces = 0;
while is(src, newline + spaces, b' ') {
spaces += 1;
}
next = (newline + spaces, next.1 + 1, spaces);
}
}
next
}
fn struct_tag(
src: Src<'_>,
fwd: Src<'_>,
cursor: (usize, usize, usize),
) -> Result<(usize, usize, usize), Box<Act>> {
let mut skip = 2;
while fwd.has(skip) && !is(fwd, skip, b' ') && !line_end(at(fwd, skip)) {
skip += 1;
}
while is(fwd, skip, b' ') {
skip += 1;
}
let mut standalone = true;
let mut indent = 0usize;
let mut back = cursor.0;
while back > 0 && !line_end(at(src, back - 1)) {
back -= 1;
if !blank(at(src, back)) {
standalone = false;
break;
}
indent += 1;
}
if standalone && line_end(at(fwd, skip)) {
let mut newline = skip;
if is(fwd, newline, b'\r') {
newline += 1;
}
if is(fwd, newline, b'\n') {
newline += 1;
}
let mut spaces = 0;
while is(fwd, newline + spaces, b' ') {
spaces += 1;
}
if spaces >= indent {
let next = (cursor.0 + newline + spaces, cursor.1 + 1, spaces);
let opener = at(src, next.0);
if opener == i32::from(b'[') || opener == i32::from(b'{') {
let (name_of, text) = if opener == i32::from(b'[') {
("#OS", "[")
} else {
("#OB", "{")
};
let token = Tok::new(name_of, Value::String(text.to_string()), text, next);
return Err(Box::new(Act::moved(
advance_cols(src, next, 1),
Some(token),
)));
}
return Ok(next);
}
}
let mut next = advance_cols(src, cursor, skip);
{
let mut index = next.0;
while blank(at(src, index)) {
index += 1;
}
if is(src, index, b'#') {
while src.has(index) && !line_end(at(src, index)) {
index += 1;
}
next = advance_cols(src, next, index - next.0);
}
}
let opener = at(src, next.0);
if opener == i32::from(b'[') || opener == i32::from(b'{') {
let (name_of, text) = if opener == i32::from(b'[') {
("#OS", "[")
} else {
("#OB", "{")
};
let token = Tok::new(name_of, Value::String(text.to_string()), text, next);
return Err(Box::new(Act::moved(
advance_cols(src, next, 1),
Some(token),
)));
}
Ok(next)
}
fn doc_marker(src: Src<'_>, fwd: Src<'_>, cursor: (usize, usize, usize)) -> Act {
let ended = is(fwd, 0, b'.');
let mut pos = 3;
while blank(at(fwd, pos)) {
pos += 1;
}
let inline = fwd.has(pos) && !line_end(at(fwd, pos)) && !is(fwd, pos, b'#');
let next = if inline {
advance_cols(src, cursor, pos)
} else {
let mut end = pos;
while fwd.has(end) && !line_end(at(fwd, end)) {
end += 1;
}
let mut rows = 0;
if is(fwd, end, b'\r') {
end += 1;
}
if is(fwd, end, b'\n') {
end += 1;
rows = 1;
}
(cursor.0 + end, cursor.1 + rows, 1)
};
let name = if ended { "#DE" } else { "#DS" };
Act::moved(
next,
Some(Tok::new(name, Value::Undefined, fwd.slice(0, 3), cursor)),
)
}
fn flush_surrogate(pending: &mut Option<u32>, out: &mut String) {
if pending.take().is_some() {
out.push('\u{fffd}');
}
}
fn push_code_point(code: u32, pending: &mut Option<u32>, out: &mut String) {
if (0xd800..=0xdbff).contains(&code) {
flush_surrogate(pending, out);
*pending = Some(code);
} else if (0xdc00..=0xdfff).contains(&code) {
match pending.take() {
Some(high) => out.push(
char::from_u32(0x10000 + ((high - 0xd800) << 10) + (code - 0xdc00))
.unwrap_or('\u{fffd}'),
),
None => out.push('\u{fffd}'),
}
} else {
flush_surrogate(pending, out);
out.push(char::from_u32(code).unwrap_or('\u{fffd}'));
}
}
fn double_quoted(src: Src<'_>, fwd: Src<'_>, cursor: (usize, usize, usize)) -> Act {
let mut index = 1;
let mut value = String::new();
let mut pending = None;
let mut escaped_upto = 0usize;
while fwd.has(index) && !is(fwd, index, b'"') {
if is(fwd, index, b'\\') {
index += 1;
let escape = at(fwd, index);
let simple = |text: &str| Some(text.to_string());
let decoded: Option<String> = match escape {
e if e == i32::from(b'n') => simple("\n"),
e if e == i32::from(b't') => simple("\t"),
e if e == i32::from(b'r') => simple("\r"),
e if e == i32::from(b'"') => simple("\""),
e if e == i32::from(b'\\') => simple("\\"),
e if e == i32::from(b'/') => simple("/"),
e if e == i32::from(b'b') => simple("\u{8}"),
e if e == i32::from(b'f') => simple("\u{c}"),
e if e == i32::from(b'a') => simple("\u{7}"),
e if e == i32::from(b'e') => simple("\u{1b}"),
e if e == i32::from(b'v') => simple("\u{b}"),
e if e == i32::from(b'0') => simple("\0"),
e if e == i32::from(b'\t') => simple("\t"),
e if e == i32::from(b' ') => simple(" "),
e if e == i32::from(b'_') => simple("\u{a0}"),
e if e == i32::from(b'N') => simple("\u{85}"),
e if e == i32::from(b'L') => simple("\u{2028}"),
e if e == i32::from(b'P') => simple("\u{2029}"),
_ => None,
};
if let Some(text) = decoded {
flush_surrogate(&mut pending, &mut value);
value.push_str(&text);
index += 1;
escaped_upto = value.len();
continue;
}
if escape == i32::from(b'x') || escape == i32::from(b'u') || escape == i32::from(b'U') {
let width = if escape == i32::from(b'x') {
2
} else if escape == i32::from(b'u') {
4
} else {
8
};
let from = index + 1;
let window = take_units(fwd.up_to(from + 4 * width + 4), from, width);
let number = crate::parse_int_16(window.digits);
if escape == i32::from(b'U') {
match crate::from_code_point(number) {
Some(code) => push_code_point(code, &mut pending, &mut value),
None => return Act::refuse(cursor),
}
} else {
push_code_point(crate::to_uint16(number), &mut pending, &mut value);
}
index = window.end;
escaped_upto = value.len();
if let Some(low) = window.split_low {
push_code_point(low, &mut pending, &mut value);
index += fwd.char_at(index).map_or(0, char::len_utf8);
}
continue;
}
if line_end(escape) {
if escape == i32::from(b'\r') && is(fwd, index + 1, b'\n') {
index += 1;
}
index += 1;
while blank(at(fwd, index)) {
index += 1;
}
continue;
}
if escape < 0 {
flush_surrogate(&mut pending, &mut value);
index += 1;
continue;
}
let character = fwd.char_at(index).unwrap_or('\\');
flush_surrogate(&mut pending, &mut value);
value.push(character);
index += character.len_utf8();
continue;
}
if line_end(at(fwd, index)) {
flush_surrogate(&mut pending, &mut value);
let mut trim_to = value.len();
while trim_to > escaped_upto
&& matches!(value.as_bytes().get(trim_to - 1), Some(b' ' | b'\t'))
{
trim_to -= 1;
}
value.truncate(trim_to);
let mut empty_lines = 0;
while fwd.has(index) && line_end(at(fwd, index)) {
if is(fwd, index, b'\r') {
index += 1;
}
if is(fwd, index, b'\n') {
index += 1;
}
empty_lines += 1;
while blank(at(fwd, index)) {
index += 1;
}
}
if empty_lines > 1 {
for _ in 1..empty_lines {
value.push('\n');
}
} else {
value.push(' ');
}
continue;
}
let character = fwd.char_at(index).unwrap_or('"');
flush_surrogate(&mut pending, &mut value);
value.push(character);
index += character.len_utf8();
}
flush_surrogate(&mut pending, &mut value);
if is(fwd, index, b'"') {
index += 1;
}
let source = fwd.slice(0, fwd.clamp(index)).to_string();
let next = advance_cols(src, cursor, index);
Act::moved(
next,
Some(Tok::new("#ST", Value::String(value), source, cursor)),
)
}
fn single_quoted(src: Src<'_>, fwd: Src<'_>, cursor: (usize, usize, usize)) -> Act {
let mut index = 1;
let mut value = String::new();
while fwd.has(index) {
if is(fwd, index, b'\'') {
if is(fwd, index + 1, b'\'') {
value.push('\'');
index += 2;
continue;
}
index += 1;
break;
}
if line_end(at(fwd, index)) {
while matches!(value.as_bytes().last(), Some(b' ' | b'\t')) {
value.pop();
}
let mut empty_lines = 0;
while fwd.has(index) && line_end(at(fwd, index)) {
if is(fwd, index, b'\r') {
index += 1;
}
if is(fwd, index, b'\n') {
index += 1;
}
empty_lines += 1;
while blank(at(fwd, index)) {
index += 1;
}
}
if empty_lines > 1 {
for _ in 1..empty_lines {
value.push('\n');
}
} else {
value.push(' ');
}
continue;
}
let character = fwd.char_at(index).unwrap_or('\'');
value.push(character);
index += character.len_utf8();
}
let source = fwd.slice(0, fwd.clamp(index)).to_string();
let next = advance_cols(src, cursor, index);
Act::moved(
next,
Some(Tok::new("#ST", Value::String(value), source, cursor)),
)
}
fn quoted_before(src: Src<'_>, offset: usize) -> bool {
src.quote_before(offset)
}
fn numeric_plain(
src: Src<'_>,
fwd: Src<'_>,
cursor: (usize, usize, usize),
context: &mut Context,
) -> Option<Act> {
let in_flow = state::flow_depth_at(context, src, cursor.0) > 0;
let mut embedded_colon = false;
let mut trailing_text = false;
let mut block_comma = false;
let ends_plain =
|index: usize| is(fwd, index, b':') && blank_line_end_or_eof(at(fwd, index + 1));
let mut index = 1;
while fwd.has(index) && !line_end(at(fwd, index)) {
if ends_plain(index) {
break;
}
if is(fwd, index, b':') && !blank_line_end_or_eof(at(fwd, index + 1)) {
embedded_colon = true;
index += 1;
continue;
}
if is(fwd, index, b',') {
if in_flow {
break;
}
block_comma = true;
index += 1;
continue;
}
if blank(at(fwd, index)) {
let mut after = index;
while blank(at(fwd, after)) {
after += 1;
}
let following = at(fwd, after);
if fwd.has(after)
&& !line_end(following)
&& following != i32::from(b'#')
&& following != i32::from(b':')
{
trailing_text = true;
}
break;
}
index += 1;
}
if trailing_text {
return Some(text::plain_scalar(src, fwd, cursor, context));
}
let mut token_end = 0;
while fwd.has(token_end)
&& !blank_line_end_or_eof(at(fwd, token_end))
&& !ends_plain(token_end)
&& !(in_flow
&& (is(fwd, token_end, b',') || is(fwd, token_end, b']') || is(fwd, token_end, b'}')))
{
token_end += 1;
}
let token = fwd.slice(0, token_end).as_bytes();
if token.contains(&b'#')
|| (!in_flow && token.iter().any(|b| matches!(b, b'[' | b']' | b'{' | b'}')))
{
return Some(text::plain_scalar(src, fwd, cursor, context));
}
let mut rest = token_end;
while blank(at(fwd, rest)) {
rest += 1;
}
if line_end(at(fwd, rest)) && text::plain_scalar_at(src, cursor.0, context).rows > 0 {
return Some(text::plain_scalar(src, fwd, cursor, context));
}
if embedded_colon || block_comma {
let mut end = 0;
while fwd.has(end)
&& !blank_line_end_or_eof(at(fwd, end))
&& !ends_plain(end)
&& !(in_flow && (is(fwd, end, b',') || is(fwd, end, b']') || is(fwd, end, b'}')))
{
end += 1;
}
let text = fwd.slice(0, end).to_string();
let next = advance_cols(src, cursor, end);
return Some(Act::moved(
next,
Some(Tok::new("#TX", Value::String(text.clone()), text, cursor)),
));
}
if crate::core_schema(context) {
let token = fwd.slice(0, token_end);
if crate::core_number(token).is_none() {
return Some(text::plain_scalar(src, fwd, cursor, context));
}
}
None
}
fn flow_newline(
src: Src<'_>,
fwd: Src<'_>,
cursor: (usize, usize, usize),
) -> Result<(usize, usize, usize), Box<Act>> {
let mut pos = 0;
let mut rows = 0;
let mut last_newline: isize = -1;
while fwd.has(pos) && (line_end(at(fwd, pos)) || blank(at(fwd, pos))) {
if is(fwd, pos, b'\n') {
rows += 1;
last_newline = pos as isize;
}
pos += 1;
}
if is(fwd, pos, b'#') {
while fwd.has(pos) && !line_end(at(fwd, pos)) {
pos += 1;
}
}
let column = if last_newline >= 0 {
fwd.slice(last_newline as usize, pos).chars().count()
} else {
cursor.2 + fwd.slice(0, pos).chars().count()
};
let next = (cursor.0 + pos, cursor.1 + rows, column);
let following = at(fwd, pos);
let punctuation = if following == i32::from(b'[') {
Some(("#OS", "["))
} else if following == i32::from(b'{') {
Some(("#OB", "{"))
} else if following == i32::from(b']') {
Some(("#CS", "]"))
} else if following == i32::from(b'}') {
Some(("#CB", "}"))
} else if following == i32::from(b',') {
Some(("#CA", ","))
} else {
None
};
if let Some((name, text)) = punctuation {
let token = Tok::new(name, Value::String(text.to_string()), text, next);
return Err(Box::new(Act::moved(
advance_cols(src, next, 1),
Some(token),
)));
}
Ok(next)
}
fn block_newline(
src: Src<'_>,
fwd: Src<'_>,
cursor: (usize, usize, usize),
context: &mut Context,
) -> Result<(usize, usize, usize), Box<Act>> {
let mut pos = 0;
let mut spaces = 0;
let mut rows = 0;
while fwd.has(pos) {
if is(fwd, pos, b'\r') && is(fwd, pos + 1, b'\n') {
pos += 2;
rows += 1;
} else if line_end(at(fwd, pos)) {
pos += 1;
rows += 1;
} else {
break;
}
spaces = 0;
while is(fwd, pos, b' ') {
pos += 1;
spaces += 1;
}
if is(fwd, pos, b'#') {
while fwd.has(pos) && !line_end(at(fwd, pos)) {
pos += 1;
}
continue;
}
if is(fwd, pos, b'\t') {
let mut tab = pos;
while blank(at(fwd, tab)) {
tab += 1;
}
if !fwd.has(tab) || line_end(at(fwd, tab)) {
pos = tab;
continue;
}
if is(fwd, tab, b'#') {
while fwd.has(tab) && !line_end(at(fwd, tab)) {
tab += 1;
}
pos = tab;
continue;
}
if block_start_at(src, cursor.0 + tab) {
return Err(Box::new(Act::bad(
(cursor.0 + pos, cursor.1, cursor.2),
TAB_INDENT,
tab - pos,
)));
}
}
if is(fwd, pos, b'&') {
let mut end = pos + 1;
while fwd.has(end) && !blank_line_end_or_eof(at(fwd, end)) {
end += 1;
}
let mut after = end;
while blank(at(fwd, after)) {
after += 1;
}
if !fwd.has(after) || line_end(at(fwd, after)) || is(fwd, after, b'#') {
let name = fwd.slice(pos + 1, end);
let mut pending = indexmap::IndexMap::new();
pending.insert("n".to_string(), Value::String(name.to_string()));
pending.insert("i".to_string(), Value::Bool(false));
state::pend_anchor(context, name, Value::object(pending));
while fwd.has(after) && !line_end(at(fwd, after)) {
after += 1;
}
pos = after;
continue;
}
}
}
if !fwd.has(pos) {
let next = (cursor.0 + pos, cursor.1 + rows, spaces + 1);
return Err(Box::new(Act::moved(
next,
Some(Tok::new("#ZZ", Value::Undefined, "", next)),
)));
}
if spaces == 0 && (is_doc_marker(fwd, pos) || is(fwd, pos, b'%')) {
return Ok((cursor.0 + pos, cursor.1 + rows, 0));
}
if spaces == 0 && (is(fwd, pos, b'"') || is(fwd, pos, b'\'')) && !quoted_key_at(fwd, pos) {
return Ok((cursor.0 + pos, cursor.1 + rows, 0));
}
let token = Tok::new(
"#IN",
Value::Number(spaces as f64),
fwd.slice(0, pos),
cursor,
);
Err(Box::new(Act::moved(
(cursor.0 + pos, cursor.1 + rows, spaces + 1),
Some(token),
)))
}
#[allow(clippy::too_many_lines)]
fn quoted_key_at(src: Src<'_>, index: usize) -> bool {
let byte = |k: usize| {
let c = src.at(k);
(c >= 0).then_some(c as u8)
};
let quote = src.at(index) as u8;
let mut j = index + 1;
while let Some(c) = byte(j).filter(|c| !matches!(c, b'\n' | b'\r')) {
if quote == b'"' && c == b'\\' {
j += 2;
continue;
}
if c == quote {
if quote == b'\'' && byte(j + 1) == Some(b'\'') {
j += 2;
continue;
}
break;
}
j += 1;
}
if byte(j) != Some(quote) {
return false;
}
j += 1;
while matches!(byte(j), Some(b' ' | b'\t')) {
j += 1;
}
byte(j) == Some(b':') && matches!(byte(j + 1), None | Some(b' ' | b'\t' | b'\n' | b'\r'))
}
fn dq_escape(e: char) -> Option<char> {
Some(match e {
'0' => '\u{0}',
'a' => '\u{7}',
'b' => '\u{8}',
't' | '\t' => '\t',
'n' => '\n',
'v' => '\u{b}',
'f' => '\u{c}',
'r' => '\r',
'e' => '\u{1b}',
' ' => ' ',
'"' => '"',
'/' => '/',
'\\' => '\\',
'N' => '\u{85}',
'_' => '\u{a0}',
'L' => '\u{2028}',
'P' => '\u{2029}',
_ => return None,
})
}
fn unquote_whole_scalar(text: &str) -> String {
let chars: Vec<char> = text.chars().collect();
let Some("e) = chars.first() else {
return text.to_string();
};
if (quote != '"' && quote != '\'') || chars.len() < 2 || chars[chars.len() - 1] != quote {
return text.to_string();
}
let last = chars.len() - 1;
let mut out = String::new();
let mut j = 1;
while j < last {
let c = chars[j];
if quote == '\'' && c == '\'' {
if chars[j + 1] != '\'' || j + 1 == last {
return text.to_string();
}
out.push('\'');
j += 1;
} else if quote == '"' && c == '"' {
return text.to_string();
} else if quote == '"' && c == '\\' {
j += 1;
if j >= last {
return text.to_string();
}
let e = chars[j];
if let Some(simple) = dq_escape(e) {
out.push(simple);
j += 1;
continue;
}
let width = match e {
'x' => 2,
'u' => 4,
'U' => 8,
_ => return text.to_string(),
};
let Some(mut code) = hex_at(&chars, j + 1, width, last) else {
return text.to_string();
};
j += width;
if e == 'u'
&& (0xd800..=0xdbff).contains(&code)
&& chars.get(j + 1) == Some(&'\\')
&& chars.get(j + 2) == Some(&'u')
{
if let Some(low) =
hex_at(&chars, j + 3, 4, last).filter(|low| (0xdc00..=0xdfff).contains(low))
{
code = 0x10000 + ((code - 0xd800) << 10) + (low - 0xdc00);
j += 6;
}
}
if code > 0x10_ffff {
return text.to_string();
}
out.push(char::from_u32(code).unwrap_or('\u{fffd}'));
} else {
out.push(c);
}
j += 1;
}
out
}
fn hex_at(chars: &[char], at: usize, width: usize, end: usize) -> Option<u32> {
if at + width > end {
return None;
}
chars[at..at + width]
.iter()
.try_fold(0u32, |n, c| c.to_digit(16).map(|d| n * 16 + d))
}
fn explicit_key(
src: Src<'_>,
fwd: Src<'_>,
cursor: (usize, usize, usize),
context: &mut Context,
) -> Act {
let start = if blank(at(fwd, 1)) { 2 } else { 1 };
let mut key_end = start;
while fwd.has(key_end) && !line_end(at(fwd, key_end)) {
if is(fwd, key_end, b' ') && is(fwd, key_end + 1, b'#') {
break;
}
key_end += 1;
}
let mut key = trim_end(fwd.slice(start, key_end)).to_string();
if let Some(stripped) = strip_key_tag(&key) {
key = stripped;
}
let raw_key = key;
key = unquote_whole_scalar(&raw_key);
let key_token = if key == raw_key { "#TX" } else { "#ST" };
let mut consumed = key_end;
while fwd.has(consumed) && !line_end(at(fwd, consumed)) {
consumed += 1;
}
let mut before_newline = consumed;
if is(fwd, consumed, b'\r') {
consumed += 1;
}
if is(fwd, consumed, b'\n') {
consumed += 1;
}
let mut question_indent = 0;
{
let mut line_start = cursor.0;
while line_start > 0 && !line_end(at(src, line_start - 1)) {
line_start -= 1;
}
while line_start < cursor.0 && is(src, line_start, b' ') {
question_indent += 1;
line_start += 1;
}
}
let mut extra_rows = 0;
if let Some((folded, chomp, explicit_indent)) = block_scalar_key(&key) {
let mut lines: Vec<String> = Vec::new();
let mut content_indent = 0usize;
while fwd.has(consumed) {
let mut line_indent = 0;
while is(fwd, consumed + line_indent, b' ') {
line_indent += 1;
}
let after = consumed + line_indent;
if !fwd.has(after) || line_end(at(fwd, after)) {
lines.push(String::new());
consumed = after;
if is(fwd, consumed, b'\r') {
consumed += 1;
}
if is(fwd, consumed, b'\n') {
consumed += 1;
}
extra_rows += 1;
continue;
}
if content_indent == 0 {
content_indent = if explicit_indent > 0 {
question_indent + explicit_indent
} else {
line_indent
};
}
if line_indent < content_indent {
break;
}
let mut line_end_index = after;
while fwd.has(line_end_index) && !line_end(at(fwd, line_end_index)) {
line_end_index += 1;
}
lines.push(
fwd.slice(consumed + content_indent, line_end_index)
.to_string(),
);
consumed = line_end_index;
if is(fwd, consumed, b'\r') {
consumed += 1;
}
if is(fwd, consumed, b'\n') {
consumed += 1;
}
extra_rows += 1;
}
if chomp != '+' {
while lines.last().is_some_and(String::is_empty) {
lines.pop();
}
}
key = if folded {
lines.join(" ") + "\n"
} else {
lines.join("\n") + "\n"
};
if chomp == '-' && key.ends_with('\n') {
key.pop();
}
} else {
while fwd.has(consumed) {
let mut line_indent = 0;
while is(fwd, consumed + line_indent, b' ') {
line_indent += 1;
}
let mut after = consumed + line_indent;
if fwd.has(after) && is(fwd, after, b'#') {
while fwd.has(after) && !line_end(at(fwd, after)) {
after += 1;
}
before_newline = after;
if is(fwd, after, b'\r') {
after += 1;
}
if is(fwd, after, b'\n') {
after += 1;
}
extra_rows += 1;
consumed = after;
continue;
}
if line_indent > question_indent
&& !is(fwd, after, b':')
&& !is(fwd, after, b'?')
&& !is(fwd, after, b'-')
{
let mut continuation_end = after;
while fwd.has(continuation_end) && !line_end(at(fwd, continuation_end)) {
if is(fwd, continuation_end, b' ') && is(fwd, continuation_end + 1, b'#') {
break;
}
continuation_end += 1;
}
let text = trim_end(fwd.slice(after, continuation_end));
if !text.is_empty() {
key.push(' ');
key.push_str(text);
}
consumed = continuation_end;
before_newline = consumed;
if is(fwd, consumed, b'\r') {
consumed += 1;
}
if is(fwd, consumed, b'\n') {
consumed += 1;
}
extra_rows += 1;
continue;
}
break;
}
}
let mut has_value = false;
let mut value_consumed = consumed;
{
let mut index = consumed;
while is(fwd, index, b' ') {
index += 1;
}
if is(fwd, index, b':') && blank_line_end_or_eof(at(fwd, index + 1)) {
has_value = true;
value_consumed = index + 1;
if blank(at(fwd, value_consumed)) {
value_consumed += 1;
}
}
}
let source = fwd
.slice(0, if has_value { consumed } else { key_end })
.to_string();
if has_value {
let indent = value_consumed - consumed;
let next = (
cursor.0 + value_consumed,
cursor.1 + 1 + extra_rows,
indent + 1,
);
let following = at(fwd, value_consumed);
let has_inline = following >= 0 && !line_end(following);
let mut needs_indent = false;
if has_inline {
let quoted_or_flow = following == i32::from(b'"')
|| following == i32::from(b'\'')
|| following == i32::from(b'[')
|| following == i32::from(b'{')
|| following == i32::from(b'!');
if !quoted_or_flow {
let mut line_end_index = value_consumed;
while fwd.has(line_end_index) && !line_end(at(fwd, line_end_index)) {
line_end_index += 1;
}
for index in value_consumed..line_end_index {
if is(fwd, index, b':') {
let after = at(fwd, index + 1);
if blank_line_end_or_eof(after) || index + 1 == line_end_index {
needs_indent = true;
break;
}
}
}
if !needs_indent
&& following == i32::from(b'-')
&& blank_line_end_or_eof(at(fwd, value_consumed + 1))
{
needs_indent = true;
}
}
}
if needs_indent {
state::list_push(
context,
state::PENDING_TOKENS,
encode_token(&Tok::new("#CL", Value::Number(1.0), ": ", next)),
);
state::list_push(
context,
state::PENDING_TOKENS,
encode_token(&Tok::new("#IN", Value::Number(indent as f64), "", next)),
);
} else {
state::set_flag(context, state::PENDING_CL, true);
}
return Act::moved(
next,
Some(Tok::new(key_token, Value::String(key), source, cursor)),
);
}
let next = advance_cols(src, cursor, before_newline);
state::list_push(
context,
state::PENDING_TOKENS,
encode_token(&Tok::new("#CL", Value::Number(1.0), ": ", next)),
);
state::list_push(
context,
state::PENDING_TOKENS,
encode_token(&Tok::new("#VL", Value::Null, "", next)),
);
Act::moved(
next,
Some(Tok::new(key_token, Value::String(key), source, cursor)),
)
}
fn strip_key_tag(key: &str) -> Option<String> {
let rest = key.strip_prefix("!!")?;
let name_len = rest
.find(|character: char| !character.is_ascii_alphanumeric() && character != '_')
.unwrap_or(rest.len());
if name_len == 0 {
return None;
}
let tail = &rest[name_len..];
let trimmed = tail.trim_start_matches(crate::js_space);
if trimmed.len() == tail.len() {
return None;
}
Some(trimmed.to_string())
}
fn block_scalar_key(key: &str) -> Option<(bool, char, usize)> {
let mut chars = key.chars();
let indicator = chars.next()?;
if indicator != '|' && indicator != '>' {
return None;
}
let mut chomp = ' ';
let mut indent = 0usize;
let mut next = chars.next();
if matches!(next, Some('+' | '-')) {
chomp = next.unwrap_or(' ');
next = chars.next();
}
if let Some(digit) = next {
if digit.is_ascii_digit() {
indent = digit.to_digit(10).unwrap_or(0) as usize;
next = chars.next();
} else {
return None;
}
}
if next.is_some() {
return None;
}
Some((indicator == '>', chomp, indent))
}