use alloc::boxed::Box;
use alloc::sync::Arc;
use core::fmt;
use crate::source::Source;
use crate::state::Lang;
use super::reader::{StdStreamPosition, StdTokenReader, TokenReader};
use super::token::StdToken;
pub trait Tokenization<L: Lang> {
type Token: Clone + fmt::Debug + PartialEq + Send + Sync;
type StreamPosition: Clone + fmt::Debug + PartialEq + Eq + Send + Sync;
fn make_token_reader<'s>(
source: &'s Arc<Source<L::SourceOrigin>>,
) -> Box<dyn TokenReader<'s, L> + 's>;
}
pub type Token<L> = <<L as Lang>::Tokenization as Tokenization<L>>::Token;
pub type StreamPosition<L> = <<L as Lang>::Tokenization as Tokenization<L>>::StreamPosition;
#[derive(Debug, Clone, Copy)]
pub struct StdTokenization;
impl<L: Lang<Tokenization = StdTokenization>> Tokenization<L> for StdTokenization {
type Token = StdToken<L>;
type StreamPosition = StdStreamPosition;
fn make_token_reader<'s>(
source: &'s Arc<Source<L::SourceOrigin>>,
) -> Box<dyn TokenReader<'s, L> + 's> {
Box::new(StdTokenReader::new(source))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::engine::{Language, ParseDriver, StdParseDriver};
use crate::node::{NodeBuildError, NodeKind, StagedChildren};
use crate::source::{SourcePos, SourceSpan};
use crate::state::{AllLangFeatures, ParsingState};
use alloc::string::String;
use core::sync::atomic::{AtomicUsize, Ordering};
use super::super::{TokenEdge, TokenKind, TokenResult};
#[derive(Debug, Clone, Copy)]
struct OwnTokenization;
impl<L: Lang<Tokenization = OwnTokenization>> Tokenization<L> for OwnTokenization {
type Token = StdToken<L>;
type StreamPosition = StdStreamPosition;
fn make_token_reader<'s>(
source: &'s Arc<Source<L::SourceOrigin>>,
) -> Box<dyn TokenReader<'s, L> + 's> {
Box::new(StdTokenReader::new(source))
}
}
#[derive(Debug, Clone, Copy)]
struct OwnLang;
#[derive(Debug, Clone, Copy)]
struct BareDriver;
impl ParseDriver<OwnLang> for BareDriver {}
impl Lang for OwnLang {
type Features = AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = OwnTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = BareDriver;
fn make_node_ext(
_kind: &NodeKind<Self>,
_span: &SourceSpan<Self::SourceOrigin>,
_state: &Arc<ParsingState<Self>>,
_children: StagedChildren<'_, Self>,
) -> Result<(), NodeBuildError> {
Ok(())
}
}
#[test]
fn a_language_with_its_own_tokenization_over_standard_tokens_parses() {
let language: Language<OwnLang> =
Language::new(BareDriver, ParsingState::lang_initial().expect("seed state"));
let result = language.parse("hello").expect("parse");
assert_eq!(result.tree.root().span_content(), "hello");
}
#[test]
fn the_ready_made_driver_carries_no_tokenization_bound() {
fn assert_drives<D: ParseDriver<OwnLang>>() {}
assert_drives::<StdParseDriver<(), Option<String>>>();
}
struct CountingReader<'s> {
inner: StdTokenReader<'s>,
peeks: &'s AtomicUsize,
}
impl<'s> CountingReader<'s> {
fn inner(&self) -> &dyn TokenReader<'s, CountingLang> {
&self.inner
}
fn inner_mut(&mut self) -> &mut dyn TokenReader<'s, CountingLang> {
&mut self.inner
}
}
impl<'s> TokenReader<'s, CountingLang> for CountingReader<'s> {
fn peek(
&mut self,
state: &Arc<ParsingState<CountingLang>>,
) -> TokenResult<CountingLang, StdToken<CountingLang>> {
self.peeks.fetch_add(1, Ordering::Relaxed);
self.inner_mut().peek(state)
}
fn move_to(&mut self, tok: &StdToken<CountingLang>, edge: TokenEdge) {
self.inner_mut().move_to(tok, edge);
}
fn move_to_position(&mut self, at: &StdStreamPosition) {
self.inner_mut().move_to_position(at);
}
fn token_kind<'t>(
&self,
tok: &'t StdToken<CountingLang>,
) -> TokenKind<'t, CountingLang>
where
's: 't,
{
self.inner().token_kind(tok)
}
fn source_span_between(
&self,
tok: &StdToken<CountingLang>,
a: TokenEdge,
b: TokenEdge,
) -> SourceSpan {
self.inner().source_span_between(tok, a, b)
}
fn position_here(&self) -> StdStreamPosition {
self.inner().position_here()
}
fn position_at(
&self,
tok: &StdToken<CountingLang>,
edge: TokenEdge,
) -> StdStreamPosition {
self.inner().position_at(tok, edge)
}
fn source_position_at(&self, at: &StdStreamPosition) -> SourcePos {
self.inner().source_position_at(at)
}
fn source_span_within(
&self,
begin: &StdStreamPosition,
end: &StdStreamPosition,
) -> Option<SourceSpan> {
self.inner().source_span_within(begin, end)
}
fn source_span_describing(
&self,
begin: &StdStreamPosition,
end: &StdStreamPosition,
) -> SourceSpan {
self.inner().source_span_describing(begin, end)
}
}
#[derive(Debug, Default)]
struct CountingDriver {
peeks: Arc<AtomicUsize>,
}
impl ParseDriver<CountingLang> for CountingDriver {
fn make_token_reader<'s>(
&'s self,
source: &'s Arc<Source<Option<String>>>,
) -> Box<dyn TokenReader<'s, CountingLang> + 's> {
Box::new(CountingReader { inner: StdTokenReader::new(source), peeks: &self.peeks })
}
}
#[derive(Debug, Clone, Copy)]
struct CountingLang;
impl Lang for CountingLang {
type Features = AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = CountingDriver;
fn make_node_ext(
_kind: &NodeKind<Self>,
_span: &SourceSpan<Self::SourceOrigin>,
_state: &Arc<ParsingState<Self>>,
_children: StagedChildren<'_, Self>,
) -> Result<(), NodeBuildError> {
Ok(())
}
}
#[test]
fn a_driver_override_installs_its_own_reader_over_the_language_declaration() {
let peeks = Arc::new(AtomicUsize::new(0));
let language: Language<CountingLang> = Language::new(
CountingDriver { peeks: Arc::clone(&peeks) },
ParsingState::lang_initial().expect("seed state"),
);
let result = language.parse("hi").expect("parse");
assert_eq!(result.tree.root().span_content(), "hi");
assert!(peeks.load(Ordering::Relaxed) > 0, "the driver's reader never ran");
}
}