use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;
use crate::constructs::{
ChildStateSpec, ConstructParser, ConstructParserResult, FromInvocation, GroupParser,
Invocation, NodesOutcome, NodesParser, RootNodesParser, StopSpec,
};
use crate::error::{DiagnosticData, Diagnostics, ParseError, Recovery};
use crate::node::{BuildId, NodeKind};
use crate::scopes::{CallableQuery, CallableSyntax};
use crate::source::{
IntoSourceResolver, Source, SourceOrigin, SourceResolver, SourceSpan,
};
use crate::spec::CallableSpec;
use crate::state::{Lang, ParsingState, ParsingStateDelta, ParsingStateStack};
use crate::token::{GroupRule, Token, TokenKind, TokenReader, Tokenization};
use super::ParserSession;
pub trait ParseDriver<L: Lang>: fmt::Debug + Send + Sync {
fn recovery(&self) -> Recovery {
Recovery::Strict
}
fn diagnostics_limit(&self) -> Option<usize> {
None
}
fn recover(
&self,
session: &mut ParserSession<L>,
state: &ParsingState<L>,
data: Box<dyn DiagnosticData>,
span: SourceSpan<L::SourceOrigin>,
) -> Result<(), ParseError<L::SourceOrigin>> {
let data = self.refine_diagnostic(data, state);
session.recover(self.recovery(), data, span)
}
fn make_token_reader<'s>(
&'s self,
source: &'s Arc<Source<L::SourceOrigin>>,
) -> Box<dyn TokenReader<'s, L> + 's> {
<L::Tokenization as Tokenization<L>>::make_token_reader(source)
}
fn probe_token<'s>(
&self,
tokens: &mut dyn TokenReader<'s, L>,
session: &ParserSession<L>,
state: &Arc<ParsingState<L>>,
) -> ConstructParserResult<L, Option<Token<L>>> {
match tokens.peek(state) {
Ok(token) => Ok(Some(token)),
Err(error) => {
if self.recovery() == Recovery::Tolerant && error.recovery().is_some() {
return Ok(None);
}
let span = error.span().clone();
Err(ParseError::from_token_error(error.kind().clone(), span)
.with_frames(session.snapshot_frames()))
}
}
}
fn resolve_command(
&self,
state: &ParsingState<L>,
token: &Token<L>,
tokens: &dyn TokenReader<'_, L>,
) -> Result<CommandResolution<L>, ParseError<L::SourceOrigin>> {
CommandResolver::resolve_command(&(), state, token, tokens)
}
fn make_paragraph_break_node(
&self,
state: &ParsingState<L>,
break_span: &SourceSpan<L::SourceOrigin>,
) -> NodeKind<L> {
let _ = state;
NodeKind::chars(break_span.span())
}
fn refine_diagnostic(
&self,
data: Box<dyn DiagnosticData>,
state: &ParsingState<L>,
) -> Box<dyn DiagnosticData> {
let _ = state;
data
}
fn observe_transition(
&self,
ext: &mut L::SessionExt,
diagnostics: &mut Diagnostics<L::SourceOrigin>,
prev: &ParsingState<L>,
new: &ParsingState<L>,
delta: &ParsingStateDelta<L>,
) -> Result<(), ParseError<L::SourceOrigin>> {
let _ = (ext, diagnostics, prev, new, delta);
Ok(())
}
fn observe_parse_start(
&self,
source: &Arc<Source<L::SourceOrigin>>,
initial_state: &Arc<ParsingState<L>>,
diagnostics: &mut Diagnostics<L::SourceOrigin>,
) {
let _ = (source, initial_state, diagnostics);
}
fn resolve_state_event(
&self,
event: &L::Event,
stack: &ParsingStateStack<L>,
) -> Result<Option<ParsingStateDelta<L>>, ParseError<L::SourceOrigin>> {
let _ = (event, stack);
Ok(None)
}
fn source_resolver(&self) -> Option<&dyn SourceResolver<L::SourceOrigin>> {
None
}
fn group_interior_delta(
&self,
base: &ParsingState<L>,
rule: &Arc<GroupRule<L>>,
) -> Option<ParsingStateDelta<L>> {
let _ = (base, rule);
None
}
#[allow(clippy::type_complexity)]
fn make_root_parser<'p>(
&'p self,
) -> Result<Box<dyn ConstructParser<L, Output = BuildId> + 'p>, ParseError<L::SourceOrigin>>
where
L::InvocationSyntax: FromInvocation<L>,
{
Ok(Box::new(RootNodesParser::new()))
}
#[allow(clippy::type_complexity)]
fn make_nodes_parser<'p>(
&'p self,
stop: StopSpec<'p, L>,
child_states: ChildStateSpec<'p, L>,
) -> Result<
Box<dyn ConstructParser<L, Output = NodesOutcome<L>> + 'p>,
ParseError<L::SourceOrigin>,
>
where
L::InvocationSyntax: FromInvocation<L>,
{
Ok(Box::new(NodesParser::new(stop).with_child_states(child_states)))
}
#[allow(clippy::type_complexity)]
fn make_group_parser<'p>(
&'p self,
open: &Token<L>,
rule: Arc<GroupRule<L>>,
child_states: ChildStateSpec<'p, L>,
) -> Result<
Box<dyn ConstructParser<L, Output = BuildId> + 'p>,
ParseError<L::SourceOrigin>,
>
where
L::InvocationSyntax: FromInvocation<L>,
{
Ok(Box::new(
GroupParser::new(open.clone(), rule).with_child_states(child_states),
))
}
#[allow(clippy::type_complexity)]
fn make_invocation_parser<'a>(
&'a self,
invocation: Invocation<'a, L>,
) -> Result<
Box<dyn ConstructParser<L, Output = BuildId> + 'a>,
ParseError<L::SourceOrigin>,
>
where
L::InvocationSyntax: FromInvocation<L>,
{
let spec = invocation.spec;
spec.make_invocation_parser(invocation)
}
}
pub trait CommandResolver<L: Lang>: fmt::Debug + Send + Sync {
fn resolve_command(
&self,
state: &ParsingState<L>,
token: &Token<L>,
tokens: &dyn TokenReader<'_, L>,
) -> Result<CommandResolution<L>, ParseError<L::SourceOrigin>>;
}
impl<L: Lang> CommandResolver<L> for () {
fn resolve_command(
&self,
state: &ParsingState<L>,
token: &Token<L>,
tokens: &dyn TokenReader<'_, L>,
) -> Result<CommandResolution<L>, ParseError<L::SourceOrigin>> {
let _ = (state, token, tokens);
Ok(CommandResolution::Unresolved {
detail: Some(
"missing command resolver in the parse driver; implement \
‘ParseDriver::resolve_command’, give ‘StdParseDriver’ a \
‘CommandResolver’, or use a preset"
.into(),
),
})
}
}
pub struct ScopesCommandResolver<L: Lang> {
pub command_type: L::CallableTypeId,
}
impl<L: Lang> CommandResolver<L> for ScopesCommandResolver<L> {
fn resolve_command(
&self,
state: &ParsingState<L>,
token: &Token<L>,
tokens: &dyn TokenReader<'_, L>,
) -> Result<CommandResolution<L>, ParseError<L::SourceOrigin>> {
Ok(resolve_command_in_scopes(state, token, tokens, self.command_type))
}
}
impl<L: Lang> Clone for ScopesCommandResolver<L> {
fn clone(&self) -> Self {
ScopesCommandResolver { command_type: self.command_type }
}
}
impl<L: Lang> fmt::Debug for ScopesCommandResolver<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ScopesCommandResolver")
.field("command_type", &self.command_type)
.finish()
}
}
pub struct StdParseDriver<R = (), O: SourceOrigin = Option<String>> {
pub recovery: Recovery,
pub command_resolver: R,
pub source_resolver: Option<Arc<dyn SourceResolver<O>>>,
}
impl<R, O: SourceOrigin> StdParseDriver<R, O> {
pub fn new(recovery: Recovery, command_resolver: R) -> StdParseDriver<R, O> {
StdParseDriver { recovery, command_resolver, source_resolver: None }
}
pub fn with_source_resolver<M>(
mut self,
resolver: impl IntoSourceResolver<O, M>,
) -> StdParseDriver<R, O> {
self.source_resolver = Some(resolver.into_source_resolver());
self
}
}
impl<L: Lang, R: CommandResolver<L>> ParseDriver<L> for StdParseDriver<R, L::SourceOrigin> {
fn recovery(&self) -> Recovery {
self.recovery
}
fn resolve_command(
&self,
state: &ParsingState<L>,
token: &Token<L>,
tokens: &dyn TokenReader<'_, L>,
) -> Result<CommandResolution<L>, ParseError<L::SourceOrigin>> {
self.command_resolver.resolve_command(state, token, tokens)
}
fn source_resolver(&self) -> Option<&dyn SourceResolver<L::SourceOrigin>> {
self.source_resolver.as_deref()
}
}
impl<R: Clone, O: SourceOrigin> Clone for StdParseDriver<R, O> {
fn clone(&self) -> Self {
StdParseDriver {
recovery: self.recovery,
command_resolver: self.command_resolver.clone(),
source_resolver: self.source_resolver.clone(),
}
}
}
impl<R: fmt::Debug, O: SourceOrigin> fmt::Debug for StdParseDriver<R, O> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StdParseDriver")
.field("recovery", &self.recovery)
.field("command_resolver", &self.command_resolver)
.finish_non_exhaustive()
}
}
pub struct ResolvedCallable<L: Lang> {
pub callable_type: L::CallableTypeId,
pub spec: Arc<dyn CallableSpec<L>>,
}
impl<L: Lang> Clone for ResolvedCallable<L> {
fn clone(&self) -> Self {
ResolvedCallable { callable_type: self.callable_type, spec: Arc::clone(&self.spec) }
}
}
impl<L: Lang> fmt::Debug for ResolvedCallable<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ResolvedCallable")
.field("callable_type", &self.callable_type)
.field("spec", &self.spec)
.finish()
}
}
#[non_exhaustive]
pub enum CommandResolution<L: Lang> {
Resolved(ResolvedCallable<L>),
Unresolved {
detail: Option<String>,
},
Failed {
detail: Option<String>,
},
}
pub fn resolve_command_in_scopes<L: Lang>(
state: &ParsingState<L>,
token: &Token<L>,
tokens: &dyn TokenReader<'_, L>,
callable_type: L::CallableTypeId,
) -> CommandResolution<L> {
let TokenKind::Command { name, escape_char } = tokens.token_kind(token) else {
return CommandResolution::Unresolved { detail: None };
};
let query =
CallableQuery::new(callable_type, name, CallableSyntax::Command { escape_char });
match state.scopes().retrieve_spec(&query, state) {
Ok(Some(spec)) => {
CommandResolution::Resolved(ResolvedCallable { callable_type, spec })
}
Ok(None) => {
let mut detail = state.scopes().searched_providers().to_string();
if let Some(hint) = did_you_mean_hint(state, name, escape_char, callable_type)
{
detail.push_str("; ");
detail.push_str(&hint);
}
CommandResolution::Unresolved { detail: Some(detail) }
}
Err(error) => CommandResolution::Failed {
detail: Some(error.to_string()),
},
}
}
fn did_you_mean_hint<L: Lang>(
state: &ParsingState<L>,
name: &str,
escape_char: char,
callable_type: L::CallableTypeId,
) -> Option<String> {
const MAX_SUGGESTIONS: usize = 3;
let mut escape_trap: Option<String> = None; let mut suggestions: Vec<(String, String)> = Vec::new(); let escape_spelling = {
let mut s = String::with_capacity(escape_char.len_utf8() + name.len());
s.push(escape_char);
s.push_str(name);
s
};
let threshold = if name.chars().count() <= 4 { 1 } else { 2 };
for provider in state.scopes().providers().iter().rev() {
let Some(symbols) = provider.iter_symbols(callable_type, state.mode()) else {
continue; };
for entry in symbols {
if escape_trap.is_none() && entry.name == escape_spelling {
escape_trap = Some(provider.name().into());
} else if suggestions.len() < MAX_SUGGESTIONS
&& entry.name != name
&& !suggestions.iter().any(|(_, n)| n == entry.name)
&& edit_distance_at_most(entry.name, name, threshold)
{
suggestions.push((provider.name().into(), entry.name.into()));
}
}
}
let mut hint = String::new();
if let Some(provider) = escape_trap {
hint.push_str(&format!(
"invalid registration ‘{escape_spelling}’ in provider ‘{provider}’ \
(names must be registered without their escape character)"
));
}
if !suggestions.is_empty() {
if !hint.is_empty() {
hint.push_str("; ");
}
hint.push_str("did you mean ");
for (i, (provider, suggested)) in suggestions.iter().enumerate() {
if i > 0 {
hint.push_str(" or ");
}
hint.push_str(&format!(
"‘{escape_char}{suggested}’ (provider ‘{provider}’)"
));
}
hint.push('?');
}
(!hint.is_empty()).then_some(hint)
}
fn edit_distance_at_most(a: &str, b: &str, bound: usize) -> bool {
let a: Vec<char> = a.chars().collect();
let b: Vec<char> = b.chars().collect();
if a.len().abs_diff(b.len()) > bound {
return false;
}
let mut previous: Vec<usize> = (0..=b.len()).collect();
let mut current = vec![0usize; b.len() + 1];
for (i, &ca) in a.iter().enumerate() {
current[0] = i + 1;
let mut row_min = current[0];
for (j, &cb) in b.iter().enumerate() {
let substitution = previous[j] + usize::from(ca != cb);
current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
row_min = row_min.min(current[j + 1]);
}
if row_min > bound {
return false; }
core::mem::swap(&mut previous, &mut current);
}
previous[b.len()] <= bound
}
impl<L: Lang> From<Option<ResolvedCallable<L>>> for CommandResolution<L> {
fn from(resolved: Option<ResolvedCallable<L>>) -> Self {
match resolved {
Some(resolved) => CommandResolution::Resolved(resolved),
None => CommandResolution::Unresolved { detail: None },
}
}
}
impl<L: Lang> Clone for CommandResolution<L> {
fn clone(&self) -> Self {
match self {
CommandResolution::Resolved(resolved) => {
CommandResolution::Resolved(resolved.clone())
}
CommandResolution::Unresolved { detail } => {
CommandResolution::Unresolved { detail: detail.clone() }
}
CommandResolution::Failed { detail } => {
CommandResolution::Failed { detail: detail.clone() }
}
}
}
}
impl<L: Lang> fmt::Debug for CommandResolution<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CommandResolution::Resolved(resolved) => {
f.debug_tuple("Resolved").field(resolved).finish()
}
CommandResolution::Unresolved { detail } => {
f.debug_struct("Unresolved").field("detail", detail).finish()
}
CommandResolution::Failed { detail } => {
f.debug_struct("Failed").field("detail", detail).finish()
}
}
}
}