#![deny(unsafe_code)]
#![deny(unsafe_op_in_unsafe_fn)]
use std::time::{Duration, Instant};
#[allow(unsafe_code)]
mod fast_utf8 {
const UTF8_CONT_MASK: u8 = 0xC0;
const UTF8_CONT_TAG: u8 = 0x80;
#[inline]
pub(crate) fn ceil_utf8_boundary(s: &str, idx: usize) -> usize {
let bytes = s.as_bytes();
let mut i = idx.min(bytes.len());
while i < bytes.len() {
let b = unsafe { *bytes.get_unchecked(i) };
if (b & UTF8_CONT_MASK) != UTF8_CONT_TAG {
break;
}
i += 1;
}
i
}
}
pub use yolowsyntax::{
Limits, Outline, Section, Symbol, SymbolKind, compact, extract, langs, lexer, parser, recover,
scanner, stack, table, tree,
};
#[cfg(feature = "tools")]
pub use yolowsyntax::{cdata, convert, corpus, lexconv};
pub mod api {
pub use yolowsyntax::api::{Ev, ParseTree, VNode};
pub fn parse(
lang: &yolowsyntax::table::Language,
input: &[u8],
limits: yolowsyntax::Limits,
) -> ParseTree {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
yolowsyntax::api::parse(lang, input, limits)
}))
.unwrap_or_else(|_| {
yolowsyntax::api::parse(
lang,
input,
yolowsyntax::Limits {
max_nodes: 0,
..limits
},
)
})
}
pub fn parse_with_budget(
lang: &yolowsyntax::table::Language,
input: &[u8],
limits: yolowsyntax::Limits,
deadline_ms: Option<u64>,
) -> ParseTree {
let clamped = match deadline_ms {
Some(0) => yolowsyntax::Limits {
max_nodes: 0,
..limits
},
Some(ms) => yolowsyntax::Limits {
max_millis: if limits.max_millis == 0 {
ms
} else {
limits.max_millis.min(ms)
},
..limits
},
None => limits,
};
parse(lang, input, clamped)
}
}
pub fn outline(tag: &str, source: &str) -> Option<Outline> {
let mut out = yolowsyntax::outline(tag, source)?;
sanitize_sections(source, &mut out.sections);
Some(out)
}
pub fn outline_with_budget(
tag: &str,
source: &str,
max_input_bytes: usize,
deadline_ms: Option<u64>,
) -> Option<Outline> {
if deadline_ms == Some(0)
|| source.is_empty()
|| source.len() > max_input_bytes
|| langs::Lang::from_tag(tag).is_none()
{
return None;
}
let started = Instant::now();
let mut out = yolowsyntax::outline(tag, source)?;
if let Some(ms) = deadline_ms
&& started.elapsed() > Duration::from_millis(ms)
{
return None;
}
sanitize_sections(source, &mut out.sections);
Some(out)
}
fn sanitize_sections(source: &str, sections: &mut Vec<Section>) {
let len = source.len();
if sections.is_empty() {
sections.push(Section {
start: 0,
end: len,
title: None,
});
return;
}
let mut cursor = 0usize;
let mut write = 0usize;
for read in 0..sections.len() {
let end = fast_utf8::ceil_utf8_boundary(source, sections[read].end);
if end <= cursor {
continue;
}
let title = sections[read].title.take();
sections[write] = Section {
start: cursor,
end,
title,
};
write += 1;
cursor = end;
}
if write == 0 {
sections.truncate(1);
sections[0] = Section {
start: 0,
end: len,
title: None,
};
} else {
sections.truncate(write);
if let Some(last) = sections.last_mut() {
last.end = len;
}
}
}
#[cfg(test)]
mod m1_2b_tests;