Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ strum_macros = "0.28.0"
static_assertions = "1.1.0"
ariadne = "0.6.0"

[workspace.lints.clippy]
unnecessary_semicolon = "deny"
match_wildcard_for_single_variants = "deny"
explicit_iter_loop = "deny"
match_same_arms = "deny"
elidable_lifetime_names = "deny"
trivially_copy_pass_by_ref = "deny"

[profile.dev.package]
insta.opt-level = 3
similar.opt-level = 3
Expand Down
8 changes: 3 additions & 5 deletions crates/math-core-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,13 +289,11 @@ fn convert_html_recursive(
for entry in dir.filter_map(Result::ok) {
convert_html_recursive(args, entry.path().as_ref(), replacer, converter)
}
} else if path.is_file() {
if let Some(ext) = path.extension() {
if ext == "html" {
} else if path.is_file()
&& let Some(ext) = path.extension()
&& ext == "html" {
convert_html(args, path, replacer, converter);
}
}
}
}

fn convert_html(args: &Args, fp: &Path, replacer: &mut Replacer, converter: &mut LatexToMathML) {
Expand Down
4 changes: 4 additions & 0 deletions crates/math-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,7 @@ minijinja = "2.16.0"
[features]
serde = ["dep:serde", "dep:serde-tuple-vec-map"]
ariadne = ["dep:ariadne"]

[lints]
workspace = true

13 changes: 6 additions & 7 deletions crates/math-core/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -722,14 +722,13 @@ static COMMANDS: phf::Map<&'static str, Token> = phf::phf_map! {
};

pub fn get_command(command: &str) -> Option<Token<'static>> {
match COMMANDS.get(command) {
Some(token) => Some(*token),
None => {
if let Some(function) = FUNCTIONS.get_key(command) {
return Some(PseudoOperator(function));
}
None
if let Some(token) = COMMANDS.get(command) {
Some(*token)
} else {
if let Some(function) = FUNCTIONS.get_key(command) {
return Some(PseudoOperator(function));
}
None
}
}

Expand Down
19 changes: 7 additions & 12 deletions crates/math-core/src/environments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,15 @@ impl Env {
ENVIRONMENTS.get(s).copied()
}

pub(super) fn as_str(&self) -> &'static str {
pub(super) fn as_str(self) -> &'static str {
ENVIRONMENTS
.entries()
.find_map(|(k, v)| if v == self { Some(*k) } else { None })
.find_map(|(k, v)| if v == &self { Some(*k) } else { None })
.unwrap_or("unknown")
}

