Skip to content

Commit 016c61f

Browse files
authored
Address some clippy lints (#864)
2 parents 479def0 + 92b4b9d commit 016c61f

17 files changed

Lines changed: 232 additions & 205 deletions

File tree

Cargo.toml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,14 @@ strum_macros = "0.28.0"
2020
static_assertions = "1.1.0"
2121
ariadne = "0.6.0"
2222

23+
[workspace.lints.clippy]
24+
unnecessary_semicolon = "deny"
25+
match_wildcard_for_single_variants = "deny"
26+
explicit_iter_loop = "deny"
27+
match_same_arms = "deny"
28+
elidable_lifetime_names = "deny"
29+
trivially_copy_pass_by_ref = "deny"
30+
2331
[profile.dev.package]
2432
insta.opt-level = 3
2533
similar.opt-level = 3

crates/math-core-cli/src/main.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -289,13 +289,11 @@ fn convert_html_recursive(
289289
for entry in dir.filter_map(Result::ok) {
290290
convert_html_recursive(args, entry.path().as_ref(), replacer, converter)
291291
}
292-
} else if path.is_file() {
293-
if let Some(ext) = path.extension() {
294-
if ext == "html" {
292+
} else if path.is_file()
293+
&& let Some(ext) = path.extension()
294+
&& ext == "html" {
295295
convert_html(args, path, replacer, converter);
296296
}
297-
}
298-
}
299297
}
300298

301299
fn convert_html(args: &Args, fp: &Path, replacer: &mut Replacer, converter: &mut LatexToMathML) {

crates/math-core/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,7 @@ minijinja = "2.16.0"
4040
[features]
4141
serde = ["dep:serde", "dep:serde-tuple-vec-map"]
4242
ariadne = ["dep:ariadne"]
43+
44+
[lints]
45+
workspace = true
46+

crates/math-core/src/commands.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -722,14 +722,13 @@ static COMMANDS: phf::Map<&'static str, Token> = phf::phf_map! {
722722
};
723723

