use std::borrow::Cow;
use std::cmp::Reverse;
use std::ops::Range;
use std::sync::Arc;
use std::time::Instant;
use thiserror::Error;
use super::capture::{Budget, Capture, Captured, Promote, Want};
use super::chain::ChainError;
use super::config::{FallbackConfig, FormatChoice, HopConfig, ParseConfig, Settings};
use super::frame::{Frame, FrameState, FramingConfig};
use super::sink::{FieldSink, SinkMark};
use super::trace::{Event, Failure, Input, Step, Trace};
use super::{ParseError, Parsed, Parser, Resolve, ResolveError};
use crate::strmatch::{SignatureError, SignatureScratch, SignatureSet};
const BUDGET_FLOOR: usize = 64 * 1024;
const PASSES_PER_LEVEL: usize = 8;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum CompileError {
#[error(transparent)]
Chain(#[from] ChainError),
#[error(transparent)]
Resolve(#[from] ResolveError),
#[error(transparent)]
Signature(#[from] SignatureError),
#[error("settings under {key:?} belong to no parser the chain names")]
StraySettings {
key: String,
},
#[error("the chain is empty: name a format, or write auto")]
EmptyChain,
#[error("hop {hop}: the format list is empty")]
EmptyList {
hop: usize,
},
#[error("{key} must be at least 1")]
ZeroLimit {
key: &'static str,
},
#[error("the first hop reads the record: it takes neither field nor each")]
FirstSelector,
#[error("hop {hop}: field and each are set together")]
FieldAndEach {
hop: usize,
},
#[error("hop {hop}: each leaves alone a value nothing takes, so it has no fallback")]
EachFallback {
hop: usize,
},
#[error("hop {hop} follows auto*, which is the last hop of a chain")]
AfterAutoStar {
hop: usize,
},
#[error("the multi-line start pattern: {0}")]
FramingStart(crate::strmatch::BuildError),
#[error("the chain has {hops} hops but max_depth is {max}")]
TooManyHops {
hops: usize,
max: usize,
},
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Status {
Parsed,
Fallback,
DepthLimit,
Truncated,
Rejected,
}
impl Status {
const fn rank(self) -> u8 {
match self {
Self::Parsed => 0,
Self::Fallback => 1,
Self::DepthLimit => 2,
Self::Truncated => 3,
Self::Rejected => 4,
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Outcome {
pub status: Status,
pub layers: usize,
pub rest: Option<Range<usize>>,
pub error: Option<ParseError>,
}
#[derive(Debug, Clone)]
enum Selector {
Body,
Field(String),
Each,
}
#[derive(Debug, Clone)]
enum Choice {
Named(Vec<usize>),
Auto,
AutoStar,
}
#[derive(Debug, Clone, Copy)]
enum Fallback {
Raw,
Reject,
Parser(usize),
}
#[derive(Debug, Clone)]
struct Hop {
selector: Selector,
choice: Choice,
prefix: Option<String>,
fallback: Fallback,
}
#[derive(Debug, Clone)]
struct Candidates {
ids: Vec<usize>,
set: SignatureSet,
}
#[cfg(feature = "metrics")]
pub type Counter = metrics::Counter;
#[cfg(feature = "metrics")]
pub fn counter(name: &'static str, labels: &[(&'static str, String)]) -> Counter {
let labels: Vec<metrics::Label> = labels
.iter()
.map(|(k, v)| metrics::Label::new(*k, v.clone()))
.collect();
metrics::counter!(name, labels)
}
#[cfg(not(feature = "metrics"))]
#[derive(Debug, Clone, Default)]
pub struct Counter;
#[cfg(not(feature = "metrics"))]
impl Counter {
#[allow(clippy::unused_self, reason = "mirrors metrics::Counter::increment")]
pub const fn increment(&self, _: u64) {}
}
#[cfg(not(feature = "metrics"))]
pub const fn counter(_: &'static str, _: &[(&'static str, String)]) -> Counter {
Counter
}
#[derive(Debug, Clone)]
struct Counters {
layer: Vec<Vec<Counter>>,
detected: Vec<Counter>,
error: Vec<Counter>,
fallback: Counter,
truncated: Counter,
}
impl Counters {
fn new(parsers: &[Arc<dyn Parser>], max_depth: usize) -> Self {
let per = |name: &'static str| -> Vec<Counter> {
parsers
.iter()
.map(|p| counter(name, &[("format", p.name().to_owned())]))
.collect()
};
let layer = (0..max_depth)
.map(|depth| {
parsers
.iter()
.map(|p| {
counter(
"parse_layer_total",
&[
("depth", depth.to_string()),
("format", p.name().to_owned()),
],
)
})
.collect()
})
.collect();
Self {
layer,
detected: per("parse_detected_total"),
error: per("parse_error_total"),
fallback: counter("parse_fallback_total", &[]),
truncated: counter("parse_truncated_total", &[]),
}
}
}
#[derive(Debug)]
pub struct ParserCounts {
held: Vec<Option<(Counter, u64)>>,
}
impl ParserCounts {
#[cfg(all(feature = "parse-grok", feature = "metrics"))]
pub(crate) fn add(&mut self, slot: usize, counter: &Counter, n: u64) {
if self.held.len() <= slot {
self.held.resize_with(slot + 1, || None);
}
match &mut self.held[slot] {
Some((_, owed)) => *owed += n,
empty => *empty = Some((counter.clone(), n)),
}
}
fn publish(&mut self) {
for (counter, owed) in self.held.iter_mut().flatten() {
if *owed > 0 {
counter.increment(std::mem::take(owed));
}
}
}
}
#[derive(Debug)]
struct Counts {
parsers: Vec<ParserCounts>,
layer: Vec<Vec<u64>>,
detected: Vec<u64>,
error: Vec<u64>,
fallback: u64,
truncated: u64,
}
#[derive(Debug, Clone, Copy)]
enum Count {
Layer {
depth: usize,
id: usize,
},
Detected(usize),
Error(usize),
Fallback,
Truncated,
}
#[derive(Debug, Clone)]
struct Scan {
scratch: SignatureScratch,
ranked: Vec<(Reverse<crate::strmatch::Specificity>, Reverse<u8>, usize)>,
}
#[derive(Debug, Clone)]
pub struct SourceState {
scan: Scan,
frames: FrameState,
}
pub struct ParsePlan {
parsers: Vec<Arc<dyn Parser>>,
gated: Vec<bool>,
dotted: Vec<String>,
hops: Vec<Hop>,
detect: Candidates,
counters: Counters,
max_depth: usize,
max_invocations: usize,
framing: FramingConfig,
start: Option<crate::strmatch::StrMatcher>,
}
impl std::fmt::Debug for ParsePlan {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ParsePlan")
.field(
"parsers",
&self.parsers.iter().map(|p| p.name()).collect::<Vec<_>>(),
)
.field("hops", &self.hops)
.finish_non_exhaustive()
}
}
struct Builder<'r> {
resolve: &'r dyn Resolve,
plan_settings: &'r Settings,
parsers: Vec<Arc<dyn Parser>>,
used: Vec<&'r str>,
}
impl Builder<'_> {
fn intern(&mut self, parser: Arc<dyn Parser>) -> usize {
if let Some(id) = self.parsers.iter().position(|p| Arc::ptr_eq(p, &parser)) {
return id;
}
self.parsers.push(parser);
self.parsers.len() - 1
}
fn named(&mut self, name: &str, hop: &HopConfig) -> Result<usize, CompileError> {
let settings = hop.settings.get(name).or_else(|| {
let (key, value) = self.plan_settings.get_key_value(name)?;
self.used.push(key);
Some(value)
});
if !super::valid_parser_name(name) {
return Err(ResolveError::BadName(name.to_owned()).into());
}
let parser = self.resolve.resolve(name, settings)?;
Ok(self.intern(parser))
}
fn hop(
&mut self,
at: usize,
hop: &HopConfig,
plan_fallback: &FallbackConfig,
) -> Result<Hop, CompileError> {
let selector = match (&hop.field, hop.each) {
(Some(_), true) => return Err(CompileError::FieldAndEach { hop: at }),
(Some(_), false) | (None, true) if at == 0 => {
return Err(CompileError::FirstSelector);
}
(Some(name), false) => Selector::Field(name.clone()),
(None, true) if hop.fallback.is_some() => {
return Err(CompileError::EachFallback { hop: at });
}
(None, true) => Selector::Each,
(None, false) => Selector::Body,
};
let mut listed: Vec<&str> = Vec::new();
let choice = match &hop.format {
FormatChoice::Auto => Choice::Auto,
FormatChoice::AutoStar => Choice::AutoStar,
FormatChoice::Named(names) if names.is_empty() => {
return Err(CompileError::EmptyList { hop: at });
}
FormatChoice::Named(names) => {
listed.extend(names.iter().map(String::as_str));
let ids: Result<Vec<usize>, CompileError> =
names.iter().map(|n| self.named(n, hop)).collect();
Choice::Named(ids?)
}
};
let fallback = match hop.fallback.as_ref().unwrap_or(plan_fallback) {
FallbackConfig::Raw => Fallback::Raw,
FallbackConfig::Reject => Fallback::Reject,
FallbackConfig::Format(name) => {
listed.push(name);
Fallback::Parser(self.named(name, hop)?)
}
};
if let Some(key) = hop.settings.keys().find(|k| !listed.contains(&k.as_str())) {
return Err(CompileError::StraySettings { key: key.clone() });
}
Ok(Hop {
selector,
choice,
prefix: hop.prefix.clone(),
fallback,
})
}
}
#[derive(Debug, Clone, Copy)]
enum Origin<'n> {
Record,
Body { parent: usize },
Value { parent: usize, name: &'n str },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Need {
Required,
Optional,
}
#[derive(Debug)]
pub struct Batch<'p> {
plan: &'p ParsePlan,
counts: Counts,
}
impl Batch<'_> {
pub fn parse<'a>(
&mut self,
input: &'a [u8],
state: &mut SourceState,
out: &mut dyn FieldSink<'a>,
) -> Outcome {
let counts = Some(&mut self.counts);
self.plan.run(input, &mut state.scan, out, None, counts)
}
pub fn publish(&mut self) {
let shared = &self.plan.counters;
let add = |counter: &Counter, held: &mut u64| {
if *held > 0 {
counter.increment(std::mem::take(held));
}
};
for (counters, held) in shared.layer.iter().zip(&mut self.counts.layer) {
for (counter, held) in counters.iter().zip(held) {
add(counter, held);
}
}
for (counter, held) in shared.detected.iter().zip(&mut self.counts.detected) {
add(counter, held);
}
for (counter, held) in shared.error.iter().zip(&mut self.counts.error) {
add(counter, held);
}
add(&shared.fallback, &mut self.counts.fallback);
add(&shared.truncated, &mut self.counts.truncated);
for own in &mut self.counts.parsers {
own.publish();
}
}
}
impl Drop for Batch<'_> {
fn drop(&mut self) {
self.publish();
}
}
#[derive(Debug, Clone, Copy)]
struct At<'n> {
hop: usize,
depth: usize,
origin: Origin<'n>,
need: Need,
}
struct Run<'r> {
scan: &'r mut Scan,
trace: Option<&'r mut Trace>,
budget: &'r Budget,
record: Range<usize>,
mark: SinkMark,
calls: usize,
status: Status,
layers: usize,
rest: Option<Range<usize>>,
error: Option<ParseError>,
stop: bool,
counts: Option<&'r mut Counts>,
}
impl Run<'_> {
fn span(&self, input: &[u8]) -> Option<Range<usize>> {
let start = input.as_ptr().addr();
let end = start + input.len();
(self.record.start <= start && end <= self.record.end)
.then(|| start - self.record.start..end - self.record.start)
}
fn raise(&mut self, status: Status, rest: Option<Range<usize>>, error: Option<ParseError>) {
if status.rank() > self.status.rank() {
self.status = status;
self.rest = rest;
self.error = error;
}
}
fn step(&mut self, at: At<'_>, parser: Option<&str>, event: Event) -> usize {
let Some(trace) = self.trace.as_deref_mut() else {
return 0;
};
let (parent, input) = match at.origin {
Origin::Record => (None, Input::Record),
Origin::Body { parent } => (Some(parent), Input::Body),
Origin::Value { parent, name } => (Some(parent), Input::Field(name.to_owned())),
};
trace.steps.push(Step {
hop: at.hop,
parent,
input,
parser: parser.map(str::to_owned),
event,
kept: matches!(event, Event::Parsed | Event::FallbackParsed),
});
trace.steps.len() - 1
}
fn truncate(&mut self, at: At<'_>, input: &[u8]) {
let rest = self.span(input);
self.raise(Status::Truncated, rest, None);
self.step(at, None, Event::Truncated);
self.stop = true;
}
}
struct Won<'i> {
body: Option<&'i [u8]>,
got: Vec<Captured<'i>>,
step: usize,
}
enum Attempt<'i> {
Won(Won<'i>),
NoMatch,
Error(ParseError),
Stopped,
}
enum Tried<'i> {
Won(Won<'i>),
Missed(Option<ParseError>),
Stopped,
}
impl ParsePlan {
pub fn compile(config: &ParseConfig, resolve: &dyn Resolve) -> Result<Self, CompileError> {
let mut limits = vec![
("max_depth", config.max_depth),
("max_invocations", config.max_invocations),
];
limits.extend(config.framing.limits());
if let Some(&(key, _)) = limits.iter().find(|(_, value)| *value == 0) {
return Err(CompileError::ZeroLimit { key });
}
let written = &config.chain.0;
if written.is_empty() {
return Err(CompileError::EmptyChain);
}
if written.len() > config.max_depth {
return Err(CompileError::TooManyHops {
hops: written.len(),
max: config.max_depth,
});
}
let mut b = Builder {
resolve,
plan_settings: &config.settings,
parsers: Vec::new(),
used: Vec::new(),
};
let mut hops: Vec<Hop> = Vec::with_capacity(written.len());
for (at, hop) in written.iter().enumerate() {
if matches!(hops.last().map(|h| &h.choice), Some(Choice::AutoStar)) {
return Err(CompileError::AfterAutoStar { hop: at });
}
hops.push(b.hop(at, hop, &config.fallback)?);
}
if let Some(key) = config
.settings
.keys()
.find(|k| !b.used.contains(&k.as_str()))
{
return Err(CompileError::StraySettings { key: key.clone() });
}
let detects = hops
.iter()
.any(|h| matches!(h.choice, Choice::Auto | Choice::AutoStar));
let mut detect_ids = Vec::new();
if detects {
for p in resolve.candidates() {
if p.detectable() && !p.signature().is_literal_free() {
detect_ids.push(b.intern(p));
}
}
}
let parsers = b.parsers;
let set = SignatureSet::new(detect_ids.iter().map(|&id| parsers[id].signature()))?;
let dotted = parsers.iter().map(|p| format!("{}.", p.name())).collect();
let counters = Counters::new(&parsers, config.max_depth);
let gated = parsers.iter().map(|p| gate_pays(p.as_ref())).collect();
Ok(Self {
parsers,
gated,
dotted,
hops,
detect: Candidates {
ids: detect_ids,
set,
},
counters,
max_depth: config.max_depth,
max_invocations: config.max_invocations,
framing: config.framing.clone(),
start: config.framing.start().map_err(CompileError::FramingStart)?,
})
}
pub fn chain(text: &str, resolve: &dyn Resolve) -> Result<Self, CompileError> {
Self::compile(&ParseConfig::chain(text)?, resolve)
}
#[must_use]
pub fn source_state(&self) -> SourceState {
SourceState {
scan: self.scan(),
frames: FrameState::default(),
}
}
fn scan(&self) -> Scan {
Scan {
scratch: self.detect.set.scratch(),
ranked: Vec::new(),
}
}
pub fn frame<'a>(
&self,
input: &'a [u8],
state: &mut SourceState,
now: Instant,
out: &mut Vec<Frame<'a>>,
) -> Result<(), ParseError> {
self.framing
.frame(input, &mut state.frames, now, self.start.as_ref(), out)
}
pub fn flush(&self, state: &mut SourceState, now: Instant, out: &mut Vec<Frame<'static>>) {
self.framing.flush(&mut state.frames, Some(now), out);
}
pub fn finish(&self, state: &mut SourceState, out: &mut Vec<Frame<'static>>) {
self.framing.flush(&mut state.frames, None, out);
}
#[must_use]
pub fn detects(&self) -> bool {
self.hops
.iter()
.any(|hop| !matches!(hop.choice, Choice::Named(_)))
}
pub fn parse<'a>(
&self,
input: &'a [u8],
state: &mut SourceState,
out: &mut dyn FieldSink<'a>,
) -> Outcome {
self.run(input, &mut state.scan, out, None, None)
}
#[must_use]
pub fn batch(&self) -> Batch<'_> {
let per_parser = || vec![0_u64; self.parsers.len()];
Batch {
plan: self,
counts: Counts {
parsers: if cfg!(feature = "metrics") {
let empty = || ParserCounts { held: Vec::new() };
self.parsers.iter().map(|_| empty()).collect()
} else {
Vec::new()
},
layer: (0..self.max_depth).map(|_| per_parser()).collect(),
detected: per_parser(),
error: per_parser(),
fallback: 0,
truncated: 0,
},
}
}
fn count(&self, counts: Option<&mut Counts>, what: Count) {
let Some(counts) = counts else {
match what {
Count::Layer { depth, id } => self.counters.layer[depth - 1][id].increment(1),
Count::Detected(id) => self.counters.detected[id].increment(1),
Count::Error(id) => self.counters.error[id].increment(1),
Count::Fallback => self.counters.fallback.increment(1),
Count::Truncated => self.counters.truncated.increment(1),
}
return;
};
match what {
Count::Layer { depth, id } => counts.layer[depth - 1][id] += 1,
Count::Detected(id) => counts.detected[id] += 1,
Count::Error(id) => counts.error[id] += 1,
Count::Fallback => counts.fallback += 1,
Count::Truncated => counts.truncated += 1,
}
}
pub fn parse_stateless<'a>(&self, input: &'a [u8], out: &mut dyn FieldSink<'a>) -> Outcome {
self.run(input, &mut self.scan(), out, None, None)
}
pub fn parse_traced<'a>(
&self,
input: &'a [u8],
state: &mut SourceState,
out: &mut dyn FieldSink<'a>,
trace: &mut Trace,
) -> Outcome {
trace.steps.clear();
self.run(input, &mut state.scan, out, Some(trace), None)
}
fn run<'a>(
&self,
input: &'a [u8],
scan: &mut Scan,
out: &mut dyn FieldSink<'a>,
trace: Option<&mut Trace>,
counts: Option<&mut Counts>,
) -> Outcome {
let passes = PASSES_PER_LEVEL.saturating_mul(self.max_depth);
let budget = Budget::new(input.len().saturating_mul(passes).max(BUDGET_FLOOR));
let start = input.as_ptr().addr();
let mut cx = Run {
scan,
trace,
budget: &budget,
record: start..start + input.len(),
mark: out.mark(),
calls: self.max_invocations,
status: Status::Parsed,
layers: 0,
rest: None,
error: None,
stop: false,
counts,
};
let at = At {
hop: 0,
depth: 1,
origin: Origin::Record,
need: Need::Required,
};
self.hop(at, input, out, &mut cx);
match cx.status {
Status::Parsed | Status::DepthLimit => {}
Status::Truncated => self.count(cx.counts.as_deref_mut(), Count::Truncated),
Status::Fallback | Status::Rejected => {
self.count(cx.counts.as_deref_mut(), Count::Fallback);
}
}
Outcome {
status: cx.status,
layers: cx.layers,
rest: cx.rest,
error: cx.error,
}
}
fn hop<'i>(&self, at: At<'_>, input: &'i [u8], out: &mut dyn FieldSink<'i>, cx: &mut Run<'_>) {
if cx.stop {
return;
}
let won = match self.choose(at, input, out, cx) {
Tried::Won(won) => won,
Tried::Stopped => return,
Tried::Missed(_) if at.need == Need::Optional => return,
Tried::Missed(error) => {
let Some(won) = self.fall_back(at, Some(input), error, out, cx) else {
return;
};
won
}
};
self.below(at, won, out, cx);
}
fn choose<'i>(
&self,
at: At<'_>,
input: &'i [u8],
out: &mut dyn FieldSink<'i>,
cx: &mut Run<'_>,
) -> Tried<'i> {
let mut first_error = None;
let mut next = 0;
let named = match &self.hops[at.hop].choice {
Choice::Named(ids) => Some(ids),
Choice::Auto | Choice::AutoStar => {
if !cx.budget.charge(input.len()) {
cx.truncate(at, input);
return Tried::Stopped;
}
self.rank(input, cx.scan);
None
}
};
loop {
let id = if let Some(ids) = named {
let Some(&id) = ids.get(next) else { break };
if self.gated[id] {
if !cx.budget.charge(input.len()) {
cx.truncate(at, input);
return Tried::Stopped;
}
if !self.parsers[id].signature().may_match(input) {
next += 1;
continue;
}
}
id
} else {
let Some(&(_, _, i)) = cx.scan.ranked.get(next) else {
break;
};
self.detect.ids[i]
};
next += 1;
match self.attempt(id, at, Event::Parsed, input, out, cx) {
Attempt::Won(won) => {
if named.is_none() {
self.count(cx.counts.as_deref_mut(), Count::Detected(id));
}
return Tried::Won(won);
}
Attempt::NoMatch => {}
Attempt::Error(e) => {
first_error.get_or_insert(e);
}
Attempt::Stopped => return Tried::Stopped,
}
}
Tried::Missed(first_error)
}
fn rank(&self, bytes: &[u8], scan: &mut Scan) {
scan.ranked.clear();
let Scan { scratch, ranked } = scan;
self.detect.set.for_each_match(bytes, scratch, |m| {
let sig = self.parsers[self.detect.ids[m.index]].signature();
ranked.push((Reverse(sig.specificity()), Reverse(sig.priority()), m.index));
});
ranked.sort_unstable();
}
fn want(&self, hop: usize) -> Want<'_> {
let detect = Some(&self.detect.set);
if matches!(self.hops[hop].choice, Choice::AutoStar) {
return Want::Values {
body_too: false,
detect,
};
}
let Some(next) = self.hops.get(hop + 1) else {
return Want::Nothing;
};
match &next.selector {
Selector::Body => Want::Nothing,
Selector::Field(name) => Want::Field(name),
Selector::Each => Want::Values {
body_too: true,
detect: detect.filter(|_| !matches!(next.choice, Choice::Named(_))),
},
}
}
fn attempt<'i>(
&self,
id: usize,
at: At<'_>,
win: Event,
input: &'i [u8],
out: &mut dyn FieldSink<'i>,
cx: &mut Run<'_>,
) -> Attempt<'i> {
if cx.calls == 0 || !cx.budget.charge(input.len()) {
cx.truncate(at, input);
return Attempt::Stopped;
}
cx.calls -= 1;
let parser = &self.parsers[id];
let hop = &self.hops[at.hop];
let prefix = match &hop.prefix {
Some(p) => p.as_str(),
None if at.depth == 1 => "",
None => self.dotted[id].as_str(),
};
let mark = out.mark();
out.push_prefix(prefix);
let (budget, traced) = (cx.budget, cx.trace.is_some());
let own = cx
.counts
.as_deref_mut()
.and_then(|held| held.parsers.get_mut(id));
let (result, got) = match self.want(at.hop) {
Want::Nothing => (call(parser.as_ref(), input, out, own), Vec::new()),
want => {
let mut capture = Capture::new(&mut *out, want, budget, traced);
let result = call(parser.as_ref(), input, &mut capture, own);
(result, capture.into_values())
}
};
out.pop_prefix();
if cx.budget.is_spent() {
out.rollback(mark);
cx.truncate(at, input);
return Attempt::Stopped;
}
let body = match result {
Ok(Parsed::Done) => None,
Ok(Parsed::Body { span, .. }) => {
let Some(body) = input.get(span) else {
out.rollback(mark);
let error = ParseError::Malformed {
offset: 0,
reason: "a parser returned a body outside its input",
};
cx.step(at, Some(parser.name()), Event::Error(Failure::of(&error)));
return Attempt::Error(error);
};
Some(body)
}
Ok(Parsed::NoMatch) => {
out.rollback(mark);
return Attempt::NoMatch;
}
Err(error) => {
out.rollback(mark);
self.count(cx.counts.as_deref_mut(), Count::Error(id));
cx.step(at, Some(parser.name()), Event::Error(Failure::of(&error)));
return Attempt::Error(error);
}
};
cx.layers += 1;
let depth = at.depth;
self.count(cx.counts.as_deref_mut(), Count::Layer { depth, id });
let step = cx.step(at, Some(parser.name()), win);
Attempt::Won(Won { body, got, step })
}
fn fall_back<'i>(
&self,
at: At<'_>,
input: Option<&'i [u8]>,
error: Option<ParseError>,
out: &mut dyn FieldSink<'i>,
cx: &mut Run<'_>,
) -> Option<Won<'i>> {
let rest = input.and_then(|i| cx.span(i));
match (self.hops[at.hop].fallback, input) {
(Fallback::Reject, _) => {
out.rollback(cx.mark);
cx.raise(Status::Rejected, rest, error);
cx.layers = 0;
cx.stop = true;
if let Some(trace) = cx.trace.as_deref_mut() {
trace.steps.iter_mut().for_each(|step| step.kept = false);
}
cx.step(at, None, Event::Rejected);
None
}
(Fallback::Parser(id), Some(input)) => {
match self.attempt(id, at, Event::FallbackParsed, input, out, cx) {
Attempt::Won(won) => {
cx.raise(Status::Fallback, None, error);
Some(won)
}
Attempt::Stopped => None,
Attempt::NoMatch | Attempt::Error(_) => {
cx.raise(Status::Fallback, rest, error);
cx.step(at, None, Event::Unparsed);
None
}
}
}
(Fallback::Raw | Fallback::Parser(_), _) => {
cx.raise(Status::Fallback, rest, error);
cx.step(at, None, Event::Unparsed);
None
}
}
}
fn below<'i>(&self, at: At<'_>, won: Won<'i>, out: &mut dyn FieldSink<'i>, cx: &mut Run<'_>) {
let parent = won.step;
let depth = at.depth + 1;
let body = Origin::Body { parent };
if matches!(self.hops[at.hop].choice, Choice::AutoStar) {
let down = At {
hop: at.hop,
depth,
origin: body,
need: Need::Optional,
};
if at.depth == self.max_depth {
self.at_the_limit(down, parent, &won, cx);
} else {
if let Some(input) = won.body {
self.hop(down, input, out, cx);
}
for value in won.got {
self.value(down, parent, value, out, cx);
}
}
} else if let Some(next) = self.hops.get(at.hop + 1) {
let mut down = At {
hop: at.hop + 1,
depth,
origin: body,
need: Need::Required,
};
match &next.selector {
Selector::Body => match won.body {
Some(input) => self.hop(down, input, out, cx),
None => self.missing(down, Event::NoBody, out, cx),
},
Selector::Field(name) => {
if let Some(value) = won.got.into_iter().next() {
self.value(down, parent, value, out, cx);
} else {
down.origin = Origin::Value { parent, name };
self.missing(down, Event::NoField, out, cx);
}
}
Selector::Each => {
down.need = Need::Optional;
for value in won.got {
self.value(down, parent, value, out, cx);
}
}
}
}
}
fn value<'i>(
&self,
at: At<'_>,
parent: usize,
value: Captured<'i>,
out: &mut dyn FieldSink<'i>,
cx: &mut Run<'_>,
) {
let at = At {
origin: Origin::Value {
parent,
name: value.name.as_deref().unwrap_or_default(),
},
..at
};
match value.value.bytes {
Cow::Borrowed(bytes) => self.hop(at, bytes, out, cx),
Cow::Owned(bytes) => {
self.hop(at, &bytes, &mut Promote::new(out, cx.budget), cx);
}
}
}
fn missing(&self, at: At<'_>, event: Event, out: &mut dyn FieldSink<'_>, cx: &mut Run<'_>) {
if cx.stop {
return;
}
cx.step(at, None, event);
self.fall_back(at, None, None, out, cx);
}
fn at_the_limit(&self, at: At<'_>, parent: usize, won: &Won<'_>, cx: &mut Run<'_>) {
let body = won.body.map(|input| (at.origin, input));
let values = won.got.iter().map(|c| {
let name = c.name.as_deref().unwrap_or_default();
(Origin::Value { parent, name }, &*c.value.bytes)
});
for (origin, input) in body.into_iter().chain(values) {
let at = At { origin, ..at };
if cx.stop {
return;
}
if !cx.budget.charge(input.len()) {
cx.truncate(at, input);
return;
}
self.rank(input, cx.scan);
if !cx.scan.ranked.is_empty() {
let rest = cx.span(input);
cx.raise(Status::DepthLimit, rest, None);
cx.step(at, None, Event::DepthLimit);
return;
}
}
}
}
fn call<'a>(
parser: &dyn Parser,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
own: Option<&mut ParserCounts>,
) -> Result<Parsed, ParseError> {
match own {
Some(counts) => parser.parse_counted(input, out, counts),
None => parser.parse(input, out),
}
}
pub fn gate_pays(parser: &dyn Parser) -> bool {
match (parser.cost(), parser.signature().cost()) {
(Some(p), Some(s)) => {
s.miss.ns(crate::cost::REFERENCE_BYTES) < p.miss.ns(crate::cost::REFERENCE_BYTES)
}
_ => true,
}
}