#[inline]
pub(super) fn allows_columns(&self) -> bool {
pub(super) fn allows_columns(self) -> bool {
!matches!(
self,
Env::Equation
Expand All @@ -77,12 +77,12 @@ impl Env {
}

#[inline]
pub(super) fn meaningful_newlines(&self) -> bool {
pub(super) fn meaningful_newlines(self) -> bool {
!matches!(self, Env::Equation | Env::EquationStar)
}

#[inline]
pub(super) fn get_numbered_env_state(&self) -> Option<NumberedEnvState> {
pub(super) fn get_numbered_env_state(self) -> Option<NumberedEnvState> {
if matches!(
self,
Env::Align
Expand Down Expand Up @@ -112,7 +112,7 @@ impl Env {
}

pub(super) fn construct_node<'arena>(
&self,
self,
content: &'arena [&'arena Node<'arena>],
array_spec: Option<&'arena ArraySpec<'arena>>,
arena: &'arena Arena,
Expand All @@ -137,7 +137,7 @@ impl Env {
content,
}
}
Env::Gathered => Node::Table {
Env::Gathered | Env::Matrix => Node::Table {
align: Alignment::Centered,
style: Some(Style::Display),
content,
Expand Down Expand Up @@ -166,11 +166,6 @@ impl Env {
style: None,
}
}
Env::Matrix => Node::Table {
align: Alignment::Centered,
style: Some(Style::Display),
content,
},
array_variant @ (Env::Array | Env::Subarray) => {
// SAFETY: `array_spec` is guaranteed to be Some because we checked for
// `Env::Array` and `Env::Subarray` in the caller.
Expand Down
29 changes: 15 additions & 14 deletions crates/math-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,16 +118,16 @@ impl LatexErrKind {
)?;
}
LatexErrKind::DisallowedChar(got) => {
write!(s, "Disallowed character in text group: '{}'.", got)?;
write!(s, "Disallowed character in text group: '{got}'.")?;
}
LatexErrKind::UnknownEnvironment(environment) => {
write!(s, "Unknown environment \"{}\".", environment)?;
write!(s, "Unknown environment \"{environment}\".")?;
}
LatexErrKind::UnknownCommand(cmd) => {
write!(s, "Unknown command \"\\{}\".", cmd)?;
write!(s, "Unknown command \"\\{cmd}\".")?;
}
LatexErrKind::UnknownColor(color) => {
write!(s, "Unknown color \"{}\".", color)?;
write!(s, "Unknown color \"{color}\".")?;
}
LatexErrKind::MismatchedEnvironment { expected, got } => {
write!(
Expand Down Expand Up @@ -164,16 +164,16 @@ impl LatexErrKind {
write!(s, "Math variant switch command found outside of sequence.")?;
}
LatexErrKind::ExpectedText(place) => {
write!(s, "Expected text in {}.", place)?;
write!(s, "Expected text in {place}.")?;
}
LatexErrKind::ExpectedLength(got) => {
write!(s, "Expected length with units, got \"{}\".", got)?;
write!(s, "Expected length with units, got \"{got}\".")?;
}
LatexErrKind::ExpectedNumber(got) => {
write!(s, "Expected a number, got \"{}\".", got)?;
write!(s, "Expected a number, got \"{got}\".")?;
}
LatexErrKind::ExpectedColSpec(got) => {
write!(s, "Expected column specification, got \"{}\".", got)?;
write!(s, "Expected column specification, got \"{got}\".")?;
}
LatexErrKind::NotValidInTextMode => {
write!(s, "Not valid in text mode.")?;
Expand All @@ -185,7 +185,7 @@ impl LatexErrKind {
write!(s, "Could not extract text from the given macro.")?;
}
LatexErrKind::InvalidMacroName(name) => {
write!(s, "Invalid macro name: \"\\{}\".", name)?;
write!(s, "Invalid macro name: \"\\{name}\".")?;
}
LatexErrKind::InvalidParameterNumber => {
write!(s, "Invalid parameter number. Must be 1-9.")?;
Expand Down Expand Up @@ -232,7 +232,7 @@ impl LatexError {
"span"
};
let css_class = css_class.unwrap_or("math-core-error");
let _ = write!(output, r#"<{} class="{}" title=""#, tag, css_class);
let _ = write!(output, r#"<{tag} class="{css_class}" title=""#);
let mut err_msg = String::new();
self.to_message(&mut err_msg, latex);
escape_double_quoted_html_attribute(&mut output, &err_msg);
Expand All @@ -253,11 +253,11 @@ impl LatexError {
/// # Arguments
/// - `s`: The string to write the message into.
/// - `input`: The original LaTeX input that caused the error; used to
/// calculate the character offset for the error position.
/// calculate the character offset for the error position.
pub fn to_message(&self, s: &mut String, input: &str) {
let loc = input.floor_char_boundary(self.0.start);
let codepoint_offset = input[..loc].chars().count();
let _ = write!(s, "{}: ", codepoint_offset);
let _ = write!(s, "{codepoint_offset}: ");
let _ = self.1.write_msg(s);
}
}
Expand All @@ -281,8 +281,9 @@ impl LatexError {
)
.into(),
LatexErrKind::UnmatchedClose(_) => "no matching opening for this".into(),
LatexErrKind::ExpectedArgumentGotClose => "expected an argument here".into(),
LatexErrKind::ExpectedArgumentGotEOI => "expected an argument here".into(),
LatexErrKind::ExpectedArgumentGotClose | LatexErrKind::ExpectedArgumentGotEOI => {
"expected an argument here".into()
}
LatexErrKind::ExpectedDelimiter(_) => "expected a delimiter here".into(),
LatexErrKind::DisallowedChar(_) => "disallowed character".into(),
LatexErrKind::UnknownEnvironment(_) => "unknown environment".into(),
Expand Down
34 changes: 18 additions & 16 deletions crates/math-core/src/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ impl<'config, 'source> Lexer<'config, 'source> {
&mut self.peek,
self.input
.next()
.map(|(idx, ch)| (idx, Some(ch)))
.unwrap_or((self.input_length, None)),
.map_or((self.input_length, None), |(idx, ch)| (idx, Some(ch))),
)
}

Expand Down Expand Up @@ -120,15 +119,15 @@ impl<'config, 'source> Lexer<'config, 'source> {
/// If the end of the input is reached before finding a `}`, the `Err` contains
/// the span and `None`.
#[inline]
fn read_env_name(&mut self) -> Result<(&'source str, usize), (Range<usize>, Option<char>)> {
fn read_env_name(&mut self) -> Result<(&'source str, usize), CharSpan> {
// If the first character is not `{`, we read a single character.
let (loc, first) = self.read_char();
if first != Some('{') {
return if first.is_some_and(|ch| ch.is_ascii_alphabetic() || matches!(ch, '*')) {
// SAFETY: we got `start` and `end` from `CharIndices`, so they are valid bounds.
Ok((self.input_string.get_unwrap(loc..self.peek.0), self.peek.0))
} else {
Err((loc..(loc + first.map_or(0, |ch| ch.len_utf8())), first))
Err((first, loc..(loc + first.map_or(0, char::len_utf8))))
};
}
let start = self.peek.0;
Expand All @@ -146,7 +145,7 @@ impl<'config, 'source> Lexer<'config, 'source> {
// SAFETY: we got `start` and `end` from `CharIndices`, so they are valid bounds.
Ok((self.input_string.get_unwrap(start..end), end + 1))
} else {
Err((loc..(loc + closing.map_or(0, |ch| ch.len_utf8())), closing))
Err((closing, loc..(loc + closing.map_or(0, char::len_utf8))))
}
}

Expand Down Expand Up @@ -215,13 +214,16 @@ impl<'config, 'source> Lexer<'config, 'source> {
{
// In pre-defined commands, `#` is used to denote a parameter.
let param_num = (next as u32).wrapping_sub('1' as u32);
if !(0..=8).contains(&param_num) {
let param_num = if let Ok(param_num) = u8::try_from(param_num)
&& (0..=8).contains(&param_num)
{
param_num
} else {
return LexerResult::Err(Box::new(LatexError(
(loc + 1)..(loc + 2),
LatexErrKind::InvalidParameterNumber,
)));
}
let param_num = param_num as u8;
};
if (param_num + 1) > *num {
*num = param_num + 1;
}
Expand All @@ -236,12 +238,11 @@ impl<'config, 'source> Lexer<'config, 'source> {
loc..(loc + ch.len_utf8()),
LatexErrKind::InvalidParameterNumber,
)));
} else {
return LexerResult::Err(Box::new(LatexError(
loc..loc,
LatexErrKind::ExpectedParamNumberGotEOI,
)));
}
return LexerResult::Err(Box::new(LatexError(
loc..loc,
LatexErrKind::ExpectedParamNumberGotEOI,
)));
}
} else {
return LexerResult::Err(Box::new(LatexError(
Expand Down Expand Up @@ -307,7 +308,7 @@ impl<'config, 'source> Lexer<'config, 'source> {
// Read the environment name.
let (name, end) = match self.read_env_name() {
Ok(lit) => lit,
Err((span, ch)) => match ch {
Err((ch, span)) => match ch {
None => {
break 'env_name Err(LatexError(
span,
Expand Down Expand Up @@ -349,6 +350,8 @@ impl<'config, 'source> Lexer<'config, 'source> {
}
}

type CharSpan = (Option<char>, Range<usize>);

fn nonalpha_nonspecial_ascii_to_token(ch: char) -> Option<Token<'static>> {
let tok_ref = match ch {
'!' => &Token::ForceClose(symbol::EXCLAMATION_MARK),
Expand Down Expand Up @@ -376,9 +379,8 @@ enum EnvMarker {
pub(crate) fn recover_limited_ascii(tok: Token) -> Option<char> {
match tok {
Token::Letter(ch, _) if ch.is_ascii_alphabetic() || ch == '.' => Some(ch),
Token::MathOrTextMode(_, ch) => Some(ch),
Token::Digit(ch) | Token::MathOrTextMode(_, ch) => Some(ch),
Token::Whitespace => Some(' '),
Token::Digit(ch) => Some(ch),
_ => None,
}
}
Expand Down
10 changes: 5 additions & 5 deletions crates/math-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ mod text_parser;
mod token;
mod token_queue;

use rustc_hash::FxHashMap;
use rustc_hash::{FxBuildHasher, FxHashMap};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -264,7 +264,7 @@ fn convert(
}
if matches!(display, MathDisplay::Block) {
output.push_str(" display=\"block\"");
};
}
output.push('>');

let pretty_print = matches!(flags.pretty_print, PrettyPrint::Always)
Expand All @@ -274,7 +274,7 @@ fn convert(
if flags.annotation {
new_line_and_indent(&mut output, base_indent);
output.push_str("<semantics>");
let node = parser::node_vec_to_node(&arena, ast, false);
let node = parser::node_vec_to_node(&arena, &ast, false);
let _ = node.emit(&mut output, base_indent + 1);
new_line_and_indent(&mut output, base_indent + 1);
output.push_str("<annotation encoding=\"application/x-tex\">");
Expand Down Expand Up @@ -318,7 +318,7 @@ fn parse_custom_commands(
macros: Vec<(String, String)>,
ignore_unknown_commands: bool,
) -> Result<CommandConfig, (Box<LatexError>, usize, String)> {
let mut map = FxHashMap::with_capacity_and_hasher(macros.len(), Default::default());
let mut map = FxHashMap::with_capacity_and_hasher(macros.len(), FxBuildHasher);
let mut tokens = Vec::new();
for (idx, (name, definition)) in macros.into_iter().enumerate() {
if !is_valid_macro_name(name.as_str()) {
Expand Down Expand Up @@ -360,7 +360,7 @@ fn parse_custom_commands(
Ok(v) => {
map.insert(name, v);
}
};
}
}
Ok(CommandConfig {
custom_cmd_tokens: tokens,
Expand Down
Loading