724724
pub fn get_command(command: &str) -> Option<Token<'static>> {
725-
match COMMANDS.get(command) {
726-
Some(token) => Some(*token),
727-
None => {
728-
if let Some(function) = FUNCTIONS.get_key(command) {
729-
return Some(PseudoOperator(function));
730-
}
731-
None
725+
if let Some(token) = COMMANDS.get(command) {
726+
Some(*token)
727+
} else {
728+
if let Some(function) = FUNCTIONS.get_key(command) {
729+
return Some(PseudoOperator(function));
732730
}
731+
None
733732
}
734733
}
735734

crates/math-core/src/environments.rs

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,15 @@ impl Env {
5656
ENVIRONMENTS.get(s).copied()
5757
}
5858

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

6666
#[inline]
67-
pub(super) fn allows_columns(&self) -> bool {
67+
pub(super) fn allows_columns(self) -> bool {
6868
!matches!(
6969
self,
7070
Env::Equation
@@ -77,12 +77,12 @@ impl Env {
7777
}
7878

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

8484
#[inline]
85-
pub(super) fn get_numbered_env_state(&self) -> Option<NumberedEnvState> {
85+
pub(super) fn get_numbered_env_state(self) -> Option<NumberedEnvState> {
8686
if matches!(
8787
self,
8888
Env::Align
@@ -112,7 +112,7 @@ impl Env {
112112
}
113113

114114
pub(super) fn construct_node<'arena>(
115-
&self,
115+
self,
116116
content: &'arena [&'arena Node<'arena>],
117117
array_spec: Option<&'arena ArraySpec<'arena>>,
118118
arena: &'arena Arena,
@@ -137,7 +137,7 @@ impl Env {
137137
content,
138138
}
139139
}
140-
Env::Gathered => Node::Table {
140+
Env::Gathered | Env::Matrix => Node::Table {
141141
align: Alignment::Centered,
142142
style: Some(Style::Display),
143143
content,
@@ -166,11 +166,6 @@ impl Env {
166166
style: None,
167167
}
168168
}
169-
Env::Matrix => Node::Table {
170-
align: Alignment::Centered,
171-
style: Some(Style::Display),
172-
content,
173-
},
174169
array_variant @ (Env::Array | Env::Subarray) => {
175170
// SAFETY: `array_spec` is guaranteed to be Some because we checked for
176171
// `Env::Array` and `Env::Subarray` in the caller.

crates/math-core/src/error.rs

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -118,16 +118,16 @@ impl LatexErrKind {
118118
)?;
119119
}
120120
LatexErrKind::DisallowedChar(got) => {
121-
write!(s, "Disallowed character in text group: '{}'.", got)?;
121+
write!(s, "Disallowed character in text group: '{got}'.")?;
122122
}
123123
LatexErrKind::UnknownEnvironment(environment) => {
124-
write!(s, "Unknown environment \"{}\".", environment)?;
124+
write!(s, "Unknown environment \"{environment}\".")?;
125125
}
126126
LatexErrKind::UnknownCommand(cmd) => {
127-
write!(s, "Unknown command \"\\{}\".", cmd)?;
127+
write!(s, "Unknown command \"\\{cmd}\".")?;
128128
}
129129
LatexErrKind::UnknownColor(color) => {
130-
write!(s, "Unknown color \"{}\".", color)?;
130+
write!(s, "Unknown color \"{color}\".")?;
131131
}
132132
LatexErrKind::MismatchedEnvironment { expected, got } => {
133133
write!(
@@ -164,16 +164,16 @@ impl LatexErrKind {
164164
write!(s, "Math variant switch command found outside of sequence.")?;
165165
}
166166
LatexErrKind::ExpectedText(place) => {
167-
write!(s, "Expected text in {}.", place)?;
167+
write!(s, "Expected text in {place}.")?;
168168
}
169169
LatexErrKind::ExpectedLength(got) => {
170-
write!(s, "Expected length with units, got \"{}\".", got)?;
170+
write!(s, "Expected length with units, got \"{got}\".")?;
171171
}
172172
LatexErrKind::ExpectedNumber(got) => {
173-
write!(s, "Expected a number, got \"{}\".", got)?;
173+
write!(s, "Expected a number, got \"{got}\".")?;
174174
}
175175
LatexErrKind::ExpectedColSpec(got) => {
176-
write!(s, "Expected column specification, got \"{}\".", got)?;
176+
write!(s, "Expected column specification, got \"{got}\".")?;
177177
}
178178
LatexErrKind::NotValidInTextMode => {
179179
write!(s, "Not valid in text mode.")?;
@@ -185,7 +185,7 @@ impl LatexErrKind {
185185
write!(s, "Could not extract text from the given macro.")?;
186186
}
187187
LatexErrKind::InvalidMacroName(name) => {
188-
write!(s, "Invalid macro name: \"\\{}\".", name)?;
188+
write!(s, "Invalid macro name: \"\\{name}\".")?;
189189
}
190190
LatexErrKind::InvalidParameterNumber => {
191191
write!(s, "Invalid parameter number. Must be 1-9.")?;
@@ -232,7 +232,7 @@ impl LatexError {
232232
"span"
233233
};
234234
let css_class = css_class.unwrap_or("math-core-error");
235-
let _ = write!(output, r#"<{} class="{}" title=""#, tag, css_class);
235+
let _ = write!(output, r#"<{tag} class="{css_class}" title=""#);
236236
let mut err_msg = String::new();
237237
self.to_message(&mut err_msg, latex);
238238
escape_double_quoted_html_attribute(&mut output, &err_msg);
@@ -253,11 +253,11 @@ impl LatexError {
253253
/// # Arguments
254254
/// - `s`: The string to write the message into.
255255
/// - `input`: The original LaTeX input that caused the error; used to
256-
/// calculate the character offset for the error position.
256+
/// calculate the character offset for the error position.
257257
pub fn to_message(&self, s: &mut String, input: &str) {
258258
let loc = input.floor_char_boundary(self.0.start);
259259
let codepoint_offset = input[..loc].chars().count();
260-
let _ = write!(s, "{}: ", codepoint_offset);
260+
let _ = write!(s, "{codepoint_offset}: ");
261261
let _ = self.1.write_msg(s);
262262
}
263263
}
@@ -281,8 +281,9 @@ impl LatexError {
281281
)
282282
.into(),
283283
LatexErrKind::UnmatchedClose(_) => "no matching opening for this".into(),
284-
LatexErrKind::ExpectedArgumentGotClose => "expected an argument here".into(),
285-
LatexErrKind::ExpectedArgumentGotEOI => "expected an argument here".into(),
284+
LatexErrKind::ExpectedArgumentGotClose | LatexErrKind::ExpectedArgumentGotEOI => {
285+
"expected an argument here".into()
286+
}
286287
LatexErrKind::ExpectedDelimiter(_) => "expected a delimiter here".into(),
287288
LatexErrKind::DisallowedChar(_) => "disallowed character".into(),
288289
LatexErrKind::UnknownEnvironment(_) => "unknown environment".into(),

crates/math-core/src/lexer.rs

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,7 @@ impl<'config, 'source> Lexer<'config, 'source> {
6262
&mut self.peek,
6363
self.input
6464
.next()
65-
.map(|(idx, ch)| (idx, Some(ch)))
66-
.unwrap_or((self.input_length, None)),
65+
.map_or((self.input_length, None), |(idx, ch)| (idx, Some(ch))),
6766
)
6867
}
6968

@@ -120,15 +119,15 @@ impl<'config, 'source> Lexer<'config, 'source> {
120119
/// If the end of the input is reached before finding a `}`, the `Err` contains
121120
/// the span and `None`.
122121
#[inline]
123-
fn read_env_name(&mut self) -> Result<(&'source str, usize), (Range<usize>, Option<char>)> {
122+
fn read_env_name(&mut self) -> Result<(&'source str, usize), CharSpan> {
124123
// If the first character is not `{`, we read a single character.
125124
let (loc, first) = self.read_char();
126125
if first != Some('{') {
127126
return if first.is_some_and(|ch| ch.is_ascii_alphabetic() || matches!(ch, '*')) {
128127
// SAFETY: we got `start` and `end` from `CharIndices`, so they are valid bounds.
129128
Ok((self.input_string.get_unwrap(loc..self.peek.0), self.peek.0))
130129
} else {
131-
Err((loc..(loc + first.map_or(0, |ch| ch.len_utf8())), first))
130+
Err((first, loc..(loc + first.map_or(0, char::len_utf8))))
132131
};
133132
}
134133
let start = self.peek.0;
@@ -146,7 +145,7 @@ impl<'config, 'source> Lexer<'config, 'source> {
146145
// SAFETY: we got `start` and `end` from `CharIndices`, so they are valid bounds.
147146
Ok((self.input_string.get_unwrap(start..end), end + 1))
148147
} else {
149-
Err((loc..(loc + closing.map_or(0, |ch| ch.len_utf8())), closing))
148+
Err((closing, loc..(loc + closing.map_or(0, char::len_utf8))))
150149
}
151150
}
152151

@@ -215,13 +214,16 @@ impl<'config, 'source> Lexer<'config, 'source> {
215214
{
216215
// In pre-defined commands, `#` is used to denote a parameter.
217216
let param_num = (next as u32).wrapping_sub('1' as u32);
218-
if !(0..=8).contains(&param_num) {
217+
let param_num = if let Ok(param_num) = u8::try_from(param_num)
218+
&& (0..=8).contains(&param_num)
219+
{
220+
param_num
221+
} else {
219222
return LexerResult::Err(Box::new(LatexError(
220223
(loc + 1)..(loc + 2),
221224
LatexErrKind::InvalidParameterNumber,
222225
)));
223-
}
224-
let param_num = param_num as u8;
226+
};
225227
if (param_num + 1) > *num {
226228
*num = param_num + 1;
227229
}
@@ -236,12 +238,11 @@ impl<'config, 'source> Lexer<'config, 'source> {
236238
loc..(loc + ch.len_utf8()),
237239
LatexErrKind::InvalidParameterNumber,
238240
)));
239-
} else {
240-
return LexerResult::Err(Box::new(LatexError(
241-
loc..loc,
242-
LatexErrKind::ExpectedParamNumberGotEOI,
243-
)));
244241
}
242+
return LexerResult::Err(Box::new(LatexError(
243+
loc..loc,
244+
LatexErrKind::ExpectedParamNumberGotEOI,
245+
)));
245246
}
246247
} else {
247248
return LexerResult::Err(Box::new(LatexError(
@@ -307,7 +308,7 @@ impl<'config, 'source> Lexer<'config, 'source> {
307308
// Read the environment name.
308309
let (name, end) = match self.read_env_name() {
309310
Ok(lit) => lit,
310-
Err((span, ch)) => match ch {
311+
Err((ch, span)) => match ch {
311312
None => {
312313
break 'env_name Err(LatexError(
313314
span,
@@ -349,6 +350,8 @@ impl<'config, 'source> Lexer<'config, 'source> {
349350
}
350351
}
351352

353+
type CharSpan = (Option<char>, Range<usize>);
354+
352355
fn nonalpha_nonspecial_ascii_to_token(ch: char) -> Option<Token<'static>> {
353356
let tok_ref = match ch {
354357
'!' => &Token::ForceClose(symbol::EXCLAMATION_MARK),
@@ -376,9 +379,8 @@ enum EnvMarker {
376379
pub(crate) fn recover_limited_ascii(tok: Token) -> Option<char> {
377380
match tok {
378381
Token::Letter(ch, _) if ch.is_ascii_alphabetic() || ch == '.' => Some(ch),
379-
Token::MathOrTextMode(_, ch) => Some(ch),
382+
Token::Digit(ch) | Token::MathOrTextMode(_, ch) => Some(ch),
380383
Token::Whitespace => Some(' '),
381-
Token::Digit(ch) => Some(ch),
382384
_ => None,
383385
}
384386
}

crates/math-core/src/lib.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ mod text_parser;
4040
mod token;
4141
mod token_queue;
4242

43-
use rustc_hash::FxHashMap;
43+
use rustc_hash::{FxBuildHasher, FxHashMap};
4444
#[cfg(feature = "serde")]
4545
use serde::{Deserialize, Serialize};
4646

@@ -264,7 +264,7 @@ fn convert(
264264
}
265265
if matches!(display, MathDisplay::Block) {
266266
output.push_str(" display=\"block\"");
267-
};
267+
}
268268
output.push('>');
269269

270270
let pretty_print = matches!(flags.pretty_print, PrettyPrint::Always)
@@ -274,7 +274,7 @@ fn convert(
274274
if flags.annotation {
275275
new_line_and_indent(&mut output, base_indent);
276276
output.push_str("<semantics>");
277-
let node = parser::node_vec_to_node(&arena, ast, false);
277+
let node = parser::node_vec_to_node(&arena, &ast, false);
278278
let _ = node.emit(&mut output, base_indent + 1);
279279
new_line_and_indent(&mut output, base_indent + 1);
280280
output.push_str("<annotation encoding=\"application/x-tex\">");
@@ -318,7 +318,7 @@ fn parse_custom_commands(
318318
macros: Vec<(String, String)>,
319319
ignore_unknown_commands: bool,
320320
) -> Result<CommandConfig, (Box<LatexError>, usize, String)> {
321-
let mut map = FxHashMap::with_capacity_and_hasher(macros.len(), Default::default());
321+
let mut map = FxHashMap::with_capacity_and_hasher(macros.len(), FxBuildHasher);
322322
let mut tokens = Vec::new();
323323
for (idx, (name, definition)) in macros.into_iter().enumerate() {
324324
if !is_valid_macro_name(name.as_str()) {
@@ -360,7 +360,7 @@ fn parse_custom_commands(
360360
Ok(v) => {
361361
map.insert(name, v);
362362
}
363-
};
363+
}
364364
}
365365
Ok(CommandConfig {
366366
custom_cmd_tokens: tokens,

0 commit comments

Comments
 (0)