fix pedantic clippy warnings

This commit is contained in:
Josh Thomas 2025-05-14 14:28:58 -05:00
parent 0cf736ad76
commit c24897add1
11 changed files with 73 additions and 41 deletions

View file

@ -24,7 +24,8 @@ tokio = { version = "1.42", features = ["full"] }
tower-lsp-server = { version = "0.21", features = ["proposed"] }
[workspace.lints.clippy]
pedantic = "warn"
pedantic = { level = "warn", priority = -1 }
missing_errors_doc = "allow"
[profile.dev.package]
insta.opt-level = 3

View file

@ -96,9 +96,8 @@ impl PythonEnvironment {
}
fn from_system_python() -> Option<Self> {
let python_path = match system::find_executable("python") {
Ok(p) => p,
Err(_) => return None,
let Ok(python_path) = system::find_executable("python") else {
return None;
};
let bin_dir = python_path.parent()?;
let prefix = bin_dir.parent()?;

View file

@ -90,7 +90,7 @@ impl TemplateTag {
&self.library
}
pub fn doc(&self) -> &Option<String> {
&self.doc
pub fn doc(&self) -> Option<&String> {
self.doc.as_ref()
}
}

View file

@ -240,9 +240,10 @@ impl TextDocument {
}
pub fn get_template_tag_context(&self, position: Position) -> Option<TemplateTagContext> {
let line = self.get_line(position.line.try_into().ok()?)?;
let prefix = &line[..position.character.try_into().ok()?];
let rest_of_line = &line[position.character.try_into().ok()?..];
let line = self.get_line(position.line)?;
let char_pos: usize = position.character.try_into().ok()?;
let prefix = &line[..char_pos];
let rest_of_line = &line[char_pos..];
let rest_trimmed = rest_of_line.trim_start();
prefix.rfind("{%").map(|tag_start| {

View file

@ -108,12 +108,14 @@ impl Span {
Self { start, length }
}
pub fn start(&self) -> &u32 {
&self.start
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn start(&self) -> u32 {
self.start
}
pub fn length(&self) -> &u32 {
&self.length
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn length(&self) -> u32 {
self.length
}
}
@ -201,14 +203,14 @@ mod tests {
// Variable starts after newline + "{{"
let (line, col) = nodelist
.line_offsets()
.position_to_line_col(*span.start() as usize);
.position_to_line_col(span.start() as usize);
assert_eq!(
(line, col),
(2, 0),
"Variable should start at line 2, col 3"
);
assert_eq!(*span.length(), 9, "Variable span should cover 'user.name'");
assert_eq!(span.length(), 9, "Variable span should cover 'user.name'");
}
}
}

View file

@ -77,7 +77,7 @@ impl TemplateError {
pub fn to_lsp_diagnostic(error: &TemplateError, _source: &str) -> lsp_types::Diagnostic {
let range = error.span().map_or_else(lsp_types::Range::default, |span| {
let start = lsp_types::Position::new(0, *span.start());
let start = lsp_types::Position::new(0, span.start());
let end = lsp_types::Position::new(0, span.start() + span.length());
lsp_types::Range::new(start, end)
});

View file

@ -63,7 +63,7 @@ impl Lexer {
self.consume()?; // >
TokenType::HtmlTagClose(tag)
}
'!' if self.matches("<!--")? => {
'!' if self.matches("<!--") => {
self.consume_n(4)?; // <!--
let content = self.consume_until("-->")?;
self.consume_n(3)?; // -->
@ -169,22 +169,34 @@ impl Lexer {
}
#[allow(dead_code)]
fn peek_until(&self, end: &str) -> Result<bool, LexerError> {
fn peek_until(&self, end: &str) -> bool {
let mut index = self.current;
let end_chars: Vec<char> = end.chars().collect();
while index < self.chars.len() {
if self.chars[index..].starts_with(&end_chars) {
return Ok(true);
return true;
}
index += 1;
}
Ok(false)
false
}
#[allow(clippy::cast_sign_loss)]
fn peek_at(&self, offset: isize) -> Result<char, LexerError> {
let index = self.current as isize + offset;
self.item_at(index as usize)
// Safely handle negative offsets
let index = if offset < 0 {
// Check if we would underflow
if self.current < offset.unsigned_abs() {
return Err(LexerError::AtBeginningOfSource);
}
self.current - offset.unsigned_abs()
} else {
// Safe addition since offset is positive
self.current + (offset as usize)
};
self.item_at(index)
}
fn item_at(&self, index: usize) -> Result<char, LexerError> {
@ -194,19 +206,19 @@ impl Lexer {
// much easier
Ok('\0')
} else {
Ok(self.source.chars().nth(index).unwrap())
self.source.chars().nth(index).ok_or(LexerError::InvalidCharacterAccess)
}
}
fn matches(&mut self, pattern: &str) -> Result<bool, LexerError> {
fn matches(&mut self, pattern: &str) -> bool {
let mut i = self.current;
for c in pattern.chars() {
if i >= self.chars.len() || self.chars[i] != c {
return Ok(false);
return false;
}
i += 1;
}
Ok(true)
true
}
fn is_at_end(&self) -> bool {

View file

@ -146,8 +146,10 @@ impl Parser {
};
let start = token.start().unwrap_or(0);
let offset = text.find(content.as_str()).unwrap_or(0) as u32;
let length = content.len() as u32;
let offset = u32::try_from(text.find(content.as_str()).unwrap_or(0))
.expect("Offset should fit in u32");
let length = u32::try_from(content.len())
.expect("Content length should fit in u32");
let span = Span::new(start + offset, length);
Ok(Node::Text { content, span })
@ -166,9 +168,21 @@ impl Parser {
self.peek_at(-1)
}
#[allow(clippy::cast_sign_loss)]
fn peek_at(&self, offset: isize) -> Result<Token, ParserError> {
let index = self.current as isize + offset;
self.item_at(index as usize)
// Safely handle negative offsets
let index = if offset < 0 {
// Check if we would underflow
if self.current < offset.unsigned_abs() {
return Err(ParserError::stream_error(StreamError::BeforeStart));
}
self.current - offset.unsigned_abs()
} else {
// Safe addition since offset is positive
self.current + (offset as usize)
};
self.item_at(index)
}
fn item_at(&self, index: usize) -> Result<Token, ParserError> {
@ -233,6 +247,7 @@ impl Parser {
#[derive(Debug)]
pub enum StreamError {
AtBeginning,
BeforeStart, // Added to match the usage in peek_at
AtEnd,
Empty,
InvalidAccess,

View file

@ -22,7 +22,7 @@ pub enum TokenType {
}
impl TokenType {
pub fn len(&self) -> Option<usize> {
pub fn len(&self) -> usize {
match self {
TokenType::DjangoBlock(s)
| TokenType::DjangoVariable(s)
@ -33,17 +33,18 @@ impl TokenType {
| TokenType::ScriptTagClose(s)
| TokenType::StyleTagOpen(s)
| TokenType::StyleTagClose(s)
| TokenType::Text(s) => Some(s.len()),
TokenType::Comment(content, _, _) => Some(content.len()),
TokenType::Whitespace(n) => Some(*n),
TokenType::Newline => Some(1),
TokenType::Eof => Some(0),
| TokenType::Text(s) => s.len(),
TokenType::Comment(content, _, _) => content.len(),
TokenType::Whitespace(n) => *n,
TokenType::Newline => 1,
TokenType::Eof => 0,
}
}
}
#[derive(Clone, Debug, Serialize, PartialEq)]
pub struct Token {
#[allow(clippy::struct_field_names)]
token_type: TokenType,
line: usize,
start: Option<usize>,
@ -106,11 +107,11 @@ impl Token {
}
pub fn start(&self) -> Option<u32> {
self.start.map(|s| s as u32)
self.start.map(|s| u32::try_from(s).expect("Start position should fit in u32"))
}
pub fn length(&self) -> Option<u32> {
self.token_type.len().map(|l| l as u32)
pub fn length(&self) -> u32 {
u32::try_from(self.token_type.len()).expect("Token length should fit in u32")
}
pub fn is_token_type(&self, token_type: &TokenType) -> bool {

View file

@ -33,7 +33,8 @@ pub fn run(args: Vec<String>) -> Result<()> {
Err(e) => {
let mut msg = e.to_string();
if let Some(source) = e.source() {
msg += &format!(", caused by {source}");
use std::fmt::Write;
let _ = write!(msg, ", caused by {source}");
}
Exit::error().with_message(msg).process_exit()
}

View file

@ -78,7 +78,7 @@ impl Exit {
pub fn ok(self) -> Result<()> {
match self.status {
ExitStatus::Success => Ok(()),
_ => Err(self.into()),
ExitStatus::Error => Err(self.into()),
}
}