use alloc::boxed::Box;
use alloc::format;
use alloc::sync::Arc;
use core::fmt;
use crate::constructs::ImplementationError;
use crate::source::Span;
use crate::state::{FeaturePresence, Lang, LangFeatures, ParsingState};
use super::error::{EndOfStreamAfterEscape, TokenErrorKind};
use super::rules::{CommandRule, GroupRule, TokenRules};
use super::specials::{SpecialsMatch, SpecialsScanError};
pub fn skip_whitespace<L: Lang>(content: &str, pos: usize, rules: &TokenRules<L>) -> usize {
check_pos(content, pos);
if !<L::Features as LangFeatures>::Whitespace::PRESENT || !rules.whitespace_enabled() {
return pos;
}
let rest = &content[pos..];
let ws_chars = rules.whitespace_chars();
let mut end = pos;
for c in rest.chars() {
if !ws_chars.contains(c) {
break;
}
if c == '\n'
&& <L::Features as LangFeatures>::Paragraphs::PRESENT
&& rules.paragraphs_enabled()
&& paragraph_continues(content, end + 1, ws_chars)
{
break;
}
end += c.len_utf8();
}
end
}
fn paragraph_continues(content: &str, after_nl: usize, ws_chars: &str) -> bool {
for c in content[after_nl..].chars() {
if c == '\n' {
return true;
}
if !ws_chars.contains(c) {
return false;
}
}
false
}
#[track_caller]
fn check_pos(content: &str, pos: usize) {
assert!(
content.is_char_boundary(pos),
"pos {} is out of bounds or not a char boundary (content len {})",
pos,
content.len()
);
}
pub fn scan_paragraph_break<L: Lang>(
content: &str,
pos: usize,
rules: &TokenRules<L>,
) -> Option<Span> {
check_pos(content, pos);
if !(<L::Features as LangFeatures>::Paragraphs::PRESENT
&& <L::Features as LangFeatures>::Whitespace::PRESENT
&& rules.paragraphs_enabled()
&& rules.whitespace_enabled())
{
return None;
}
let ws_chars = rules.whitespace_chars();
if !content[pos..].starts_with('\n') || !ws_chars.contains('\n') {
return None;
}
let mut newlines = 0usize;
let mut end = pos;
let mut last_nl_end = pos;
for c in content[pos..].chars() {
if !ws_chars.contains(c) {
break;
}
end += c.len_utf8();
if c == '\n' {
newlines += 1;
last_nl_end = end;
}
}
if newlines < 2 {
return None; }
Some(Span::new(pos, last_nl_end))
}
pub enum GroupDelimiterMatch<'r, L: Lang> {
Open {
span: Span,
rule: &'r Arc<GroupRule<L>>,
},
Close {
span: Span,
rule: &'r Arc<GroupRule<L>>,
},
}
impl<'r, L: Lang> GroupDelimiterMatch<'r, L> {
pub fn span(&self) -> Span {
match self {
GroupDelimiterMatch::Open { span, .. }
| GroupDelimiterMatch::Close { span, .. } => *span,
}
}
pub fn rule(&self) -> &'r Arc<GroupRule<L>> {
match self {
GroupDelimiterMatch::Open { rule, .. }
| GroupDelimiterMatch::Close { rule, .. } => rule,
}
}
}
impl<L: Lang> Clone for GroupDelimiterMatch<'_, L> {
fn clone(&self) -> Self {
*self
}
}
impl<L: Lang> Copy for GroupDelimiterMatch<'_, L> {}
impl<L: Lang> PartialEq for GroupDelimiterMatch<'_, L> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(
GroupDelimiterMatch::Open { span: s1, rule: r1 },
GroupDelimiterMatch::Open { span: s2, rule: r2 },
) => s1 == s2 && r1 == r2,
(
GroupDelimiterMatch::Close { span: s1, rule: r1 },
GroupDelimiterMatch::Close { span: s2, rule: r2 },
) => s1 == s2 && r1 == r2,
_ => false,
}
}
}
impl<L: Lang> Eq for GroupDelimiterMatch<'_, L> {}
impl<L: Lang> fmt::Debug for GroupDelimiterMatch<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GroupDelimiterMatch::Open { span, rule } => {
f.debug_struct("Open").field("span", span).field("rule", rule).finish()
}
GroupDelimiterMatch::Close { span, rule } => {
f.debug_struct("Close").field("span", span).field("rule", rule).finish()
}
}
}
}
pub fn scan_group_delimiter<'r, L: Lang>(
content: &str,
pos: usize,
state: &'r ParsingState<L>,
) -> Option<GroupDelimiterMatch<'r, L>> {
check_pos(content, pos);
let rules = state.rules();
let rest = &content[pos..];
if let Some(expected) = rules.expecting_group_close() {
if !expected.close.is_empty() && rest.starts_with(expected.close.as_str()) {
let span = Span::new(pos, pos + expected.close.len());
return Some(GroupDelimiterMatch::Close { span, rule: expected });
}
}
let entry = state.prefix_table()?.match_at(rest)?;
let span = Span::new(pos, pos + entry.delim().len());
Some(match (entry.open(), entry.close()) {
(Some(rule), _) => GroupDelimiterMatch::Open { span, rule },
(None, Some(rule)) => GroupDelimiterMatch::Close { span, rule },
(None, None) => unreachable!("prefix table entries always carry a direction"),
})
}
pub fn command_rule_at<'r, L: Lang>(
content: &str,
pos: usize,
rules: &'r TokenRules<L>,
) -> Option<&'r Arc<CommandRule>> {
check_pos(content, pos);
if !<L::Features as LangFeatures>::Commands::PRESENT || !rules.commands_enabled() {
return None;
}
let c = content[pos..].chars().next()?;
rules.command_rules().iter().find(|r| c == r.escape_char)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommandMatch {
pub escape_char: char,
pub span: Span,
pub name: Span,
pub post_space: Span,
}
pub fn scan_command<L: Lang>(
content: &str,
pos: usize,
rules: &TokenRules<L>,
rule: &CommandRule,
) -> Result<CommandMatch, EndOfStreamAfterEscape> {
check_pos(content, pos);
assert!(
content[pos..].starts_with(rule.escape_char),
"the rule's escape character {:?} does not stand at pos {}",
rule.escape_char,
pos
);
let s = content;
let name_start = pos + rule.escape_char.len_utf8();
if name_start >= s.len() {
return Err(EndOfStreamAfterEscape::new(rule.escape_char));
}
let first = s[name_start..].chars().next().expect("name_start < len checked above");
let mut name_end = name_start + first.len_utf8();
let is_named = rule.name_chars.contains(first);
if is_named {
for c in s[name_end..].chars() {
if !rule.name_chars.contains(c) {
break;
}
name_end += c.len_utf8();
}
}
let post_space = if is_named {
Span::new(name_end, skip_whitespace(s, name_end, rules))
} else {
Span::empty(name_end)
};
Ok(CommandMatch {
escape_char: rule.escape_char,
span: Span::new(pos, post_space.end()),
name: Span::new(name_start, name_end),
post_space,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommentMatch {
pub span: Span,
pub start: Span,
pub content: Span,
pub post_space: Span,
}
pub fn scan_comment<L: Lang>(
content: &str,
pos: usize,
rules: &TokenRules<L>,
) -> Option<CommentMatch> {
check_pos(content, pos);
if !<L::Features as LangFeatures>::Comments::PRESENT || !rules.comments_enabled() {
return None;
}
let s = content;
let rest = &s[pos..];
let start = rules
.comment_rules()
.iter()
.map(|r| r.start.as_str())
.filter(|d| !d.is_empty() && rest.starts_with(d))
.max_by_key(|d| d.len())?;
let content_start = pos + start.len();
let content_end = match s[content_start..].find('\n') {
Some(i) => content_start + i,
None => s.len(),
};
let post_space = Span::new(content_end, skip_whitespace(s, content_end, rules));
Some(CommentMatch {
span: Span::new(pos, post_space.end()),
start: Span::new(pos, content_start),
content: Span::new(content_start, content_end),
post_space,
})
}
pub fn scan_specials_trigger<L: Lang>(
content: &str,
pos: usize,
state: &ParsingState<L>,
) -> Result<Option<SpecialsMatch<L>>, SpecialsScanError> {
check_pos(content, pos);
if !<L::Features as LangFeatures>::Specials::PRESENT {
return Ok(None);
}
let Some(c) = content[pos..].chars().next() else {
return Ok(None);
};
if !state.trigger_chars().is_some_and(|trigger_chars| trigger_chars.may_start(c)) {
return Ok(None);
}
let scanned = L::scan_specials(state, content, pos)
.map_err(|error| checked_scan_error(error, content, pos))?;
let Some(m) = scanned else {
return Ok(None);
};
if !(m.end > pos && m.end <= content.len() && content.is_char_boundary(m.end)) {
return Err(SpecialsScanError {
kind: TokenErrorKind::Custom(Box::new(ImplementationError::new(format!(
"Lang::scan_specials returned an invalid match end \
{} for a match at {} (content length {})",
m.end,
pos,
content.len()
)))),
span: Span::empty(pos),
});
}
Ok(Some(m))
}
fn checked_scan_error(
error: SpecialsScanError,
content: &str,
pos: usize,
) -> SpecialsScanError {
let span = error.span;
let valid = span.end() <= content.len()
&& content.is_char_boundary(span.start())
&& content.is_char_boundary(span.end());
if !valid {
return SpecialsScanError {
kind: TokenErrorKind::Custom(Box::new(ImplementationError::new(format!(
"Lang::scan_specials reported an error at an invalid span {}..{} \
for a scan at {} (content length {})",
span.start(),
span.end(),
pos,
content.len()
)))),
span: Span::empty(pos),
};
}
error
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::DiagnosticInfo;
use crate::scopes::ScopeStack;
use crate::spec::CallableSpec;
use crate::state::{StateData, TrivialLang};
use crate::token::{
CommandRules, CommentRule, CommentRules, ForbiddenCharsRules, GroupRules,
ParagraphRules, SpecialsRules, TriggerChars, WhitespaceRules,
};
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;
const BRACES: u32 = 0;
const BRACKETS: u32 = 1;
const MATH_INLINE: u32 = 2;
const MATH_DISPLAY: u32 = 3;
const MATH_INLINE_PAREN: u32 = 4;
const MATH_DISPLAY_BRACKET: u32 = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct TestLang;
impl TrivialLang for TestLang {}
fn latex_rules<L: Lang<GroupTypeId = u32, Features = crate::state::AllLangFeatures>>(
) -> TokenRules<L> {
TokenRules {
whitespace: WhitespaceRules { enabled: true, chars: " \t\n\r\u{000B}\u{000C}".into() },
paragraphs: ParagraphRules { enabled: true },
groups: GroupRules {
enabled: true,
rules: vec![
group(BRACES, "{", "}"),
group(BRACKETS, "[", "]"),
group(MATH_INLINE, "$", "$"),
group(MATH_DISPLAY, "$$", "$$"),
group(MATH_INLINE_PAREN, r"\(", r"\)"),
group(MATH_DISPLAY_BRACKET, r"\[", r"\]"),
],
temporary: Vec::new(),
expecting_close: None,
},
commands: CommandRules {
enabled: true,
rules: vec![Arc::new(CommandRule {
escape_char: '\\',
name_chars: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".into(),
})],
},
comments: CommentRules {
enabled: true,
rules: vec![Arc::new(CommentRule { start: "%".into() })],
},
specials: SpecialsRules { enabled: true },
forbidden_chars: ForbiddenCharsRules { chars: "".into() },
}
}
fn group<L: Lang<GroupTypeId = u32>>(
group_type: u32,
open: &str,
close: &str,
) -> Arc<GroupRule<L>> {
Arc::new(GroupRule { group_type, open: open.into(), close: close.into() })
}
#[test]
fn skip_whitespace_never_consumes_paragraph_newlines() {
let rules: TokenRules<TestLang> = latex_rules();
assert_eq!(skip_whitespace(" \n x", 0, &rules), 4);
assert_eq!(skip_whitespace(" \n \n x", 0, &rules), 3);
assert_eq!(skip_whitespace("\n\nx", 0, &rules), 0);
let mut no_par: TokenRules<TestLang> = latex_rules();
no_par.paragraphs.enabled = false;
assert_eq!(skip_whitespace(" \n \n x", 0, &no_par), 8);
let mut no_ws: TokenRules<TestLang> = latex_rules();
no_ws.whitespace.enabled = false;
assert_eq!(skip_whitespace(" x", 0, &no_ws), 0);
}
#[test]
#[should_panic(expected = "char boundary")]
fn skip_whitespace_panics_on_an_out_of_bounds_pos() {
let rules: TokenRules<TestLang> = latex_rules();
let _ = skip_whitespace("ab", 5, &rules);
}
#[test]
#[should_panic(expected = "char boundary")]
fn skip_whitespace_panics_on_a_mid_char_pos() {
let rules: TokenRules<TestLang> = latex_rules();
let _ = skip_whitespace("é!", 1, &rules);
}
#[test]
#[should_panic(expected = "char boundary")]
fn skip_whitespace_panics_on_an_invalid_pos_with_whitespace_disabled() {
let mut rules: TokenRules<TestLang> = latex_rules();
rules.whitespace.enabled = false;
let _ = skip_whitespace("ab", 5, &rules);
}
fn sp(start: usize, end: usize) -> Span {
Span::new(start, end)
}
fn state(rules: TokenRules<TestLang>) -> Arc<ParsingState<TestLang>> {
Arc::new(ParsingState::new(StateData {
rules,
scopes: ScopeStack::new(),
mode: (),
ext: (),
}))
}
fn rule_of(group_type: u32) -> Arc<GroupRule<TestLang>> {
latex_rules::<TestLang>()
.groups
.rules
.into_iter()
.find(|g| g.group_type == group_type)
.expect("class present in latex_rules")
}
fn expecting_close(group_type: u32) -> Arc<ParsingState<TestLang>> {
let mut rules: TokenRules<TestLang> = latex_rules();
rules.groups.expecting_close = Some(rule_of(group_type));
state(rules)
}
fn backslash() -> Arc<CommandRule> {
latex_rules::<TestLang>().commands.rules[0].clone()
}
#[test]
fn paragraph_break_runs_through_the_last_newline() {
let rules: TokenRules<TestLang> = latex_rules();
assert_eq!(scan_paragraph_break("a\n \n b", 1, &rules), Some(sp(1, 4)));
assert_eq!(scan_paragraph_break("\n\n\n x", 0, &rules), Some(sp(0, 3)));
}
#[test]
fn paragraph_break_needs_a_run_of_two_newlines_at_pos() {
let rules: TokenRules<TestLang> = latex_rules();
assert_eq!(scan_paragraph_break("a\n b", 1, &rules), None);
assert_eq!(scan_paragraph_break(" \n\n", 0, &rules), None);
assert_eq!(scan_paragraph_break("ab", 1, &rules), None);
assert_eq!(scan_paragraph_break("ab", 2, &rules), None);
}
#[test]
fn paragraph_break_off_when_the_rules_say_so() {
let mut no_par: TokenRules<TestLang> = latex_rules();
no_par.paragraphs.enabled = false;
assert_eq!(scan_paragraph_break("\n\nx", 0, &no_par), None);
let mut no_ws: TokenRules<TestLang> = latex_rules();
no_ws.whitespace.enabled = false;
assert_eq!(scan_paragraph_break("\n\nx", 0, &no_ws), None);
let mut no_nl: TokenRules<TestLang> = latex_rules();
no_nl.whitespace.chars = " \t".into();
assert_eq!(scan_paragraph_break("\n\nx", 0, &no_nl), None);
}
#[test]
#[should_panic(expected = "char boundary")]
fn scan_paragraph_break_panics_on_an_out_of_bounds_pos() {
let rules: TokenRules<TestLang> = latex_rules();
let _ = scan_paragraph_break("ab", 5, &rules);
}
#[test]
#[should_panic(expected = "char boundary")]
fn scan_paragraph_break_panics_on_a_mid_char_pos() {
let rules: TokenRules<TestLang> = latex_rules();
let _ = scan_paragraph_break("é!", 1, &rules);
}
#[test]
fn group_delimiter_reads_both_directions_and_the_longest_match() {
let st = state(latex_rules());
let braces = rule_of(BRACES);
assert_eq!(
scan_group_delimiter("{a}", 0, &st),
Some(GroupDelimiterMatch::Open { span: sp(0, 1), rule: &braces }),
);
assert_eq!(
scan_group_delimiter("{a}", 2, &st),
Some(GroupDelimiterMatch::Close { span: sp(2, 3), rule: &braces }),
);
let display = rule_of(MATH_DISPLAY);
assert_eq!(
scan_group_delimiter("$$x", 0, &st),
Some(GroupDelimiterMatch::Open { span: sp(0, 2), rule: &display }),
);
assert_eq!(scan_group_delimiter("ax", 0, &st), None);
assert_eq!(scan_group_delimiter("ax", 2, &st), None);
}
#[test]
fn group_delimiter_reads_an_ambiguous_string_as_an_opener() {
let st = state(latex_rules());
let inline = rule_of(MATH_INLINE);
assert_eq!(
scan_group_delimiter("$x$", 0, &st),
Some(GroupDelimiterMatch::Open { span: sp(0, 1), rule: &inline }),
);
}
#[test]
fn group_delimiter_gives_the_expected_close_precedence() {
let st = expecting_close(MATH_INLINE);
let inline = rule_of(MATH_INLINE);
assert_eq!(
scan_group_delimiter("$x", 0, &st),
Some(GroupDelimiterMatch::Close { span: sp(0, 1), rule: &inline }),
);
assert_eq!(
scan_group_delimiter("$$x", 0, &st),
Some(GroupDelimiterMatch::Close { span: sp(0, 1), rule: &inline }),
);
}
#[test]
fn group_delimiter_with_groups_disabled_still_answers_the_expected_close() {
let mut rules: TokenRules<TestLang> = latex_rules();
rules.groups.enabled = false;
rules.groups.expecting_close = Some(rule_of(BRACES));
let st = state(rules);
assert_eq!(scan_group_delimiter("{a}", 0, &st), None);
let braces = rule_of(BRACES);
assert_eq!(
scan_group_delimiter("}a", 0, &st),
Some(GroupDelimiterMatch::Close { span: sp(0, 1), rule: &braces }),
);
}
#[test]
#[should_panic(expected = "char boundary")]
fn scan_group_delimiter_panics_on_an_out_of_bounds_pos() {
let st = state(latex_rules());
let _ = scan_group_delimiter("ab", 5, &st);
}
#[test]
#[should_panic(expected = "char boundary")]
fn scan_group_delimiter_panics_on_a_mid_char_pos() {
let st = state(latex_rules());
let _ = scan_group_delimiter("é!", 1, &st);
}
#[test]
fn command_rule_at_answers_the_rule_whose_escape_char_stands_there() {
let rules: TokenRules<TestLang> = latex_rules();
assert_eq!(command_rule_at(r"a\foo", 1, &rules), Some(&backslash()));
assert_eq!(command_rule_at(r"a\foo", 0, &rules), None);
assert_eq!(command_rule_at("a", 1, &rules), None);
}
#[test]
fn command_rule_at_answers_the_first_rule_in_list_order() {
let mut rules: TokenRules<TestLang> = latex_rules();
rules.commands.rules = vec![
Arc::new(CommandRule { escape_char: '@', name_chars: "a".into() }),
Arc::new(CommandRule { escape_char: '@', name_chars: "b".into() }),
];
let found = command_rule_at("@a", 0, &rules).expect("the escape char stands there");
assert_eq!(&*found.name_chars, "a");
}
#[test]
fn command_rule_at_off_when_the_rules_say_so() {
let mut off: TokenRules<TestLang> = latex_rules();
off.commands.enabled = false;
assert_eq!(command_rule_at(r"\foo", 0, &off), None);
let mut empty: TokenRules<TestLang> = latex_rules();
empty.commands.rules = Vec::new();
assert_eq!(command_rule_at(r"\foo", 0, &empty), None);
}
#[test]
#[should_panic(expected = "char boundary")]
fn command_rule_at_panics_on_an_out_of_bounds_pos() {
let rules: TokenRules<TestLang> = latex_rules();
let _ = command_rule_at("ab", 5, &rules);
}
#[test]
#[should_panic(expected = "char boundary")]
fn command_rule_at_panics_on_a_mid_char_pos() {
let rules: TokenRules<TestLang> = latex_rules();
let _ = command_rule_at("é!", 1, &rules);
}
#[test]
fn command_with_a_name_takes_its_post_space() {
let rules: TokenRules<TestLang> = latex_rules();
assert_eq!(
scan_command(r"\foo bar", 0, &rules, &backslash()),
Ok(CommandMatch {
escape_char: '\\',
span: sp(0, 6),
name: sp(1, 4),
post_space: sp(4, 6),
}),
);
}
#[test]
fn command_of_a_single_character_takes_no_post_space() {
let rules: TokenRules<TestLang> = latex_rules();
assert_eq!(
scan_command(r"\& x", 0, &rules, &backslash()),
Ok(CommandMatch {
escape_char: '\\',
span: sp(0, 2),
name: sp(1, 2),
post_space: Span::empty(2),
}),
);
}
#[test]
fn command_of_a_single_name_character_takes_its_post_space() {
let rules: TokenRules<TestLang> = latex_rules();
assert_eq!(
scan_command(r"\t x", 0, &rules, &backslash()),
Ok(CommandMatch {
escape_char: '\\',
span: sp(0, 4),
name: sp(1, 2),
post_space: sp(2, 4),
}),
);
}
#[test]
fn command_post_space_stops_before_a_paragraph_break() {
let rules: TokenRules<TestLang> = latex_rules();
let m = scan_command("\\foo \n\nbar", 0, &rules, &backslash()).expect("a command");
assert_eq!(m.post_space, sp(4, 5));
assert_eq!(m.span, sp(0, 5));
assert_eq!(scan_paragraph_break("\\foo \n\nbar", 5, &rules), Some(sp(5, 7)));
}
#[test]
fn command_at_a_dangling_escape_character_is_an_end_of_stream_condition() {
let rules: TokenRules<TestLang> = latex_rules();
assert_eq!(
scan_command(r"a\", 1, &rules, &backslash()),
Err(EndOfStreamAfterEscape::new('\\')),
);
}
#[test]
fn command_with_a_multi_byte_escape_character() {
let mut rules: TokenRules<TestLang> = latex_rules();
let rule = Arc::new(CommandRule { escape_char: '§', name_chars: "abc".into() });
rules.commands.rules = vec![rule.clone()];
assert_eq!(
scan_command("§ab d", 0, &rules, &rule),
Ok(CommandMatch {
escape_char: '§',
span: sp(0, 5),
name: sp(2, 4),
post_space: sp(4, 5),
}),
);
assert_eq!(scan_command("§", 0, &rules, &rule), Err(EndOfStreamAfterEscape::new('§')));
}
#[test]
#[should_panic(expected = "char boundary")]
fn scan_command_panics_on_an_out_of_bounds_pos() {
let rules: TokenRules<TestLang> = latex_rules();
let _ = scan_command(r"\a", 5, &rules, &backslash());
}
#[test]
#[should_panic(expected = "char boundary")]
fn scan_command_panics_on_a_mid_char_pos() {
let rules: TokenRules<TestLang> = latex_rules();
let _ = scan_command("é!", 1, &rules, &backslash());
}
#[test]
#[should_panic(expected = "does not stand at pos")]
fn scan_command_panics_when_the_rules_escape_char_is_not_at_pos() {
let rules: TokenRules<TestLang> = latex_rules();
let _ = scan_command("abc", 0, &rules, &backslash());
}
#[test]
fn comment_takes_the_longest_start_delimiter() {
let mut rules: TokenRules<TestLang> = latex_rules();
rules.comments.rules = vec![
Arc::new(CommentRule { start: "%".into() }),
Arc::new(CommentRule { start: "%%".into() }),
Arc::new(CommentRule { start: "".into() }),
];
assert_eq!(
scan_comment("%%x\ny", 0, &rules),
Some(CommentMatch {
span: sp(0, 4),
start: sp(0, 2),
content: sp(2, 3),
post_space: sp(3, 4),
}),
);
}
#[test]
fn comment_post_space_is_the_newline_and_the_next_lines_indentation() {
let rules: TokenRules<TestLang> = latex_rules();
assert_eq!(
scan_comment("a% note\n b", 1, &rules),
Some(CommentMatch {
span: sp(1, 11),
start: sp(1, 2),
content: sp(2, 7),
post_space: sp(7, 11),
}),
);
}
#[test]
fn comment_without_a_terminating_newline_runs_to_the_end() {
let rules: TokenRules<TestLang> = latex_rules();
assert_eq!(
scan_comment("%tail", 0, &rules),
Some(CommentMatch {
span: sp(0, 5),
start: sp(0, 1),
content: sp(1, 5),
post_space: Span::empty(5),
}),
);
}
#[test]
fn comment_keeps_a_carriage_return_in_its_content() {
let rules: TokenRules<TestLang> = latex_rules();
let m = scan_comment("%a\r\nb", 0, &rules).expect("a comment");
assert_eq!(m.content, sp(1, 3));
assert_eq!(m.post_space, sp(3, 4));
}
#[test]
fn comment_takes_no_post_space_before_a_paragraph_break() {
let rules: TokenRules<TestLang> = latex_rules();
let m = scan_comment("%a\n\nb", 0, &rules).expect("a comment");
assert_eq!(m.content, sp(1, 2));
assert_eq!(m.post_space, Span::empty(2));
assert_eq!(m.span, sp(0, 2));
assert_eq!(scan_paragraph_break("%a\n\nb", 2, &rules), Some(sp(2, 4)));
}
#[test]
fn comment_none_without_a_delimiter_and_when_the_rules_say_so() {
let rules: TokenRules<TestLang> = latex_rules();
assert_eq!(scan_comment("a%x", 0, &rules), None);
assert_eq!(scan_comment("a%x", 3, &rules), None);
let mut off: TokenRules<TestLang> = latex_rules();
off.comments.enabled = false;
assert_eq!(scan_comment("%x", 0, &off), None);
let mut empty: TokenRules<TestLang> = latex_rules();
empty.comments.rules = Vec::new();
assert_eq!(scan_comment("%x", 0, &empty), None);
}
#[test]
#[should_panic(expected = "char boundary")]
fn scan_comment_panics_on_an_out_of_bounds_pos() {
let rules: TokenRules<TestLang> = latex_rules();
let _ = scan_comment("ab", 5, &rules);
}
#[test]
#[should_panic(expected = "char boundary")]
fn scan_comment_panics_on_a_mid_char_pos() {
let rules: TokenRules<TestLang> = latex_rules();
let _ = scan_comment("é!", 1, &rules);
}
#[derive(Debug)]
struct StubSpec;
impl crate::serialize::SerializableObject<HookLang> for StubSpec {}
impl CallableSpec<HookLang> for StubSpec {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct HookLang;
impl Lang for HookLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = crate::engine::StdParseDriver;
fn specials_trigger_chars(_data: &StateData<Self>) -> TriggerChars {
TriggerChars::Only("~&-!?;:".into())
}
fn scan_specials(
_state: &ParsingState<Self>,
content: &str,
pos: usize,
) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
let rest = &content[pos..];
for trigger in ["---", "~~", "~", "&"] {
if rest.starts_with(trigger) {
return Ok(Some(SpecialsMatch {
end: pos + trigger.len(),
callable_type: 7,
spec: Arc::new(StubSpec),
}));
}
}
if rest.starts_with('!') {
return Ok(Some(SpecialsMatch {
end: pos,
callable_type: 7,
spec: Arc::new(StubSpec),
}));
}
let bad_span = match rest.chars().next() {
Some('?') => Some(Span::new(pos, pos + 1)), Some(';') => Some(Span::new(content.len() + 1, content.len() + 2)),
Some(':') => Some(Span::new(1, 2)), _ => None,
};
match bad_span {
Some(span) => Err(SpecialsScanError {
kind: TokenErrorKind::Custom(Box::new(ImplementationError::new(
String::from("the scan declined loudly"),
))),
span,
}),
None => Ok(None),
}
}
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &Arc<ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
fn hook_state(rules: TokenRules<HookLang>) -> Arc<ParsingState<HookLang>> {
Arc::new(ParsingState::new(StateData {
rules,
scopes: ScopeStack::new(),
mode: (),
ext: (),
}))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct UnconsultedHookLang;
impl Lang for UnconsultedHookLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = crate::engine::StdParseDriver;
fn specials_trigger_chars(_data: &StateData<Self>) -> TriggerChars {
TriggerChars::Only("~".into())
}
fn scan_specials(
_state: &ParsingState<Self>,
_content: &str,
_pos: usize,
) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
panic!("scan_specials consulted where the filter admits no trigger")
}
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &Arc<ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
fn unconsulted_state(
rules: TokenRules<UnconsultedHookLang>,
) -> Arc<ParsingState<UnconsultedHookLang>> {
Arc::new(ParsingState::new(StateData {
rules,
scopes: ScopeStack::new(),
mode: (),
ext: (),
}))
}
#[test]
fn specials_trigger_answers_the_hooks_match() {
let st = hook_state(latex_rules());
let m = scan_specials_trigger("a---b", 1, &st).expect("no failure").expect("a match");
assert_eq!(m.end, 4);
assert_eq!(m.callable_type, 7);
}
#[test]
fn specials_trigger_answers_none_when_no_trigger_is_there() {
let st = hook_state(latex_rules());
assert!(scan_specials_trigger("-x", 0, &st).expect("no failure").is_none());
assert!(scan_specials_trigger("x~", 0, &st).expect("no failure").is_none());
assert!(scan_specials_trigger("x", 1, &st).expect("no failure").is_none());
}
#[test]
fn specials_trigger_does_not_consult_the_hook_off_the_filter() {
let st = unconsulted_state(latex_rules());
assert!(scan_specials_trigger("x~", 0, &st).expect("no failure").is_none());
assert!(scan_specials_trigger("x~", 2, &st).expect("no failure").is_none());
}
#[test]
fn specials_trigger_is_off_when_the_specials_gate_is_off() {
let mut rules: TokenRules<UnconsultedHookLang> = latex_rules();
rules.specials.enabled = false;
let st = unconsulted_state(rules);
assert!(scan_specials_trigger("~x", 0, &st).expect("no failure").is_none());
}
#[test]
fn specials_trigger_rejects_a_match_end_the_documentation_rules_out() {
let st = hook_state(latex_rules());
let err = scan_specials_trigger("a!b", 1, &st).expect_err("a rejected match");
assert_eq!(err.span, Span::empty(1));
match &err.kind {
TokenErrorKind::Custom(data) => {
assert_eq!(data.identifier(), ImplementationError::IDENTIFIER);
assert!(data.to_string().contains("invalid match end"), "{}", data);
}
other => panic!("expected a Custom implementation error, got {:?}", other),
}
}
#[test]
fn specials_trigger_passes_a_hook_error_with_a_valid_span_through() {
let st = hook_state(latex_rules());
let err = scan_specials_trigger("a?b", 1, &st).expect_err("the hook's failure");
assert_eq!(err.span, sp(1, 2));
assert!(err.to_string().contains("declined loudly"), "{err}");
}
#[test]
fn specials_trigger_anchors_a_hook_error_reported_at_an_invalid_span() {
let st = hook_state(latex_rules());
for (content, pos, half) in [(";x", 0, "out of bounds"), ("é:", 2, "mid-character")] {
let err = scan_specials_trigger(content, pos, &st).expect_err("a rejected span");
assert_eq!(err.span, Span::empty(pos), "{half}");
match &err.kind {
TokenErrorKind::Custom(data) => {
assert_eq!(data.identifier(), ImplementationError::IDENTIFIER, "{half}");
assert!(data.to_string().contains("invalid span"), "{half}: {}", data);
}
other => panic!("{half}: expected a Custom error, got {:?}", other),
}
}
}
#[test]
#[should_panic(expected = "char boundary")]
fn scan_specials_trigger_panics_on_an_out_of_bounds_pos() {
let st = hook_state(latex_rules());
let _ = scan_specials_trigger("ab", 5, &st);
}
#[test]
#[should_panic(expected = "char boundary")]
fn scan_specials_trigger_panics_on_a_mid_char_pos() {
let st = hook_state(latex_rules());
let _ = scan_specials_trigger("é!", 1, &st);
}
}