use alloc::sync::Arc;
use core::fmt;
use crate::source::Span;
use crate::spec::CallableSpec;
use crate::state::Lang;
use super::reader::TokenEdge;
use super::rules::GroupRule;
pub enum TokenKind<'t, L: Lang> {
Char(char),
GroupOpen {
delim: &'t str,
rule: &'t Arc<GroupRule<L>>,
},
GroupClose {
delim: &'t str,
},
Command {
name: &'t str,
escape_char: char,
},
Specials {
callable_type: L::CallableTypeId,
name: &'t str,
spec: &'t Arc<dyn CallableSpec<L>>,
},
Comment {
start_delim: &'t str,
content: &'t str,
},
ParagraphBreak,
EndOfStream,
}
impl<L: Lang> TokenKind<'_, L> {
pub const fn as_str(&self) -> &'static str {
match self {
TokenKind::Char(_) => "Char",
TokenKind::GroupOpen { .. } => "GroupOpen",
TokenKind::GroupClose { .. } => "GroupClose",
TokenKind::Command { .. } => "Command",
TokenKind::Specials { .. } => "Specials",
TokenKind::Comment { .. } => "Comment",
TokenKind::ParagraphBreak => "ParagraphBreak",
TokenKind::EndOfStream => "EndOfStream",
}
}
}
impl<L: Lang> Clone for TokenKind<'_, L> {
fn clone(&self) -> Self {
*self
}
}
impl<L: Lang> Copy for TokenKind<'_, L> {}
impl<L: Lang> PartialEq for TokenKind<'_, L> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(TokenKind::Char(a), TokenKind::Char(b)) => a == b,
(
TokenKind::GroupOpen { delim: d1, rule: r1 },
TokenKind::GroupOpen { delim: d2, rule: r2 },
) => d1 == d2 && r1 == r2,
(TokenKind::GroupClose { delim: d1 }, TokenKind::GroupClose { delim: d2 }) => {
d1 == d2
}
(
TokenKind::Command { name: n1, escape_char: e1 },
TokenKind::Command { name: n2, escape_char: e2 },
) => n1 == n2 && e1 == e2,
(
TokenKind::Specials { callable_type: t1, name: n1, spec: s1 },
TokenKind::Specials { callable_type: t2, name: n2, spec: s2 },
) => t1 == t2 && n1 == n2 && Arc::ptr_eq(s1, s2),
(
TokenKind::Comment { start_delim: d1, content: c1 },
TokenKind::Comment { start_delim: d2, content: c2 },
) => d1 == d2 && c1 == c2,
(TokenKind::ParagraphBreak, TokenKind::ParagraphBreak) => true,
(TokenKind::EndOfStream, TokenKind::EndOfStream) => true,
_ => false,
}
}
}
impl<L: Lang> Eq for TokenKind<'_, L> {}
impl<L: Lang> fmt::Debug for TokenKind<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TokenKind::Char(c) => f.debug_tuple("Char").field(c).finish(),
TokenKind::GroupOpen { delim, rule } => f
.debug_struct("GroupOpen")
.field("delim", delim)
.field("rule", rule)
.finish(),
TokenKind::GroupClose { delim } => {
f.debug_struct("GroupClose").field("delim", delim).finish()
}
TokenKind::Command { name, escape_char } => f
.debug_struct("Command")
.field("name", name)
.field("escape_char", escape_char)
.finish(),
TokenKind::Specials { callable_type, name, spec } => f
.debug_struct("Specials")
.field("callable_type", callable_type)
.field("name", name)
.field("spec", spec)
.finish(),
TokenKind::Comment { start_delim, content } => f
.debug_struct("Comment")
.field("start_delim", start_delim)
.field("content", content)
.finish(),
TokenKind::ParagraphBreak => write!(f, "ParagraphBreak"),
TokenKind::EndOfStream => write!(f, "EndOfStream"),
}
}
}
impl<L: Lang> fmt::Display for TokenKind<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TokenKind::Char(c) => write!(f, "Char({:?})", c),
TokenKind::GroupOpen { delim, rule } => {
write!(f, "GroupOpen({}, {:?})", delim, rule.group_type)
}
TokenKind::GroupClose { delim } => write!(f, "GroupClose({})", delim),
TokenKind::Command { name, escape_char } => {
write!(f, "Command({}{})", escape_char, name)
}
TokenKind::Specials { name, .. } => write!(f, "Specials({})", name),
TokenKind::Comment { content, .. } => {
let (preview, truncated) = truncate_for_display(content);
write!(f, "Comment({:?}{})", preview, if truncated { "…" } else { "" })
}
TokenKind::ParagraphBreak => write!(f, "ParagraphBreak"),
TokenKind::EndOfStream => write!(f, "EndOfStream"),
}
}
}
pub(crate) enum StdTokenKindData<L: Lang> {
Char(char),
GroupOpen {
rule: Arc<GroupRule<L>>,
},
GroupClose,
Command {
escape_char: char,
post_space: Span,
},
Specials {
callable_type: L::CallableTypeId,
spec: Arc<dyn CallableSpec<L>>,
},
Comment {
start: Span,
post_space: Span,
},
ParagraphBreak,
EndOfStream,
}
pub struct StdToken<L: Lang> {
kind: StdTokenKindData<L>,
span: Span,
pre_space: Span,
}
fn assert_pre_space(span: Span, pre_space: Span) {
assert!(
pre_space.end() == span.start(),
"pre_space {:?} must end exactly at span start {:?}",
pre_space,
span
);
}
fn assert_post_space(span: Span, post_space: Span) {
assert!(
post_space.end() == span.end() && post_space.start() >= span.start(),
"post_space {:?} must be a trailing sub-range of span {:?}",
post_space,
span
);
}
impl<L: Lang> StdToken<L> {
pub fn char(c: char, span: Span, pre_space: Span) -> StdToken<L> {
assert_pre_space(span, pre_space);
StdToken { kind: StdTokenKindData::Char(c), span, pre_space }
}
pub fn group_open(rule: Arc<GroupRule<L>>, span: Span, pre_space: Span) -> StdToken<L> {
assert_pre_space(span, pre_space);
StdToken { kind: StdTokenKindData::GroupOpen { rule }, span, pre_space }
}
pub fn group_close(span: Span, pre_space: Span) -> StdToken<L> {
assert_pre_space(span, pre_space);
StdToken { kind: StdTokenKindData::GroupClose, span, pre_space }
}
pub fn command(
escape_char: char,
span: Span,
pre_space: Span,
post_space: Span,
) -> StdToken<L> {
assert_pre_space(span, pre_space);
assert_post_space(span, post_space);
StdToken {
kind: StdTokenKindData::Command { escape_char, post_space },
span,
pre_space,
}
}
pub fn specials(
callable_type: L::CallableTypeId,
spec: Arc<dyn CallableSpec<L>>,
span: Span,
pre_space: Span,
) -> StdToken<L> {
assert_pre_space(span, pre_space);
StdToken {
kind: StdTokenKindData::Specials { callable_type, spec },
span,
pre_space,
}
}
pub fn comment(
start: Span,
span: Span,
pre_space: Span,
post_space: Span,
) -> StdToken<L> {
assert_pre_space(span, pre_space);
assert_post_space(span, post_space);
assert!(
start.start() == span.start() && start.end() <= post_space.start(),
"comment start {:?} must be a leading sub-range of span {:?} ending before post_space {:?}",
start,
span,
post_space
);
StdToken { kind: StdTokenKindData::Comment { start, post_space }, span, pre_space }
}
pub fn paragraph_break(span: Span, pre_space: Span) -> StdToken<L> {
assert_pre_space(span, pre_space);
StdToken { kind: StdTokenKindData::ParagraphBreak, span, pre_space }
}
pub fn end_of_stream(pre_space: Span) -> StdToken<L> {
StdToken {
kind: StdTokenKindData::EndOfStream,
span: Span::empty(pre_space.end()),
pre_space,
}
}
pub(crate) fn kind_data(&self) -> &StdTokenKindData<L> {
&self.kind
}
#[cfg(test)]
pub(crate) fn span(&self) -> Span {
self.span
}
#[cfg(test)]
pub(crate) fn pre_space(&self) -> Span {
self.pre_space
}
pub(crate) fn post_space(&self) -> Span {
match &self.kind {
StdTokenKindData::Command { post_space, .. }
| StdTokenKindData::Comment { post_space, .. } => *post_space,
_ => Span::empty(self.span.end()),
}
}
pub(crate) fn edge_offset(&self, edge: TokenEdge) -> usize {
match edge {
TokenEdge::StartBeforePreSpace => self.pre_space.start(),
TokenEdge::Start => self.span.start(),
TokenEdge::ContentStart => match &self.kind {
StdTokenKindData::Comment { start, .. } => start.end(),
StdTokenKindData::Command { escape_char, .. } => {
self.span.start() + escape_char.len_utf8()
}
_ => self.span.start(),
},
TokenEdge::End => self.post_space().start(),
TokenEdge::EndPastPostSpace => self.span.end(),
}
}
#[cfg(test)]
pub(crate) fn with_pre_space(&self, pre_space: Span) -> StdToken<L> {
assert_pre_space(self.span, pre_space);
StdToken { kind: self.kind.clone(), span: self.span, pre_space }
}
}
impl<L: Lang> Clone for StdTokenKindData<L> {
fn clone(&self) -> Self {
match self {
StdTokenKindData::Char(c) => StdTokenKindData::Char(*c),
StdTokenKindData::GroupOpen { rule } => {
StdTokenKindData::GroupOpen { rule: Arc::clone(rule) }
}
StdTokenKindData::GroupClose => StdTokenKindData::GroupClose,
StdTokenKindData::Command { escape_char, post_space } => {
StdTokenKindData::Command {
escape_char: *escape_char,
post_space: *post_space,
}
}
StdTokenKindData::Specials { callable_type, spec } => {
StdTokenKindData::Specials {
callable_type: *callable_type,
spec: Arc::clone(spec),
}
}
StdTokenKindData::Comment { start, post_space } => {
StdTokenKindData::Comment { start: *start, post_space: *post_space }
}
StdTokenKindData::ParagraphBreak => StdTokenKindData::ParagraphBreak,
StdTokenKindData::EndOfStream => StdTokenKindData::EndOfStream,
}
}
}
impl<L: Lang> Clone for StdToken<L> {
fn clone(&self) -> Self {
StdToken { kind: self.kind.clone(), span: self.span, pre_space: self.pre_space }
}
}
impl<L: Lang> PartialEq for StdTokenKindData<L> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(StdTokenKindData::Char(a), StdTokenKindData::Char(b)) => a == b,
(
StdTokenKindData::GroupOpen { rule: r1 },
StdTokenKindData::GroupOpen { rule: r2 },
) => r1 == r2,
(StdTokenKindData::GroupClose, StdTokenKindData::GroupClose) => true,
(
StdTokenKindData::Command { escape_char: e1, post_space: p1 },
StdTokenKindData::Command { escape_char: e2, post_space: p2 },
) => e1 == e2 && p1 == p2,
(
StdTokenKindData::Specials { callable_type: t1, spec: s1 },
StdTokenKindData::Specials { callable_type: t2, spec: s2 },
) => t1 == t2 && Arc::ptr_eq(s1, s2),
(
StdTokenKindData::Comment { start: s1, post_space: p1 },
StdTokenKindData::Comment { start: s2, post_space: p2 },
) => s1 == s2 && p1 == p2,
(StdTokenKindData::ParagraphBreak, StdTokenKindData::ParagraphBreak) => true,
(StdTokenKindData::EndOfStream, StdTokenKindData::EndOfStream) => true,
_ => false,
}
}
}
impl<L: Lang> Eq for StdTokenKindData<L> {}
impl<L: Lang> PartialEq for StdToken<L> {
fn eq(&self, other: &Self) -> bool {
self.kind == other.kind && self.span == other.span && self.pre_space == other.pre_space
}
}
impl<L: Lang> Eq for StdToken<L> {}
impl<L: Lang> fmt::Debug for StdTokenKindData<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StdTokenKindData::Char(c) => f.debug_tuple("Char").field(c).finish(),
StdTokenKindData::GroupOpen { rule } => {
f.debug_struct("GroupOpen").field("rule", rule).finish()
}
StdTokenKindData::GroupClose => write!(f, "GroupClose"),
StdTokenKindData::Command { escape_char, post_space } => f
.debug_struct("Command")
.field("escape_char", escape_char)
.field("post_space", post_space)
.finish(),
StdTokenKindData::Specials { callable_type, spec } => f
.debug_struct("Specials")
.field("callable_type", callable_type)
.field("spec", spec)
.finish(),
StdTokenKindData::Comment { start, post_space } => f
.debug_struct("Comment")
.field("start", start)
.field("post_space", post_space)
.finish(),
StdTokenKindData::ParagraphBreak => write!(f, "ParagraphBreak"),
StdTokenKindData::EndOfStream => write!(f, "EndOfStream"),
}
}
}
impl<L: Lang> fmt::Debug for StdToken<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StdToken")
.field("kind", &self.kind)
.field("span", &self.span)
.field("pre_space", &self.pre_space)
.finish()
}
}
fn truncate_for_display(content: &str) -> (&str, bool) {
const MAX_DISPLAY_CONTENT: usize = 24;
if content.len() <= MAX_DISPLAY_CONTENT {
return (content, false);
}
let mut end = MAX_DISPLAY_CONTENT;
while !content.is_char_boundary(end) {
end -= 1;
}
(&content[..end], true)
}
#[cfg(test)]
mod tests {
use super::{StdToken, StdTokenKindData, TokenEdge, TokenKind, truncate_for_display};
use crate::source::Span;
use crate::spec::{CallableSpec, StdCallableSpec};
use crate::state::{Lang, TrivialLang};
use crate::token::{GroupRule, StdTokenization, Token};
use alloc::format;
use alloc::sync::Arc;
#[derive(Debug, Clone, Copy)]
struct PlainLang;
impl TrivialLang for PlainLang {}
fn rule() -> Arc<GroupRule<PlainLang>> {
Arc::new(GroupRule { group_type: 0, open: "{".into(), close: "}".into() })
}
fn spec() -> Arc<dyn CallableSpec<PlainLang>> {
Arc::new(StdCallableSpec::default())
}
#[test]
fn a_trivial_lang_gets_the_standard_token_from_the_blanket_impl() {
fn assert_std_tokenization<L: Lang<Tokenization = StdTokenization>>() {}
assert_std_tokenization::<PlainLang>();
let token: Token<PlainLang> = StdToken::char('a', Span::new(0, 1), Span::empty(0));
assert_eq!(token, StdToken::char('a', Span::new(0, 1), Span::empty(0)));
}
#[test]
fn every_constructor_records_its_kind_and_spans() {
let tokens: [(StdToken<PlainLang>, &str, Span, Span); 8] = [
(
StdToken::char('a', Span::new(1, 2), Span::empty(1)),
"Char",
Span::new(1, 2),
Span::empty(2),
),
(
StdToken::group_open(rule(), Span::new(0, 1), Span::empty(0)),
"GroupOpen",
Span::new(0, 1),
Span::empty(1),
),
(
StdToken::group_close(Span::new(3, 4), Span::empty(3)),
"GroupClose",
Span::new(3, 4),
Span::empty(4),
),
(
StdToken::command('\\', Span::new(0, 6), Span::empty(0), Span::new(4, 6)),
"Command",
Span::new(0, 6),
Span::new(4, 6),
),
(
StdToken::specials(0, spec(), Span::new(2, 3), Span::new(1, 2)),
"Specials",
Span::new(2, 3),
Span::empty(3),
),
(
StdToken::comment(
Span::new(0, 1),
Span::new(0, 8),
Span::empty(0),
Span::new(7, 8),
),
"Comment",
Span::new(0, 8),
Span::new(7, 8),
),
(
StdToken::paragraph_break(Span::new(2, 4), Span::empty(2)),
"ParagraphBreak",
Span::new(2, 4),
Span::empty(4),
),
(
StdToken::end_of_stream(Span::new(1, 3)),
"EndOfStream",
Span::empty(3),
Span::empty(3),
),
];
for (token, kind_name, span, post_space) in &tokens {
assert_eq!(token.span(), *span, "{kind_name}");
assert_eq!(token.post_space(), *post_space, "{kind_name}");
assert_eq!(
token.edge_offset(TokenEdge::StartBeforePreSpace),
token.pre_space().start(),
"{kind_name}"
);
assert_eq!(token.edge_offset(TokenEdge::Start), span.start(), "{kind_name}");
assert_eq!(token.edge_offset(TokenEdge::End), post_space.start(), "{kind_name}");
assert_eq!(
token.edge_offset(TokenEdge::EndPastPostSpace),
span.end(),
"{kind_name}"
);
assert_eq!(token.clone(), *token, "{kind_name}");
}
assert_eq!(tokens[3].0.edge_offset(TokenEdge::ContentStart), 1); assert_eq!(tokens[5].0.edge_offset(TokenEdge::ContentStart), 1); assert_eq!(tokens[0].0.edge_offset(TokenEdge::ContentStart), 1); }
#[test]
fn the_kind_data_of_each_constructor_is_its_own_variant() {
use alloc::vec;
fn name(data: &StdTokenKindData<PlainLang>) -> &'static str {
match data {
StdTokenKindData::Char(_) => "Char",
StdTokenKindData::GroupOpen { .. } => "GroupOpen",
StdTokenKindData::GroupClose => "GroupClose",
StdTokenKindData::Command { .. } => "Command",
StdTokenKindData::Specials { .. } => "Specials",
StdTokenKindData::Comment { .. } => "Comment",
StdTokenKindData::ParagraphBreak => "ParagraphBreak",
StdTokenKindData::EndOfStream => "EndOfStream",
}
}
let one = Span::new(0, 1);
let none = Span::empty(0);
let tokens: vec::Vec<StdToken<PlainLang>> = vec![
StdToken::char('a', one, none),
StdToken::group_open(rule(), one, none),
StdToken::group_close(one, none),
StdToken::command('\\', Span::new(0, 4), none, Span::empty(4)),
StdToken::specials(0, spec(), one, none),
StdToken::comment(one, Span::new(0, 5), none, Span::empty(5)),
StdToken::paragraph_break(Span::new(0, 2), none),
StdToken::end_of_stream(none),
];
let expected = [
"Char",
"GroupOpen",
"GroupClose",
"Command",
"Specials",
"Comment",
"ParagraphBreak",
"EndOfStream",
];
for (token, kind_name) in tokens.iter().zip(expected) {
assert_eq!(name(token.kind_data()), kind_name);
}
}
#[test]
fn tokens_compare_specs_by_identity_and_rules_structurally() {
let one = spec();
let same = Arc::clone(&one);
let other = spec();
let token =
|spec| StdToken::<PlainLang>::specials(0, spec, Span::new(0, 1), Span::empty(0));
assert_eq!(token(Arc::clone(&one)), token(same));
assert_ne!(token(one), token(other));
let group = |rule| StdToken::<PlainLang>::group_open(rule, Span::new(0, 1), Span::empty(0));
assert_eq!(group(rule()), group(rule()));
}
#[test]
#[should_panic(expected = "must end exactly at span start")]
fn a_token_with_incoherent_pre_space_panics_in_all_builds() {
let _ = StdToken::<PlainLang>::char('a', Span::new(5, 6), Span::empty(3));
}
#[test]
#[should_panic(expected = "must be a trailing sub-range of span")]
fn a_command_token_with_a_detached_post_space_panics_in_all_builds() {
let _ = StdToken::<PlainLang>::command(
'\\',
Span::new(0, 4),
Span::empty(0),
Span::new(4, 5),
);
}
#[test]
#[should_panic(expected = "must be a leading sub-range of span")]
fn a_comment_token_whose_start_is_not_leading_panics_in_all_builds() {
let _ = StdToken::<PlainLang>::comment(
Span::new(1, 2),
Span::new(0, 5),
Span::empty(0),
Span::empty(5),
);
}
#[test]
fn the_views_as_str_answers_the_bare_variant_name() {
use alloc::vec;
fn expected(kind: &TokenKind<'_, PlainLang>) -> &'static str {
match kind {
TokenKind::Char(_) => "Char",
TokenKind::GroupOpen { .. } => "GroupOpen",
TokenKind::GroupClose { .. } => "GroupClose",
TokenKind::Command { .. } => "Command",
TokenKind::Specials { .. } => "Specials",
TokenKind::Comment { .. } => "Comment",
TokenKind::ParagraphBreak => "ParagraphBreak",
TokenKind::EndOfStream => "EndOfStream",
}
}
let rule = rule();
let spec = spec();
let kinds: vec::Vec<TokenKind<'_, PlainLang>> = vec![
TokenKind::Char('a'),
TokenKind::GroupOpen { delim: "{", rule: &rule },
TokenKind::GroupClose { delim: "}" },
TokenKind::Command { name: "frac", escape_char: '\\' },
TokenKind::Specials { callable_type: 0, name: "~", spec: &spec },
TokenKind::Comment { start_delim: "%", content: " note" },
TokenKind::ParagraphBreak,
TokenKind::EndOfStream,
];
for kind in &kinds {
assert_eq!(kind.as_str(), expected(kind));
}
}
#[test]
fn views_compare_specs_by_identity_and_rules_structurally() {
let one = spec();
let same = Arc::clone(&one);
let other = spec();
fn view(spec: &Arc<dyn CallableSpec<PlainLang>>) -> TokenKind<'_, PlainLang> {
TokenKind::Specials { callable_type: 0, name: "~", spec }
}
assert_eq!(view(&one), view(&same));
assert_ne!(view(&one), view(&other));
let one_rule = rule();
let twin = rule();
let opened: TokenKind<'_, PlainLang> =
TokenKind::GroupOpen { delim: "{", rule: &one_rule };
assert_eq!(opened, TokenKind::GroupOpen { delim: "{", rule: &twin });
}
#[test]
fn the_views_display_renders_the_written_spelling() {
use alloc::string::ToString;
let command: TokenKind<'_, PlainLang> =
TokenKind::Command { name: "vec", escape_char: '@' };
assert_eq!(command.to_string(), "Command(@vec)");
let comment: TokenKind<'_, PlainLang> = TokenKind::Comment {
start_delim: "%",
content: "0123456789012345678901234567890",
};
assert_eq!(comment.to_string(), "Comment(\"012345678901234567890123\"…)");
}
#[test]
fn truncate_for_display_stops_at_char_boundaries() {
assert_eq!(truncate_for_display("short"), ("short", false));
let ascii = "abcdefghijklmnopqrstuvwxyz";
assert_eq!(truncate_for_display(ascii), ("abcdefghijklmnopqrstuvwx", true));
let straddling = format!("{}🦀!", "x".repeat(22)); let (prefix, cut) = truncate_for_display(&straddling);
assert_eq!(prefix, "x".repeat(22));
assert!(cut);
}
}