From ba34fe732d88cd9053776027f8e08142e00f783c Mon Sep 17 00:00:00 2001 From: Kisaragi Marine Date: Thu, 19 Oct 2023 23:22:14 +0900 Subject: [PATCH 1/2] refactor: cargo clippy --fix --- package/origlang-ast/src/lib.rs | 10 +++--- package/origlang-cli/src/task/repl.rs | 4 +-- .../origlang-compiler-entrypoint/src/lib.rs | 12 +++---- .../origlang-compiler/src/chars/boundary.rs | 2 +- package/origlang-compiler/src/lexer.rs | 32 ++++++++--------- package/origlang-compiler/src/lexer/tests.rs | 34 +++++++++---------- package/origlang-compiler/src/lexer/token.rs | 7 ++-- package/origlang-compiler/src/parser.rs | 4 +-- package/origlang-compiler/src/type_check.rs | 14 ++++---- package/origlang-ir/src/lib.rs | 16 ++++----- package/origlang-runtime/src/invoke_once.rs | 4 +-- package/origlang-runtime/src/lib.rs | 6 ++-- 12 files changed, 74 insertions(+), 71 deletions(-) diff --git a/package/origlang-ast/src/lib.rs b/package/origlang-ast/src/lib.rs index 46c8859f..97801da9 100644 --- a/package/origlang-ast/src/lib.rs +++ b/package/origlang-ast/src/lib.rs @@ -23,9 +23,9 @@ pub enum AtomicPattern { impl Display for AtomicPattern { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - AtomicPattern::Discard => f.write_str("_"), - AtomicPattern::Bind(i) => f.write_str(i.as_name()), - AtomicPattern::Tuple(v) => { + Self::Discard => f.write_str("_"), + Self::Bind(i) => f.write_str(i.as_name()), + Self::Tuple(v) => { f.write_str("(")?; for i in v { Display::fmt(i, f)?; @@ -112,8 +112,8 @@ impl From for TypeSignature { impl Display for TypeSignature { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - TypeSignature::Simple(x) => ::fmt(x, f), - TypeSignature::Tuple(v) => { + Self::Simple(x) => ::fmt(x, f), + Self::Tuple(v) => { for x in v { ::fmt(x, f)?; } diff --git a/package/origlang-cli/src/task/repl.rs b/package/origlang-cli/src/task/repl.rs index 8f6afbad..11810096 100644 --- a/package/origlang-cli/src/task/repl.rs +++ b/package/origlang-cli/src/task/repl.rs @@ -54,9 +54,9 @@ impl Repl { let ir = tra.into_ir(); let trans = TheTranspiler::new(&NoOptimization); let ir = trans.lower(ir); - let ir = trans.lower(ir); + - ir + trans.lower(ir) } } diff --git a/package/origlang-compiler-entrypoint/src/lib.rs b/package/origlang-compiler-entrypoint/src/lib.rs index 06ea60f1..53377252 100644 --- a/package/origlang-compiler-entrypoint/src/lib.rs +++ b/package/origlang-compiler-entrypoint/src/lib.rs @@ -2,7 +2,7 @@ #![warn(clippy::pedantic, clippy::nursery)] use std::any::type_name; -use std::ops::Deref; + use log::debug; use thiserror::Error; use origlang_ast::Statement; @@ -24,7 +24,7 @@ pub struct TheCompiler { impl TheCompiler { /// Creates new instance without any optimization, scanner, nor diagnostic receiver. - pub fn new() -> Self { + #[must_use] pub fn new() -> Self { Self { scanner: ScannerRegistry::default(), optimization_preset: OptimizationPresetCollection::none(), @@ -38,7 +38,7 @@ impl TheCompiler { self } - pub fn register_diagnostic_receiver(mut self, receiver: Box) -> Self { + #[must_use] pub fn register_diagnostic_receiver(mut self, receiver: Box) -> Self { debug!("registered {ds}", ds = type_name::()); self.diagnostic_receivers.push(receiver as _); @@ -71,7 +71,7 @@ impl TheCompiler { let diagnostics = diags.iter(); for diag in diagnostics { for receiver in &self.diagnostic_receivers { - receiver.handle_diagnostic(diag.deref()) + receiver.handle_diagnostic(&**diag); } } } @@ -83,7 +83,7 @@ impl TheCompiler { let diagnostics = diags.iter(); for diag in diagnostics { for receiver in &self.diagnostic_receivers { - receiver.handle_diagnostic(diag.deref()) + receiver.handle_diagnostic(&**diag); } } } @@ -145,7 +145,7 @@ pub struct OptimizationPresetCollection { impl OptimizationPresetCollection { fn none() -> Self { - OptimizationPresetCollection { + Self { ir0: Box::new(NoOptimization) as Box<_>, ir1: Box::new(NoOptimization) as Box<_>, ir2: Box::new(NoOptimization) as Box<_>, diff --git a/package/origlang-compiler/src/chars/boundary.rs b/package/origlang-compiler/src/chars/boundary.rs index 2c0adb38..a559c0d9 100644 --- a/package/origlang-compiler/src/chars/boundary.rs +++ b/package/origlang-compiler/src/chars/boundary.rs @@ -14,7 +14,7 @@ impl Utf8CharBoundaryStartByte { self.0 } - pub const fn stride(self, stride: Utf8CharStride) -> Utf8CharBoundaryStartByte { + pub const fn stride(self, stride: Utf8CharStride) -> Self { Self::new(self.as_usize() + stride.as_usize()) } } diff --git a/package/origlang-compiler/src/lexer.rs b/package/origlang-compiler/src/lexer.rs index e8108995..5f16d1df 100644 --- a/package/origlang-compiler/src/lexer.rs +++ b/package/origlang-compiler/src/lexer.rs @@ -3,7 +3,7 @@ pub(crate) mod error; mod tests; pub mod token; -use std::borrow::Cow; + use std::cell::Cell; use std::convert::Infallible; @@ -73,7 +73,7 @@ impl Lexer<'_> { if let Some(b) = self.source.get((start.as_usize())..end_exclusive) { if s == b { match self.set_current_index(Utf8CharBoundaryStartByte::new(end_exclusive)) { - Ok(_) => Ok(Some(s)), + Ok(()) => Ok(Some(s)), Err(OutOfRangeError { .. }) => Ok(None), } } else { @@ -134,14 +134,14 @@ impl Lexer<'_> { .or_else(|| self.try_and_eat_str(r#"("#).expect("huh?").map(|_| Token::SymLeftPar)) .or_else(|| self.try_and_eat_str(r#")"#).expect("huh?").map(|_| Token::SymRightPar)) .or_else(|| { - if let Some(_) = self.try_and_eat_str(r#"<"#).expect("huh?") { - if let Some(_) = self.try_and_eat_str(r#"="#).expect("huh?") { - if let Some(_) = self.try_and_eat_str(r#">"#).expect("huh?") { + if self.try_and_eat_str(r#"<"#).expect("huh?").is_some() { + if self.try_and_eat_str(r#"="#).expect("huh?").is_some() { + if self.try_and_eat_str(r#">"#).expect("huh?").is_some() { Some(Token::PartLessEqMore) } else { Some(Token::PartLessEq) } - } else if let Some(_) = self.try_and_eat_str(r#"<"#).expect("huh?") { + } else if self.try_and_eat_str(r#"<"#).expect("huh?").is_some() { Some(Token::PartLessLess) } else { Some(Token::SymLess) @@ -151,10 +151,10 @@ impl Lexer<'_> { } }) .or_else(|| { - if let Some(_) = self.try_and_eat_str(r#">"#).expect("huh?") { - if let Some(_) = self.try_and_eat_str(r#"="#).expect("huh?") { + if self.try_and_eat_str(r#">"#).expect("huh?").is_some() { + if self.try_and_eat_str(r#"="#).expect("huh?").is_some() { Some(Token::PartMoreEq) - } else if let Some(_) = self.try_and_eat_str(r#">"#).expect("huh?") { + } else if self.try_and_eat_str(r#">"#).expect("huh?").is_some() { Some(Token::PartMoreMore) } else { Some(Token::SymMore) @@ -300,7 +300,7 @@ impl Lexer<'_> { let r = self.byte_skip_n(plus); if let Ok(b) = r { - if (b'0'..=b'9').contains(&b) { + if b.is_ascii_digit() { plus += 1; } else { break @@ -366,13 +366,13 @@ impl Lexer<'_> { new - (old + old_relative) } else { let mut c = self.column.get().get(); - c += (new - old); + c += new - old; c }; self.line.set(NonZeroUsize::new(new_line).expect("overflow")); - self.column.set(NonZeroUsize::new(new_col).expect("overflow")) + self.column.set(NonZeroUsize::new(new_col).expect("overflow")); } else { // back let new_line = current_line - src[new..old].bytes().filter(|x| *x == b'\n').count(); @@ -400,7 +400,7 @@ impl Lexer<'_> { }; self.line.set(NonZeroUsize::new(new_line).expect("overflow")); - self.column.set(NonZeroUsize::new(new_col).expect("overflow")) + self.column.set(NonZeroUsize::new(new_col).expect("overflow")); } debug!("index: requested = {future_index:?}"); @@ -411,7 +411,7 @@ impl Lexer<'_> { fn scan_line_comment(&self) -> Result { let start = self.source_bytes_nth.get().as_usize(); - let rel_pos = self.source[start..].find("\n").unwrap_or(self.source.len()); + let rel_pos = self.source[start..].find('\n').unwrap_or(self.source.len()); self.advance_bytes(rel_pos)?; let content = self.source[start..(start + rel_pos)].to_string(); @@ -536,11 +536,11 @@ impl Lexer<'_> { } fn current_byte(&self) -> Result { - self.source.bytes().nth(self.source_bytes_nth.get().as_usize()).ok_or_else(|| self.report_out_of_range_error()) + self.source.as_bytes().get(self.source_bytes_nth.get().as_usize()).copied().ok_or_else(|| self.report_out_of_range_error()) } fn byte_skip_n(&self, skip: usize) -> Result { - self.source.bytes().nth(self.source_bytes_nth.get().as_usize() + skip).ok_or_else(|| self.report_out_of_range_error()) + self.source.as_bytes().get(self.source_bytes_nth.get().as_usize() + skip).copied().ok_or_else(|| self.report_out_of_range_error()) } fn report_out_of_range_error(&self) -> LexerError { diff --git a/package/origlang-compiler/src/lexer/tests.rs b/package/origlang-compiler/src/lexer/tests.rs index d5ffc82a..375f7da8 100644 --- a/package/origlang-compiler/src/lexer/tests.rs +++ b/package/origlang-compiler/src/lexer/tests.rs @@ -15,82 +15,82 @@ fn test(str_lit: &str) { #[test] fn parse_string_literal_ascii() { - test("123456") + test("123456"); } #[test] fn parse_string_literal_empty() { - test("") + test(""); } #[test] fn parse_string_literal_two_bytes() { - test("\u{80}") + test("\u{80}"); } #[test] fn parse_string_literal_three_bytes() { - test("\u{800}") + test("\u{800}"); } #[test] fn parse_string_literal_mixed_1_2() { - test("1\u{80}") + test("1\u{80}"); } #[test] fn parse_string_literal_mixed_1_3() { - test("1あ") + test("1あ"); } #[test] fn parse_string_literal_mixed_1_4() { - test("1\u{10000}") + test("1\u{10000}"); } #[test] fn parse_string_literal_mixed_2_1() { - test("\u{80}1") + test("\u{80}1"); } #[test] fn parse_string_literal_mixed_2_3() { - test("\u{80}あ") + test("\u{80}あ"); } #[test] fn parse_string_literal_mixed_2_4() { - test("\u{80}\u{10000}") + test("\u{80}\u{10000}"); } #[test] fn parse_string_literal_mixed_3_1() { - test("あ1") + test("あ1"); } #[test] fn parse_string_literal_mixed_3_2() { - test("あ\u{80}") + test("あ\u{80}"); } #[test] fn parse_string_literal_mixed_3_4() { - test("あ\u{10000}") + test("あ\u{10000}"); } #[test] fn parse_string_literal_mixed_4_1() { - test("\u{10000}1") + test("\u{10000}1"); } #[test] fn parse_string_literal_mixed_4_2() { - test("\u{10000}\u{80}") + test("\u{10000}\u{80}"); } #[test] fn parse_string_literal_mixed_4_3() { - test("\u{10000}あ") + test("\u{10000}あ"); } use std::num::NonZeroUsize; @@ -231,5 +231,5 @@ fn off_by_one_range_regression() { line: NonZeroUsize::new(1).unwrap(), column: NonZeroUsize::new(1).unwrap(), } - }) + }); } \ No newline at end of file diff --git a/package/origlang-compiler/src/lexer/token.rs b/package/origlang-compiler/src/lexer/token.rs index 564a4436..e0ac0a5b 100644 --- a/package/origlang-compiler/src/lexer/token.rs +++ b/package/origlang-compiler/src/lexer/token.rs @@ -8,6 +8,7 @@ pub struct TemporalLexerUnwindToken { } impl TemporalLexerUnwindToken { + #[must_use] pub fn new(reset_to: Utf8CharBoundaryStartByte) -> Self { Self { unwind_index: reset_to @@ -159,12 +160,14 @@ impl Token { } } + #[must_use] pub const fn is_error(&self) -> bool { - matches!(self, Token::UnexpectedChar { .. }) + matches!(self, Self::UnexpectedChar { .. }) } + #[must_use] pub const fn is_end(&self) -> bool { - matches!(self, Token::EndOfFile) + matches!(self, Self::EndOfFile) } } diff --git a/package/origlang-compiler/src/parser.rs b/package/origlang-compiler/src/parser.rs index a3240f5a..c8d2ea66 100644 --- a/package/origlang-compiler/src/parser.rs +++ b/package/origlang-compiler/src/parser.rs @@ -206,7 +206,7 @@ impl Parser<'_> { if let Token::Identifier { inner: aliased } = aliased.data { let except_eq = self.lexer.next(); - if let Token::SymEq = except_eq.data { + if except_eq.data == Token::SymEq { let Ok(replace_with) = self.lexer.parse_fallible(|| self.parse_type()) else { return Err(SimpleErrorWithPos { @@ -729,7 +729,7 @@ impl Parser<'_> { } }) } - other_token => return Err(SimpleErrorWithPos { + other_token => Err(SimpleErrorWithPos { kind: ParserError::UnexpectedToken { pat: TokenKind::StartOfTypeSignature, unmatch: other_token, diff --git a/package/origlang-compiler/src/type_check.rs b/package/origlang-compiler/src/type_check.rs index e08646f9..b38783d0 100644 --- a/package/origlang-compiler/src/type_check.rs +++ b/package/origlang-compiler/src/type_check.rs @@ -164,7 +164,7 @@ impl TryIntoTypeCheckedForm for Expression { lhs: Box::new(lhs_expr), rhs: Box::new(rhs_expr), operator, - return_type: lhs_type.clone() + return_type: lhs_type }) } else { Err(TypeCheckError::UnableToUnifyEqualityQuery { @@ -282,7 +282,7 @@ fn desugar( Err(TypeCheckError::UnsatisfiablePattern { pattern: AtomicPattern::Tuple(outer_destruction.to_vec()), expression: TypedExpression::Variable { ident, tp: Type::tuple(tuple_element_types.clone()) }, - expr_type: Type::tuple(tuple_element_types.clone()), + expr_type: Type::tuple(tuple_element_types), }) } } @@ -296,12 +296,12 @@ fn desugar( } } } - TypedExpression::Block { inner, final_expression, return_type } => { + TypedExpression::Block { inner: _, final_expression, return_type: _ } => { // TODO: how can we handle inner statement? desugar(outer_destruction, *final_expression, checker) } TypedExpression::Tuple { expressions } => { - let m = outer_destruction.iter().zip(expressions).enumerate().map(|(i, (element_binding, expression))| { + let m = outer_destruction.iter().zip(expressions).enumerate().map(|(_i, (element_binding, expression))| { handle_atomic_pattern(expression, element_binding, checker) }).collect::>(); @@ -353,12 +353,12 @@ fn desugar( ident: new_ident.clone(), tp: tp.clone() }; - checker.ctx.borrow_mut().add_known_variable(new_ident.clone(), tp.clone()); + checker.ctx.borrow_mut().add_known_variable(new_ident.clone(), tp); let v = desugar(outer_destruction, v, checker)?; let mut r = VecDeque::from(v); r.push_front(TypedStatement::VariableDeclaration { - identifier: new_ident.clone(), + identifier: new_ident, expression: TypedExpression::ExtractTuple { expr: Box::new(expr), index @@ -454,7 +454,7 @@ impl TryIntoTypeCheckedForm for Statement { }]), Self::Exit => Ok(vec![TypedStatement::Exit]), Self::TypeAliasDeclaration { new_name, replace_with } => { - checker.ctx.borrow_mut().known_aliases.insert(new_name, checker.lower_type_signature_into_type(&replace_with).map_err(|_| TypeCheckError::UnknownType { + checker.ctx.borrow_mut().known_aliases.insert(new_name, checker.lower_type_signature_into_type(&replace_with).map_err(|()| TypeCheckError::UnknownType { name: replace_with, })?); diff --git a/package/origlang-ir/src/lib.rs b/package/origlang-ir/src/lib.rs index 623b6b33..b55515c1 100644 --- a/package/origlang-ir/src/lib.rs +++ b/package/origlang-ir/src/lib.rs @@ -29,12 +29,12 @@ impl IntoVerbatimSequencedIR for TypedStatement { let statement = self; match statement { - TypedStatement::Print { expression } => { + Self::Print { expression } => { vec![ IR0::Normal(IR1::Output(expression)) ] } - TypedStatement::VariableDeclaration { identifier, expression } => { + Self::VariableDeclaration { identifier, expression } => { vec![ IR0::Normal(IR1::UpdateVariable { ident: identifier, @@ -42,7 +42,7 @@ impl IntoVerbatimSequencedIR for TypedStatement { }) ] } - TypedStatement::VariableAssignment { identifier, expression } => { + Self::VariableAssignment { identifier, expression } => { vec![ IR0::Normal(IR1::UpdateVariable { ident: identifier, @@ -50,16 +50,16 @@ impl IntoVerbatimSequencedIR for TypedStatement { }) ] } - TypedStatement::Block { inner_statements } => { + Self::Block { inner_statements } => { let mut vec = inner_statements.into_iter() - .flat_map(::into_ir) + .flat_map(::into_ir) .collect::>(); vec.push_front(IR0::Normal(IR1::PushScope)); vec.push_back(IR0::Normal(IR1::PopScope)); vec.into() } - TypedStatement::Exit => vec![IR0::Exit], - TypedStatement::EvalAndForget { expression } => { + Self::Exit => vec![IR0::Exit], + Self::EvalAndForget { expression } => { vec![IR0::Normal(IR1::EvalAndForget { expression })] }, } @@ -76,7 +76,7 @@ impl IntoVerbatimSequencedIR for TypedRootAst { impl IntoVerbatimSequencedIR for Vec { fn into_ir(self) -> Vec { - self.into_iter().flat_map(|x| x.into_ir()).collect() + self.into_iter().flat_map(IntoVerbatimSequencedIR::into_ir).collect() } } diff --git a/package/origlang-runtime/src/invoke_once.rs b/package/origlang-runtime/src/invoke_once.rs index 01da57ae..7369f500 100644 --- a/package/origlang-runtime/src/invoke_once.rs +++ b/package/origlang-runtime/src/invoke_once.rs @@ -1,6 +1,6 @@ use std::cell::{Cell, RefCell}; use std::mem::{MaybeUninit}; -use std::ops::DerefMut; + #[derive(Debug)] pub struct InvokeOnce { @@ -22,7 +22,7 @@ impl InvokeOnce { if self.owned.get() { self.owned.set(false); let mut ret: MaybeUninit = MaybeUninit::uninit(); - std::mem::swap(self.inner.borrow_mut().deref_mut(), &mut ret); + std::mem::swap(&mut *self.inner.borrow_mut(), &mut ret); // SAFETY: The only way to initialize Self type is calling `new` constructor. // It moves into already-initialized value to us. diff --git a/package/origlang-runtime/src/lib.rs b/package/origlang-runtime/src/lib.rs index 6c2095f9..d601c71f 100644 --- a/package/origlang-runtime/src/lib.rs +++ b/package/origlang-runtime/src/lib.rs @@ -225,7 +225,7 @@ impl Runtime { } IR2::Exit => { if let Some(x) = self.on_exit.as_ref() { - x.try_get().expect("exit receiver is already called!").on_exit() + x.try_get().expect("exit receiver is already called!").on_exit(); } } IR2::EvalAndForget { expression } => { @@ -436,7 +436,7 @@ impl CanBeEvaluated for CompiledTypedExpression { boxes: res })) } - CompiledTypedExpression::ExtractTuple { expr, index } => { + Self::ExtractTuple { expr, index } => { let x = expr.evaluate(runtime)?; match x { TypeBox::Tuple(x) => { @@ -446,7 +446,7 @@ impl CanBeEvaluated for CompiledTypedExpression { indicate_type_checker_bug!(context = "tuple_destruction: out of bounds") } } - other => indicate_type_checker_bug!(context = "must be tuple") + _other => indicate_type_checker_bug!(context = "must be tuple") } } } From afdf5d17f80f9a5f6cf00b4be2854bf21e0465e9 Mon Sep 17 00:00:00 2001 From: Kisaragi Marine Date: Thu, 19 Oct 2023 23:25:39 +0900 Subject: [PATCH 2/2] refactor: fix clippy::new_without_default --- package/origlang-compiler-entrypoint/src/lib.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/package/origlang-compiler-entrypoint/src/lib.rs b/package/origlang-compiler-entrypoint/src/lib.rs index 53377252..0dcf535c 100644 --- a/package/origlang-compiler-entrypoint/src/lib.rs +++ b/package/origlang-compiler-entrypoint/src/lib.rs @@ -93,6 +93,12 @@ impl TheCompiler { } } +impl Default for TheCompiler { + fn default() -> Self { + Self::new() + } +} + #[derive(Debug, Eq, PartialEq, Error)] pub enum PartialCompilation { #[error("syntax error: {0}")]