use tabnas::{Context, Lexer, Point, Rule, Site, Token, Value};
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,
pub(crate) ri: usize,
pub(crate) ci: 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,
ri: at.1,
ci: at.2,
}
}
}
pub(crate) struct Act {
pub(crate) si: usize,
pub(crate) ri: usize,
pub(crate) ci: usize,
pub(crate) token: Option<Tok>,
pub(crate) bad: bool,
}
impl Act {
pub(crate) fn still(at: (usize, usize, usize)) -> Self {
Act {
si: at.0,
ri: at.1,
ci: at.2,
token: None,
bad: false,
}
}
pub(crate) fn moved(at: (usize, usize, usize), token: Option<Tok>) -> Self {
Act {
si: at.0,
ri: at.1,
ci: at.2,
token,
bad: false,
}
}
pub(crate) fn refuse(at: (usize, usize, usize)) -> Self {
Act {
si: at.0,
ri: at.1,
ci: at.2,
token: None,
bad: true,
}
}
}
#[inline]
pub(crate) fn at(src: &str, index: usize) -> i32 {
src.as_bytes()
.get(index)
.map_or(-1, |byte| i32::from(*byte))
}
#[inline]
pub(crate) fn is(src: &str, 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: &str,
at: (usize, usize, usize),
count: usize,
) -> (usize, usize, usize) {
let mut end = (at.0 + count).min(src.len());
while end < src.len() && !src.is_char_boundary(end) {
end += 1;
}
let columns = src[at.0..end].chars().count();
(end, at.1, at.2 + columns)
}
fn carry(src: &str, from: usize, to: usize, row: usize, column: usize) -> (usize, usize) {
let (mut row, mut column) = (row, column);
let from = from.min(src.len());
let to = to.min(src.len()).max(from);
for character in src[from..to].chars() {
if character == '\n' {
row += 1;
column = 1;
} else {
column += 1;
}
}
(row, column)
}
pub(crate) fn virtual_point_for(lexer: &Lexer<'_>, context: &mut Context) -> (usize, usize) {
let point = lexer.point();
let here = point.site.si;
let Some(stored) = state::num(context, state::V_POS) else {
return (point.site.ri, point.site.ci);
};
let stored = stored.max(0.0) as usize;
if stored > here {
return (point.site.ri, point.site.ci);
}
let row = state::usize_at(context, state::V_ROW);
let column = state::usize_at(context, state::V_COL);
carry(lexer.source(), stored, here, row, column)
}
fn store_point(context: &mut Context, act: &Act) {
state::set_usize(context, state::V_POS, act.si);
state::set_usize(context, state::V_ROW, act.ri);
state::set_usize(context, state::V_COL, act.ci);
}
pub(crate) fn apply(lexer: &mut Lexer<'_>, context: &mut Context, act: Act) -> Option<Token> {
let point = lexer.point();
let start = point.site.si;
let start_pos = point.site.pos;
let length = point.len;
let token = {
let source = lexer.source();
act.token.as_ref().map(|token| {
let offset = token.si.clamp(start, source.len());
let pos = start_pos + source[start..offset].chars().count();
Token::new(
token.name,
-1,
token.val.clone(),
token.src.as_str(),
Point {
len: length,
site: Site {
si: offset,
pos,
ri: token.ri,
ci: token.ci,
},
},
)
})
};
let characters = {
let source = lexer.source();
let end = act.si.clamp(start, source.len());
source[start..end].chars().count()
};
if characters > 0 {
lexer.advance_chars(characters);
}
store_point(context, &act);
if act.bad {
let mut refusal = lexer.bad("unexpected");
refusal.site.ri = act.ri;
refusal.site.ci = act.ci;
return Some(refusal);
}
token
}
pub(crate) fn yaml_matcher(
lexer: &mut Lexer<'_>,
_rule: &mut Rule,
context: &mut Context,
) -> Option<Token> {
let (row, column) = virtual_point_for(lexer, context);
let start = lexer.point().site.si;
let act = {
let source = lexer.source();
decide(source, (start, row, column), context)
};
let moved = act.token.is_none() && !act.bad && act.si != start;
state::set_flag(context, state::MOVED, moved);
apply(lexer, context, act)
}
fn strip_comment_lines(src: &str) -> String {
let mut out = String::with_capacity(src.len());
let mut rest = src;
while !rest.is_empty() {
let end = rest.find('\n').map_or(rest.len(), |index| index + 1);
let (line, tail) = rest.split_at(end);
if !line.trim_start_matches([' ', '\t']).starts_with('#') {
out.push_str(line);
}
rest = tail;
}
out
}
#[allow(clippy::too_many_lines)]
fn decide(src: &str, start: (usize, usize, usize), context: &mut Context) -> Act {
if !state::flag(context, state::INIT) {
state::initialise(context);
if src.trim_matches(crate::js_space).is_empty()
|| strip_comment_lines(src)
.trim_matches(crate::js_space)
.is_empty()
{
return Act::moved(
(src.len(), 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(BOM) {
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[cursor.0..=cursor.0], cursor);
return Act::moved((cursor.0 + 1, cursor.1, cursor.2 + 1), Some(token));
}
if here == i32::from(b'#') {
while cursor.0 < src.len() && !line_end(at(src, cursor.0)) {
cursor.0 += 1;
}
}
}
loop {
if cursor.0 >= src.len() {
return Act::refuse(cursor);
}
let fwd = &src[cursor.0..];
if blank(at(fwd, 0)) {
let line_end_index = fwd.find('\n');
let line = line_end_index.map_or(fwd, |index| &fwd[..index]);
if line.contains('\t')
&& !line.is_empty()
&& line.bytes().all(|byte| blank(i32::from(byte)))
{
let skip = line_end_index.map_or(line.len(), |index| index + 1);
cursor = (cursor.0 + skip, cursor.1 + 1, 0);
continue;
}
}
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 pos < fwd.len() && !line_end(at(fwd, pos)) {
pos += 1;
}
let text = fwd[..pos].to_string();
let next = advance_cols(src, cursor, pos);
return Act::moved(
next,
Some(Tok::new("#DR", Value::String(text.clone()), text, next)),
);
}
if is(fwd, 0, b'!') && !is(fwd, 1, b'!') && at(fwd, 1) >= 0 {
if is(fwd, 1, b' ') {
let mut val_end = 2;
while val_end < fwd.len() && !line_end(at(fwd, val_end)) {
val_end += 1;
}
let raw = trim_end(&fwd[2..val_end]).to_string();
let source = fwd[..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();
if digit(0) || ((is(fwd, 0, b'+') || is(fwd, 0, b'-')) && digit(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[..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}';
fn at_line_start(src: &str, offset: usize) -> bool {
offset == 0
|| line_end(at(src, offset - 1))
|| (offset == BOM.len_utf8() && src.starts_with(BOM))
}
pub(crate) fn line_start_of(src: &str, offset: usize) -> usize {
let mut index = offset;
while index > 0 && !line_end(at(src, index - 1)) {
index -= 1;
}
if index == 0 && src.starts_with(BOM) {
index = BOM.len_utf8();
}
index
}
fn doc_marker_run(src: &str, 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: &str, 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: &str, 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: &str, index: usize, word: &str) -> bool {
word.bytes()
.enumerate()
.all(|(offset, byte)| at(src, index + offset) == i32::from(byte))
}
fn is_struct_tag(fwd: &str) -> 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;
}
fwd["!!python/".len()..]
.chars()
.take_while(|character| !crate::js_space(*character))
.any(|character| character.is_ascii_alphanumeric() || character == '_')
}
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));
map.insert("r".to_string(), Value::Number(token.ri as f64));
map.insert("c".to_string(), Value::Number(token.ci 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),
ri: number("r", fallback.1),
ci: number("c", fallback.2),
}
}
fn name_end(fwd: &str, alias: bool) -> usize {
let mut index = 1;
while index < fwd.len() {
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: &str, fwd: &str, cursor: (usize, usize, usize), context: &mut Context) -> Act {
let end = name_end(fwd, true);
let name = fwd[1..end].to_string();
let source = fwd[..end].to_string();
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: &str,
fwd: &str,
cursor: (usize, usize, usize),
context: &mut Context,
) -> Result<(usize, usize, usize), Box<Act>> {
let end = name_end(fwd, false);
let name = fwd[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 index < src.len() && !line_end(at(src, index)) {
index += 1;
}
next = advance_cols(src, next, index - next.0);
}
}
let inline = !(standalone && (line_end(at(src, next.0)) || next.0 >= src.len()));
if inline {
let peek = &src[next.0.min(src.len())..];
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(context, state::ANCHORS, name.clone(), Value::String(scalar));
}
}
}
let mut pending = indexmap::IndexMap::new();
pending.insert("n".to_string(), Value::String(name));
pending.insert("i".to_string(), Value::Bool(inline));
state::list_push(context, state::PENDING_ANCHORS, 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: &str) -> Option<String> {
match at(peek, 0) {
value if value == i32::from(b'"') => {
let mut index = 1;
while index < peek.len() && !is(peek, index, b'"') {
if is(peek, index, b'\\') {
index += 1;
}
index += 1;
}
let raw = &peek[1..index.min(peek.len())];
Some(
raw.replace("\\n", "\n")
.replace("\\t", "\t")
.replace("\\\\", "\\")
.replace("\\\"", "\""),
)
}
value if value == i32::from(b'\'') => {
let mut index = 1;
while index < peek.len() && !is(peek, index, b'\'') {
if is(peek, index, b'\'') && is(peek, index + 1, b'\'') {
index += 1;
}
index += 1;
}
let raw = &peek[1..index.min(peek.len())];
Some(raw.replace("''", "'"))
}
_ => {
let mut index = 0;
while index < peek.len() {
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[..index].trim_matches(crate::js_space);
if raw.is_empty() {
None
} else {
Some(raw.to_string())
}
}
}
}
fn local_tag(src: &str, fwd: &str, cursor: (usize, usize, usize)) -> (usize, usize, usize) {
let mut tag_end = 1;
while tag_end < fwd.len() && !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 next.0 < src.len() && 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: &str,
fwd: &str,
cursor: (usize, usize, usize),
) -> Result<(usize, usize, usize), Box<Act>> {
let mut skip = 2;
while skip < fwd.len() && !is(fwd, skip, b' ') && !is(fwd, skip, b'\n') {
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 index < src.len() && !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: &str, fwd: &str, cursor: (usize, usize, usize)) -> Act {
let ended = is(fwd, 0, b'.');
let mut pos = 3;
while blank(at(fwd, pos)) {
pos += 1;
}
let inline = pos < fwd.len() && !line_end(at(fwd, pos)) && !is(fwd, pos, b'#');
let next = if inline {
advance_cols(src, cursor, pos)
} else {
let mut end = pos;
while end < fwd.len() && !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[..3], next)),
)
}
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: &str, fwd: &str, cursor: (usize, usize, usize)) -> Act {
let mut index = 1;
let mut value = String::new();
let mut pending = None;
let mut escaped_upto = 0usize;
while index < fwd.len() && !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, 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[index..].chars().next().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[index..].chars().next().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 index < fwd.len() && 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[index..].chars().next().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[..index.min(fwd.len())].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: &str, fwd: &str, cursor: (usize, usize, usize)) -> Act {
let mut index = 1;
let mut value = String::new();
while index < fwd.len() {
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 index < fwd.len() && 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[index..].chars().next().unwrap_or('\'');
value.push(character);
index += character.len_utf8();
}
let source = fwd[..index.min(fwd.len())].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: &str, offset: usize) -> bool {
let mut previous = offset as isize - 1;
while previous >= 0 {
let byte = at(src, previous as usize);
if blank(byte) || line_end(byte) {
previous -= 1;
continue;
}
let mut line_start = previous as usize;
while line_start > 0 && !line_end(at(src, line_start - 1)) {
line_start -= 1;
}
let mut hash_at: isize = -1;
let mut quote: i32 = 0;
let mut index = line_start;
while index <= previous as usize {
let character = at(src, index);
if quote != 0 {
if quote == i32::from(b'"') && character == i32::from(b'\\') {
index += 2;
continue;
}
if character == quote {
if quote == i32::from(b'\'') && is(src, index + 1, b'\'') {
index += 2;
continue;
}
quote = 0;
}
index += 1;
continue;
}
if character == i32::from(b'"') || character == i32::from(b'\'') {
quote = character;
index += 1;
continue;
}
if character == i32::from(b'#') && (index == line_start || blank(at(src, index - 1))) {
hash_at = index as isize;
break;
}
index += 1;
}
if hash_at >= 0 {
previous = hash_at - 1;
continue;
}
break;
}
previous >= 0 && (is(src, previous as usize, b'"') || is(src, previous as usize, b'\''))
}
fn numeric_plain(
src: &str,
fwd: &str,
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 mut index = 1;
while index < fwd.len() && !line_end(at(fwd, index)) {
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 after < fwd.len()
&& !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 token_end < fwd.len()
&& !blank_line_end_or_eof(at(fwd, 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.as_bytes()[..token_end];
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));
}
if embedded_colon || block_comma {
let mut end = 0;
while end < fwd.len()
&& !blank_line_end_or_eof(at(fwd, end))
&& !(in_flow && (is(fwd, end, b',') || is(fwd, end, b']') || is(fwd, end, b'}')))
{
end += 1;
}
let text = fwd[..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)),
));
}
None
}
fn flow_newline(
src: &str,
fwd: &str,
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 pos < fwd.len() && (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 pos < fwd.len() && !line_end(at(fwd, pos)) {
pos += 1;
}
}
let column = if last_newline >= 0 {
fwd[last_newline as usize..pos].chars().count()
} else {
cursor.2 + fwd[..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: &str,
fwd: &str,
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 pos < fwd.len() {
if is(fwd, pos, b'\r') && is(fwd, pos + 1, b'\n') {
pos += 2;
rows += 1;
} else if is(fwd, pos, b'\n') {
pos += 1;
rows += 1;
} else {
break;
}
spaces = 0;
while is(fwd, pos, b' ') {
pos += 1;
spaces += 1;
}
if is(fwd, pos, b'#') {
while pos < fwd.len() && !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 tab >= fwd.len() || line_end(at(fwd, tab)) {
pos = tab;
continue;
}
}
if is(fwd, pos, b'&') {
let mut end = pos + 1;
while end < fwd.len() && !blank_line_end_or_eof(at(fwd, end)) {
end += 1;
}
let mut after = end;
while blank(at(fwd, after)) {
after += 1;
}
if after >= fwd.len() || line_end(at(fwd, after)) || is(fwd, after, b'#') {
let mut pending = indexmap::IndexMap::new();
pending.insert(
"n".to_string(),
Value::String(fwd[pos + 1..end].to_string()),
);
pending.insert("i".to_string(), Value::Bool(false));
state::list_push(context, state::PENDING_ANCHORS, Value::object(pending));
while after < fwd.len() && !line_end(at(fwd, after)) {
after += 1;
}
pos = after;
continue;
}
}
}
if pos >= fwd.len() {
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'[')
|| ((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[..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: &str, index: usize) -> bool {
let bytes = src.as_bytes();
let quote = bytes[index];
let mut j = index + 1;
while j < bytes.len() && !matches!(bytes[j], b'\n' | b'\r') {
if quote == b'"' && bytes[j] == b'\\' {
j += 2;
continue;
}
if bytes[j] == quote {
if quote == b'\'' && bytes.get(j + 1) == Some(&b'\'') {
j += 2;
continue;
}
break;
}
j += 1;
}
if bytes.get(j) != Some("e) {
return false;
}
j += 1;
while matches!(bytes.get(j), Some(b' ' | b'\t')) {
j += 1;
}
bytes.get(j) == Some(&b':')
&& matches!(bytes.get(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;
}
}
let Some(decoded) = char::from_u32(code) else {
return text.to_string();
};
out.push(decoded);
} 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: &str, fwd: &str, cursor: (usize, usize, usize), context: &mut Context) -> Act {
let start = if blank(at(fwd, 1)) { 2 } else { 1 };
let mut key_end = start;
while key_end < fwd.len() && !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[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 consumed < fwd.len() && !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 consumed < fwd.len() {
let mut line_indent = 0;
while is(fwd, consumed + line_indent, b' ') {
line_indent += 1;
}
let after = consumed + line_indent;
if after >= fwd.len() || 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 line_end_index < fwd.len() && !line_end(at(fwd, line_end_index)) {
line_end_index += 1;
}
lines.push(fwd[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 consumed < fwd.len() {
let mut line_indent = 0;
while is(fwd, consumed + line_indent, b' ') {
line_indent += 1;
}
let mut after = consumed + line_indent;
if after < fwd.len() && is(fwd, after, b'#') {
while after < fwd.len() && !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 continuation_end < fwd.len() && !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[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[..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 line_end_index < fwd.len() && !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(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, next)),
);
}
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, next)),
)
}
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))
}