From b3ad7c21b3c9685b23c8d3150c2cb529bdfc9396 Mon Sep 17 00:00:00 2001 From: Rik Huijzer Date: Sat, 21 Dec 2024 21:15:29 +0100 Subject: [PATCH] Setup `cargo clippy` (#40) --- .github/workflows/check.yml | 3 ++ arnoldc/src/arnold.rs | 8 ++-- arnoldc/src/arnold_to_mlir.rs | 3 +- arnoldc/src/main.rs | 7 ++-- arnoldc/src/transform.rs | 26 +++++-------- xrcf-bin/src/main.rs | 7 ++-- xrcf/src/convert/experimental_to_mlir.rs | 9 +++-- xrcf/src/convert/mlir_to_llvmir.rs | 15 ++++---- xrcf/src/convert/mod.rs | 6 +-- xrcf/src/convert/scf_to_cf.rs | 7 ++-- xrcf/src/dialect/arith/op.rs | 8 ++-- xrcf/src/dialect/cf/op.rs | 8 ++-- xrcf/src/dialect/experimental/op.rs | 8 ++-- xrcf/src/dialect/func/op.rs | 27 ++++++-------- xrcf/src/dialect/llvm/attribute.rs | 4 +- xrcf/src/dialect/llvm/op.rs | 8 ++-- xrcf/src/dialect/llvm/typ.rs | 47 +++++++++++++++--------- xrcf/src/dialect/scf/op.rs | 8 ++-- xrcf/src/{parser => frontend}/mod.rs | 0 xrcf/src/{parser => frontend}/parser.rs | 18 +++++---- xrcf/src/{parser => frontend}/scanner.rs | 23 ++++++------ xrcf/src/{parser => frontend}/token.rs | 0 xrcf/src/ir/attribute.rs | 11 +++--- xrcf/src/ir/block.rs | 13 ++++--- xrcf/src/ir/mod.rs | 17 ++++----- xrcf/src/ir/module.rs | 10 +++-- xrcf/src/ir/op.rs | 6 +-- xrcf/src/ir/op_operand.rs | 8 ++-- xrcf/src/ir/operation.rs | 20 +++++----- xrcf/src/ir/region.rs | 4 +- xrcf/src/ir/typ.rs | 26 ++++++------- xrcf/src/ir/value.rs | 15 +++++--- xrcf/src/lib.rs | 4 +- xrcf/src/targ3t/llvmir/op.rs | 11 ++++-- xrcf/src/targ3t/llvmir/typ.rs | 13 +++++-- xrcf/src/tester.rs | 4 +- xrcf/src/transform.rs | 6 +-- xrcf/tests/arith.rs | 2 +- xrcf/tests/canonicalize.rs | 4 +- xrcf/tests/convert/cf_to_llvm.rs | 2 +- xrcf/tests/convert/func_to_llvm.rs | 4 +- xrcf/tests/convert/mlir_to_llvmir.rs | 6 +-- xrcf/tests/convert/scf_to_cf.rs | 4 +- 43 files changed, 228 insertions(+), 212 deletions(-) rename xrcf/src/{parser => frontend}/mod.rs (100%) rename xrcf/src/{parser => frontend}/parser.rs (97%) rename xrcf/src/{parser => frontend}/scanner.rs (95%) rename xrcf/src/{parser => frontend}/token.rs (100%) diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 32715549..6bbe1917 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -23,6 +23,7 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: toolchain: '${{ env.RUST_TOOLCHAIN }}' + components: 'clippy' # Compile, but don't run. - run: cargo test --no-run @@ -45,6 +46,8 @@ jobs: # Deny warnings. RUSTDOCFLAGS="-D warnings" cargo doc + - run: cargo clippy -- -Dwarnings + typos: runs-on: ubuntu-22.04 timeout-minutes: 10 diff --git a/arnoldc/src/arnold.rs b/arnoldc/src/arnold.rs index e0ae689a..847f5909 100644 --- a/arnoldc/src/arnold.rs +++ b/arnoldc/src/arnold.rs @@ -1,6 +1,10 @@ use anyhow::Result; use std::fmt::Formatter; use std::sync::Arc; +use xrcf::frontend::Parse; +use xrcf::frontend::Parser; +use xrcf::frontend::ParserDispatch; +use xrcf::frontend::TokenKind; use xrcf::ir::APInt; use xrcf::ir::Attribute; use xrcf::ir::Block; @@ -11,10 +15,6 @@ use xrcf::ir::OpOperand; use xrcf::ir::Operation; use xrcf::ir::OperationName; use xrcf::ir::Region; -use xrcf::parser::Parse; -use xrcf::parser::Parser; -use xrcf::parser::ParserDispatch; -use xrcf::parser::TokenKind; use xrcf::shared::Shared; use xrcf::shared::SharedExt; diff --git a/arnoldc/src/arnold_to_mlir.rs b/arnoldc/src/arnold_to_mlir.rs index 5cb9fee5..bcb352d7 100644 --- a/arnoldc/src/arnold_to_mlir.rs +++ b/arnoldc/src/arnold_to_mlir.rs @@ -188,8 +188,7 @@ impl ModuleLowering { let operand = Shared::new(operand.into()); ret.set_operand(0, operand); let ret = func::ReturnOp::from_operation(ret); - let ret = Shared::new(ret.into()); - ret + Shared::new(ret.into()) } fn return_zero(func: Shared) { let typ = IntegerType::new(32); diff --git a/arnoldc/src/main.rs b/arnoldc/src/main.rs index 2fe4868e..c905c5a1 100644 --- a/arnoldc/src/main.rs +++ b/arnoldc/src/main.rs @@ -1,3 +1,4 @@ +#![allow(clippy::arc_with_non_send_sync)] mod arnold; mod arnold_to_mlir; mod transform; @@ -36,8 +37,8 @@ struct ArnoldcArgs { fn cli() -> Command { let cli = Command::new("arnoldc").args(xrcf::default_arguments()); - let cli = ArnoldcArgs::augment_args(cli); - cli + + ArnoldcArgs::augment_args(cli) } fn compile_passes() -> Vec<&'static str> { @@ -166,7 +167,7 @@ mod tests { ]; tracing::info!("\nBefore {args:?}:\n{src}"); let out: Shared> = Shared::new(Vec::new().into()); - let result = run_app(Some(out.clone()), args.clone(), &src); + let result = run_app(Some(out.clone()), args.clone(), src); assert!(result.is_ok()); let actual = match result.unwrap() { RewriteResult::Changed(op) => { diff --git a/arnoldc/src/transform.rs b/arnoldc/src/transform.rs index 1851843b..1b317adb 100644 --- a/arnoldc/src/transform.rs +++ b/arnoldc/src/transform.rs @@ -3,15 +3,15 @@ use crate::arnold_to_mlir::ConvertArnoldToMLIR; use anyhow::Result; use xrcf::convert::Pass; use xrcf::convert::RewriteResult; +use xrcf::frontend::default_dispatch; +use xrcf::frontend::default_parse_type; +use xrcf::frontend::Parse; +use xrcf::frontend::Parser; +use xrcf::frontend::ParserDispatch; +use xrcf::frontend::TokenKind; use xrcf::ir::Block; use xrcf::ir::Op; use xrcf::ir::Type; -use xrcf::parser::default_dispatch; -use xrcf::parser::default_parse_type; -use xrcf::parser::Parse; -use xrcf::parser::Parser; -use xrcf::parser::ParserDispatch; -use xrcf::parser::TokenKind; use xrcf::shared::Shared; use xrcf::transform; use xrcf::DefaultTransformDispatch; @@ -25,11 +25,7 @@ fn is_function_call(parser: &Parser) -> bool { && parser.peek_n(1).unwrap().kind == TokenKind::LParen; let known_keyword = { if let TokenKind::BareIdentifier = parser.peek().kind { - match parser.peek().lexeme.as_str() { - "def" => true, - "print" => true, - _ => false, - } + matches!(parser.peek().lexeme.as_str(), "def" | "print") } else { false } @@ -75,9 +71,7 @@ impl ParserDispatch for ArnoldParserDispatch { // Ignore nothing (e.g., ` x, y`). parser.peek().clone() }; - match name.lexeme.clone().as_str() { - _ => default_dispatch(name, parser, parent), - } + default_dispatch(name, parser, parent) } fn parse_type(parser: &mut Parser) -> Result> { default_parse_type(parser) @@ -103,6 +97,7 @@ impl TransformDispatch for ArnoldTransformDispatch { fn preprocess(src: &str) -> String { let mut result = String::new(); for line in src.lines() { + #[allow(clippy::if_same_then_else)] if line.contains("IT'S SHOWTIME") { result.push_str(&format!("{} {{", line)); } else if line.contains("BECAUSE I'M GOING TO SAY PLEASE") { @@ -114,7 +109,7 @@ fn preprocess(src: &str) -> String { } else if line.contains("BULLSHIT") { result.push_str(&line.replace("BULLSHIT", "} BULLSHIT {")); } else { - result.push_str(&line); + result.push_str(line); } result.push('\n'); } @@ -134,7 +129,6 @@ mod tests { use crate::compile_passes; use indoc::indoc; use std::panic::Location; - use tracing; use xrcf::shared::SharedExt; use xrcf::tester::Tester; use xrcf::Passes; diff --git a/xrcf-bin/src/main.rs b/xrcf-bin/src/main.rs index e5407094..3cfd7a2e 100644 --- a/xrcf-bin/src/main.rs +++ b/xrcf-bin/src/main.rs @@ -3,9 +3,9 @@ use clap::Args; use clap::Command; use std::io::Read; use xrcf::convert::RewriteResult; +use xrcf::frontend::DefaultParserDispatch; +use xrcf::frontend::Parser; use xrcf::init_subscriber; -use xrcf::parser::DefaultParserDispatch; -use xrcf::parser::Parser; use xrcf::shared::SharedExt; use xrcf::transform; use xrcf::DefaultTransformDispatch; @@ -26,8 +26,7 @@ struct XRCFArgs { fn cli() -> Command { let cli = Command::new("xrcf").args(xrcf::default_arguments()); - let cli = XRCFArgs::augment_args(cli); - cli + XRCFArgs::augment_args(cli) } fn remove_comments(src: &str) -> String { diff --git a/xrcf/src/convert/experimental_to_mlir.rs b/xrcf/src/convert/experimental_to_mlir.rs index 7a9f851c..3adb3039 100644 --- a/xrcf/src/convert/experimental_to_mlir.rs +++ b/xrcf/src/convert/experimental_to_mlir.rs @@ -23,6 +23,7 @@ use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; use dialect::experimental::PrintfOp; +use std::str::FromStr; use std::sync::Arc; struct PrintLowering; @@ -50,7 +51,7 @@ impl PrintLowering { fn len_specifier(parent: &Shared, len: usize) -> Shared { let mut operation = Operation::default(); operation.set_parent(Some(parent.clone())); - let typ = IntegerType::from_str("i16"); + let typ = IntegerType::from_str("i16").unwrap(); let name = parent.rd().unique_value_name("%"); let result_type = Shared::new(typ.into()); let result = operation.add_new_op_result(&name, result_type); @@ -117,7 +118,7 @@ impl PrintLowering { let var = var.expect("expected vararg"); operation.set_operand(1, var); } - let typ = IntegerType::from_str("i32"); + let typ = IntegerType::from_str("i32").unwrap(); let name = parent.rd().unique_value_name("%"); let result_type = Shared::new(typ.into()); let result = operation.add_new_op_result(&name, result_type); @@ -128,7 +129,7 @@ impl PrintLowering { op.set_identifier("@printf".to_string()); if set_varargs { let varargs = "!llvm.func"; - let varargs = llvm::FunctionType::from_str(varargs); + let varargs = llvm::FunctionType::from_str(varargs).unwrap(); let varargs = Shared::new(varargs.into()); op.set_varargs(Some(varargs)); } @@ -171,7 +172,7 @@ impl PrintLowering { fn printf_func_def(parent: Shared, set_varargs: bool) -> Result> { let mut operation = Operation::default(); operation.set_parent(Some(parent.clone())); - let result_type = crate::ir::IntegerType::from_str("i32"); + let result_type = IntegerType::from_str("i32").unwrap(); let result_type = Shared::new(result_type.into()); operation.set_anonymous_result(result_type)?; diff --git a/xrcf/src/convert/mlir_to_llvmir.rs b/xrcf/src/convert/mlir_to_llvmir.rs index aba843e9..8adcd821 100644 --- a/xrcf/src/convert/mlir_to_llvmir.rs +++ b/xrcf/src/convert/mlir_to_llvmir.rs @@ -27,6 +27,7 @@ use crate::shared::Shared; use crate::shared::SharedExt; use crate::targ3t; use anyhow::Result; +use std::str::FromStr; struct AddLowering; @@ -265,7 +266,7 @@ fn lower_block_argument_types(operation: &mut Operation) { let typ = argument.rd().typ().unwrap(); let typ = typ.rd(); if typ.as_any().is::() { - let typ = targ3t::llvmir::PointerType::from_str("ptr"); + let typ = targ3t::llvmir::PointerType::from_str("ptr").unwrap(); let typ = Shared::new(typ.into()); let name = BlockArgumentName::Unset; let name = Shared::new(name.into()); @@ -366,16 +367,16 @@ fn determine_argument_pairs(block: &Shared) -> Vec<(Shared, Sh /// Replace the operands of the argument pairs by constants if possible. fn replace_constant_argument_pairs(pairs: &mut Vec<(Shared, Shared)>) { - for i in 0..pairs.len() { - let (op_operand, block) = pairs[i].clone(); + for pair in pairs { + let (op_operand, block) = pair.clone(); let new = constant_op_operand(op_operand); if let Some(new) = new { - pairs[i] = (new, block); + *pair = (new, block); } } } -fn verify_argument_pairs(pairs: &Vec<(Shared, Shared)>) { +fn verify_argument_pairs(pairs: &[(Shared, Shared)]) { if pairs.len() != 2 { panic!("Expected two callers"); } @@ -460,7 +461,7 @@ fn insert_phi(block: Shared) { replace_constant_argument_pairs(&mut argument_pairs); verify_argument_pairs(&argument_pairs); phi.set_argument_pairs(Some(argument_pairs)); - let argument = arguments.get(0).unwrap(); + let argument = arguments.first().unwrap(); let phi = Shared::new(phi.into()); set_phi_result(phi.clone(), argument); arguments.clear(); @@ -634,7 +635,7 @@ impl TypeConvert for ConvertMLIRToLLVMIR { let converted = arguments .vec() .iter() - .map(|argument| Self::convert_type(argument)) + .map(Self::convert_type) .collect::>>()?; let arguments = Types::from_vec(converted); let typ = targ3t::llvmir::FunctionType::new(typ.return_types().clone(), arguments); diff --git a/xrcf/src/convert/mod.rs b/xrcf/src/convert/mod.rs index 341c328e..2ab84849 100644 --- a/xrcf/src/convert/mod.rs +++ b/xrcf/src/convert/mod.rs @@ -55,7 +55,7 @@ pub enum RewriteResult { impl RewriteResult { pub fn is_changed(&self) -> Option<&ChangedOp> { match self { - RewriteResult::Changed(op) => Some(&op), + RewriteResult::Changed(op) => Some(op), RewriteResult::Unchanged => None, } } @@ -93,7 +93,7 @@ fn apply_rewrites_helper( for nested_op in ops.iter() { let indent = indent + 1; let result = apply_rewrites_helper(nested_op.clone(), rewrites, indent)?; - if let Some(_) = result.is_changed() { + if result.is_changed().is_some() { let root_passthrough = ChangedOp::new(root.clone()); let root_passthrough = RewriteResult::Changed(root_passthrough); return Ok(root_passthrough); @@ -110,7 +110,7 @@ fn apply_rewrites_helper( if rewrite.is_match(&*root_read)? { debug!("{}--> Success", spaces(indent)); let root_rewrite = rewrite.rewrite(root.clone())?; - if let Some(_) = root_rewrite.is_changed() { + if root_rewrite.is_changed().is_some() { debug!("{}----> Changed", spaces(indent)); return Ok(root_rewrite); } diff --git a/xrcf/src/convert/scf_to_cf.rs b/xrcf/src/convert/scf_to_cf.rs index 29f421ee..8288ecf8 100644 --- a/xrcf/src/convert/scf_to_cf.rs +++ b/xrcf/src/convert/scf_to_cf.rs @@ -68,8 +68,7 @@ fn branch_op(after: Shared) -> Shared { let mut new_op = dialect::cf::BranchOp::from_operation(operation); let operand = Shared::new(OpOperand::from_block(after).into()); new_op.set_dest(operand); - let new_op = Shared::new(new_op.into()); - new_op + Shared::new(new_op.into()) } /// Add a `cf.br` to the end of `block` with destination `after`. @@ -81,7 +80,7 @@ fn add_branch_to_after(block: Shared, after: Shared) { let last_op = last_op.rd(); let yield_op = last_op.as_any().downcast_ref::(); if let Some(yield_op) = yield_op { - let new_op = lower_yield_op(&yield_op, after.clone()).unwrap(); + let new_op = lower_yield_op(yield_op, after.clone()).unwrap(); ops.pop(); ops.push(new_op.clone()); } else { @@ -282,7 +281,7 @@ impl Rewrite for IfLowering { let parent_region = parent.rd().parent().expect("Expected parent region"); let op = op.as_any().downcast_ref::().unwrap(); - let (then, els) = add_blocks(&op, parent_region.clone())?; + let (then, els) = add_blocks(op, parent_region.clone())?; let mut operation = Operation::default(); operation.set_parent(Some(parent.clone())); diff --git a/xrcf/src/dialect/arith/op.rs b/xrcf/src/dialect/arith/op.rs index 6c18bd06..3b8b8cdb 100644 --- a/xrcf/src/dialect/arith/op.rs +++ b/xrcf/src/dialect/arith/op.rs @@ -1,5 +1,9 @@ use crate::convert::ChangedOp; use crate::convert::RewriteResult; +use crate::frontend::Parse; +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; +use crate::frontend::TokenKind; use crate::ir::AnyType; use crate::ir::Attribute; use crate::ir::Block; @@ -11,10 +15,6 @@ use crate::ir::Operation; use crate::ir::OperationName; use crate::ir::Value; use crate::ir::Values; -use crate::parser::Parse; -use crate::parser::Parser; -use crate::parser::ParserDispatch; -use crate::parser::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; diff --git a/xrcf/src/dialect/cf/op.rs b/xrcf/src/dialect/cf/op.rs index 08e07a1a..6d65bd81 100644 --- a/xrcf/src/dialect/cf/op.rs +++ b/xrcf/src/dialect/cf/op.rs @@ -1,12 +1,12 @@ +use crate::frontend::Parse; +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; +use crate::frontend::TokenKind; use crate::ir::Block; use crate::ir::Op; use crate::ir::OpOperand; use crate::ir::Operation; use crate::ir::OperationName; -use crate::parser::Parse; -use crate::parser::Parser; -use crate::parser::ParserDispatch; -use crate::parser::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; diff --git a/xrcf/src/dialect/experimental/op.rs b/xrcf/src/dialect/experimental/op.rs index 667dccf8..3fa7bb99 100644 --- a/xrcf/src/dialect/experimental/op.rs +++ b/xrcf/src/dialect/experimental/op.rs @@ -1,3 +1,7 @@ +use crate::frontend::Parse; +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; +use crate::frontend::TokenKind; use crate::ir::Block; use crate::ir::Constant; use crate::ir::Op; @@ -6,10 +10,6 @@ use crate::ir::Operation; use crate::ir::OperationName; use crate::ir::StringAttr; use crate::ir::Value; -use crate::parser::Parse; -use crate::parser::Parser; -use crate::parser::ParserDispatch; -use crate::parser::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; diff --git a/xrcf/src/dialect/func/op.rs b/xrcf/src/dialect/func/op.rs index 56f72b10..a6d58e18 100644 --- a/xrcf/src/dialect/func/op.rs +++ b/xrcf/src/dialect/func/op.rs @@ -1,3 +1,7 @@ +use crate::frontend::Parse; +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; +use crate::frontend::TokenKind; use crate::ir::AnyType; use crate::ir::Attribute; use crate::ir::Block; @@ -10,14 +14,11 @@ use crate::ir::StringAttr; use crate::ir::Type; use crate::ir::UnsetOp; use crate::ir::Values; -use crate::parser::Parse; -use crate::parser::Parser; -use crate::parser::ParserDispatch; -use crate::parser::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; use std::fmt::Formatter; +use std::str::FromStr; use std::sync::Arc; const TOKEN_KIND: TokenKind = TokenKind::PercentIdentifier; @@ -195,11 +196,8 @@ pub trait Func: Op { let operation = self.operation(); let attributes = operation.rd().attributes(); let attribute = attributes.get("sym_visibility"); - match attribute { - Some(attribute) => Some(attribute.to_string()), - // It is legal to not have set visibility. - None => None, - } + // Returns None when attribute is not set (which is legal). + attribute.map(|attribute| attribute.to_string()) } /// Set the symbol visibility. /// @@ -318,11 +316,10 @@ impl FuncOp { parser: &mut Parser, expected_name: &OperationName, ) -> Option { - if expected_name == &FuncOp::operation_name() { - if parser.check(TokenKind::BareIdentifier) { - let sym_visibility = parser.advance().lexeme.clone(); - return Some(sym_visibility); - } + let name_match = expected_name == &FuncOp::operation_name(); + if name_match && parser.check(TokenKind::BareIdentifier) { + let sym_visibility = parser.advance().lexeme.clone(); + return Some(sym_visibility); } None } @@ -469,7 +466,7 @@ impl Parser { operation.set_operands(self.parse_op_operands(parent.clone().unwrap(), TOKEN_KIND)?); self.expect(TokenKind::Colon)?; let return_type = self.expect(TokenKind::IntType)?; - let return_type = IntegerType::from_str(&return_type.lexeme); + let return_type = IntegerType::from_str(&return_type.lexeme).unwrap(); let result_type = Shared::new(return_type.into()); operation.set_anonymous_result(result_type)?; } diff --git a/xrcf/src/dialect/llvm/attribute.rs b/xrcf/src/dialect/llvm/attribute.rs index 5be9661d..a6c29da4 100644 --- a/xrcf/src/dialect/llvm/attribute.rs +++ b/xrcf/src/dialect/llvm/attribute.rs @@ -1,8 +1,8 @@ +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; use crate::ir::Attribute; use crate::ir::StringType; use crate::ir::Type; -use crate::parser::Parser; -use crate::parser::ParserDispatch; use crate::shared::Shared; use std::fmt::Formatter; use std::fmt::Result; diff --git a/xrcf/src/dialect/llvm/op.rs b/xrcf/src/dialect/llvm/op.rs index 80af7b34..0f9e0723 100644 --- a/xrcf/src/dialect/llvm/op.rs +++ b/xrcf/src/dialect/llvm/op.rs @@ -2,6 +2,10 @@ use crate::dialect::func; use crate::dialect::func::Call; use crate::dialect::func::Func; use crate::dialect::llvm::attribute::LinkageAttr; +use crate::frontend::Parse; +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; +use crate::frontend::TokenKind; use crate::ir::AnyAttr; use crate::ir::Attribute; use crate::ir::Attributes; @@ -13,10 +17,6 @@ use crate::ir::Operation; use crate::ir::OperationName; use crate::ir::StringAttr; use crate::ir::Type; -use crate::parser::Parse; -use crate::parser::Parser; -use crate::parser::ParserDispatch; -use crate::parser::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; diff --git a/xrcf/src/dialect/llvm/typ.rs b/xrcf/src/dialect/llvm/typ.rs index 2d64b73e..42ee52c2 100644 --- a/xrcf/src/dialect/llvm/typ.rs +++ b/xrcf/src/dialect/llvm/typ.rs @@ -8,6 +8,7 @@ use crate::shared::SharedExt; use anyhow::Result; use std::fmt::Display; use std::fmt::Formatter; +use std::str::FromStr; /// Represent an integer type such as i32 or i64. /// @@ -31,7 +32,7 @@ impl ArrayType { }; let (num_elements, element_type) = s.split_once('x').unwrap(); let num_elements = num_elements.parse::().unwrap(); - let element_type = IntegerType::from_str(element_type); + let element_type = IntegerType::from_str(element_type).unwrap(); let element_type = Shared::new(element_type.into()); Self { num_elements, @@ -43,16 +44,16 @@ impl ArrayType { let text = s.to_string(); let text = text.trim_matches('"'); let num_elements = text.as_bytes().len() as u32; - let element_type = IntegerType::from_str("i8"); + let element_type = IntegerType::from_str("i8").unwrap(); let element_type = Shared::new(element_type.into()); Self { num_elements, element_type, } } - pub fn for_bytes(bytes: &Vec) -> Self { + pub fn for_bytes(bytes: &[u8]) -> Self { let num_elements = bytes.len() as u32; - let element_type = IntegerType::from_str("i8"); + let element_type = IntegerType::from_str("i8").unwrap(); let element_type = Shared::new(element_type.into()); Self { num_elements, @@ -103,13 +104,17 @@ impl FunctionType { pub fn arguments(&self) -> &Types { &self.arguments } +} + +impl FromStr for FunctionType { + type Err = (); /// Parse `!llvm.func`. - pub fn from_str(s: &str) -> Self { + fn from_str(s: &str) -> Result { assert!(s.starts_with("!llvm.func<")); let s = s.strip_prefix("!llvm.func<").unwrap(); - let (return_types, arguments) = s.split_once('(').unwrap(); + let (ret_types, arguments) = s.split_once('(').unwrap(); - let return_type = IntegerType::from_str(return_types.trim()); + let return_type = IntegerType::from_str(ret_types.trim()).unwrap(); let return_type = Shared::new(return_type.into()); let return_types = Types::from_vec(vec![return_type]); @@ -122,10 +127,10 @@ impl FunctionType { } let arguments = Types::from_vec(arguments); - Self { + Ok(Self { return_types, arguments, - } + }) } } @@ -149,8 +154,12 @@ impl PointerType { pub fn new() -> Self { Self {} } - pub fn from_str(_s: &str) -> Self { - Self {} +} + +impl FromStr for PointerType { + type Err = (); + fn from_str(_s: &str) -> Result { + Ok(Self {}) } } @@ -170,9 +179,13 @@ impl VariadicType { pub fn new() -> Self { Self {} } - pub fn from_str(s: &str) -> Self { +} + +impl FromStr for VariadicType { + type Err = (); + fn from_str(s: &str) -> Result { assert!(s == "...", "Expected '...', but got {s}"); - Self {} + Ok(Self {}) } } @@ -191,16 +204,16 @@ impl TypeParse for LLVM { return Ok(Shared::new(ArrayType::parse_str(src).into())); } if src.starts_with("!llvm.func") { - return Ok(Shared::new(FunctionType::from_str(src).into())); + return Ok(Shared::new(FunctionType::from_str(src).unwrap().into())); } if src.starts_with("!llvm.ptr") { - return Ok(Shared::new(PointerType::from_str(src).into())); + return Ok(Shared::new(PointerType::from_str(src).unwrap().into())); } if src.starts_with("ptr") { - return Ok(Shared::new(PointerType::from_str(src).into())); + return Ok(Shared::new(PointerType::from_str(src).unwrap().into())); } if src == "..." { - return Ok(Shared::new(VariadicType::from_str(src).into())); + return Ok(Shared::new(VariadicType::from_str(src).unwrap().into())); } todo!("Not yet implemented for {}", src) } diff --git a/xrcf/src/dialect/scf/op.rs b/xrcf/src/dialect/scf/op.rs index 8b211811..f831cb08 100644 --- a/xrcf/src/dialect/scf/op.rs +++ b/xrcf/src/dialect/scf/op.rs @@ -1,12 +1,12 @@ +use crate::frontend::Parse; +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; +use crate::frontend::TokenKind; use crate::ir::Block; use crate::ir::Op; use crate::ir::Operation; use crate::ir::OperationName; use crate::ir::Region; -use crate::parser::Parse; -use crate::parser::Parser; -use crate::parser::ParserDispatch; -use crate::parser::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; diff --git a/xrcf/src/parser/mod.rs b/xrcf/src/frontend/mod.rs similarity index 100% rename from xrcf/src/parser/mod.rs rename to xrcf/src/frontend/mod.rs diff --git a/xrcf/src/parser/parser.rs b/xrcf/src/frontend/parser.rs similarity index 97% rename from xrcf/src/parser/parser.rs rename to xrcf/src/frontend/parser.rs index 0ecfd998..b467b254 100644 --- a/xrcf/src/parser/parser.rs +++ b/xrcf/src/frontend/parser.rs @@ -5,6 +5,9 @@ use crate::dialect::func; use crate::dialect::llvm; use crate::dialect::llvm::LLVM; use crate::dialect::scf; +use crate::frontend::scanner::Scanner; +use crate::frontend::token::Token; +use crate::frontend::token::TokenKind; use crate::ir::Attribute; use crate::ir::Block; use crate::ir::BlockName; @@ -20,12 +23,10 @@ use crate::ir::Type; use crate::ir::TypeParse; use crate::ir::Value; use crate::ir::Values; -use crate::parser::scanner::Scanner; -use crate::parser::token::Token; -use crate::parser::token::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; +use std::str::FromStr; use std::sync::Arc; /// Interface to add custom operations to the parser. @@ -96,7 +97,7 @@ pub fn default_dispatch( "scf.yield" => ::op(parser, parent), _ => { let msg = parser.error(&name, &format!("Unknown operation: {}", name.lexeme)); - return Err(anyhow::anyhow!(msg)); + Err(anyhow::anyhow!(msg)) } } } @@ -104,7 +105,7 @@ pub fn default_dispatch( pub fn default_parse_type(parser: &mut Parser) -> Result> { if parser.check(TokenKind::IntType) { let typ = parser.advance(); - let typ = IntegerType::from_str(&typ.lexeme); + let typ = IntegerType::from_str(&typ.lexeme).unwrap(); return Ok(Shared::new(typ.into())); } let text = parser.parse_type_text()?; @@ -153,12 +154,13 @@ pub struct Parser { src: String, tokens: Vec, current: usize, - parse_op: std::marker::PhantomData, + _marker: std::marker::PhantomData, } #[allow(dead_code)] enum Dialects { Builtin, + #[allow(clippy::upper_case_acronyms)] LLVM, } @@ -289,7 +291,7 @@ impl Parser { } if ops.rd().is_empty() { let token = self.peek(); - let msg = self.error(&token, "Could not find operations in block"); + let msg = self.error(token, "Could not find operations in block"); return Err(anyhow::anyhow!(msg)); } for op in block.rd().ops().rd().iter() { @@ -357,7 +359,7 @@ impl Parser { src: src.to_string(), tokens: Scanner::scan(src)?, current: 0, - parse_op: std::marker::PhantomData, + _marker: std::marker::PhantomData, }; let op = T::parse_op(&mut parser, None)?; let op_rd = op.clone(); diff --git a/xrcf/src/parser/scanner.rs b/xrcf/src/frontend/scanner.rs similarity index 95% rename from xrcf/src/parser/scanner.rs rename to xrcf/src/frontend/scanner.rs index c2245de8..632c67bb 100644 --- a/xrcf/src/parser/scanner.rs +++ b/xrcf/src/frontend/scanner.rs @@ -1,6 +1,6 @@ -use crate::parser::token::Location; -use crate::parser::token::Token; -use crate::parser::token::TokenKind; +use crate::frontend::token::Location; +use crate::frontend::token::Token; +use crate::frontend::token::TokenKind; use anyhow::Result; pub struct Scanner { @@ -63,12 +63,11 @@ impl Scanner { } }; } - let word = if let Some(c) = already_matched { + if let Some(c) = already_matched { format!("{}{}", c, word) } else { word - }; - word + } } fn add_token(&mut self, kind: TokenKind) { let lexeme = if kind == TokenKind::Eof { @@ -82,16 +81,16 @@ impl Scanner { self.tokens.push(Token::new(kind, lexeme, location)); } fn number(&mut self) -> Result<()> { - while self.peek().is_digit(10) { + while self.peek().is_ascii_digit() { self.advance(); } let mut is_float = false; - if self.peek() == '.' && self.peek_next().is_digit(10) { + if self.peek() == '.' && self.peek_next().is_ascii_digit() { if self.peek() == '.' { is_float = true; } self.advance(); - while self.peek().is_digit(10) { + while self.peek().is_ascii_digit() { self.advance(); } } @@ -108,7 +107,7 @@ impl Scanner { } // Whether the character is a valid identifier character. fn is_identifier(c: char) -> bool { - c.is_alphabetic() || c == '_' || c == '.' || c.is_digit(10) + c.is_alphabetic() || c == '_' || c == '.' || c.is_ascii_digit() } // Scan identifiers and keywords. fn identifier(&mut self) -> Result<()> { @@ -137,7 +136,7 @@ impl Scanner { Ok(()) } fn is_int_type(word: &str) -> bool { - let types = vec!["i1", "i4", "i8", "i16", "i32", "i64", "i128"]; + let types = ["i1", "i4", "i8", "i16", "i32", "i64", "i128"]; types.contains(&word) } fn int_type(&mut self, c: char) -> Result<()> { @@ -205,7 +204,7 @@ impl Scanner { '-' => self.arrow_or_minus()?, '"' => self.string()?, s if self.is_int_type_start(s) => self.int_type(s)?, - s if s.is_digit(10) => self.number()?, + s if s.is_ascii_digit() => self.number()?, s if Scanner::is_identifier_start(s) => self.identifier()?, s if self.is_comment(s) => self.comment()?, _ => { diff --git a/xrcf/src/parser/token.rs b/xrcf/src/frontend/token.rs similarity index 100% rename from xrcf/src/parser/token.rs rename to xrcf/src/frontend/token.rs diff --git a/xrcf/src/ir/attribute.rs b/xrcf/src/ir/attribute.rs index 23098588..a64c463c 100644 --- a/xrcf/src/ir/attribute.rs +++ b/xrcf/src/ir/attribute.rs @@ -1,3 +1,6 @@ +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; +use crate::frontend::TokenKind; use crate::ir::bytes_to_llvm_string; use crate::ir::escape; use crate::ir::llvm_string_to_bytes; @@ -6,15 +9,13 @@ use crate::ir::APInt; use crate::ir::IntegerType; use crate::ir::StringType; use crate::ir::Type; -use crate::parser::Parser; -use crate::parser::ParserDispatch; -use crate::parser::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; use std::collections::HashMap; use std::fmt::Display; use std::fmt::Formatter; +use std::str::FromStr; use std::sync::Arc; /// Attributes are known-constant values of operations (a variable is not allowed). @@ -63,7 +64,7 @@ impl Attribute for BooleanAttr { Self { value } } fn typ(&self) -> Shared { - Shared::new(IntegerType::from_str("i1").into()) + Shared::new(IntegerType::from_str("i1").unwrap().into()) } fn as_any(&self) -> &dyn std::any::Any { self @@ -282,7 +283,7 @@ impl Parser { let _colon = self.expect(TokenKind::Colon)?; let num_bits = self.expect(TokenKind::IntType)?; - let typ = IntegerType::from_str(&num_bits.lexeme); + let typ = IntegerType::from_str(&num_bits.lexeme).unwrap(); let value = APInt::from_str(&num_bits.lexeme, &value); let integer = IntegerAttr::new(typ, value); Ok(integer) diff --git a/xrcf/src/ir/block.rs b/xrcf/src/ir/block.rs index 36dbdfdc..e6ab7384 100644 --- a/xrcf/src/ir/block.rs +++ b/xrcf/src/ir/block.rs @@ -194,6 +194,7 @@ impl Block { if op.is_func() { for argument in operation.rd().arguments().into_iter() { match &*argument.rd() { + #[allow(clippy::single_match)] Value::BlockArgument(arg) => match &*arg.name().rd() { BlockArgumentName::Name(curr) => { if curr == name { @@ -325,7 +326,7 @@ impl Block { self.ops.wr().insert(index, op); } pub fn insert_after(&self, earlier: Shared, later: Shared) { - match self.index_of(&*earlier.rd()) { + match self.index_of(&earlier.rd()) { Some(index) => self.insert_op(later, index + 1), None => { panic!("Could not find op in block during insert_after"); @@ -333,19 +334,19 @@ impl Block { } } pub fn insert_before(&self, earlier: Shared, later: Shared) { - match self.index_of(&*later.rd()) { + match self.index_of(&later.rd()) { Some(index) => self.insert_op(earlier, index), None => panic!("could not find op in block"), } } pub fn replace(&self, old: Shared, new: Shared) { - match self.index_of(&*old.rd()) { + match self.index_of(&old.rd()) { Some(index) => self.ops().wr()[index] = new, None => panic!("could not find op in block"), } } pub fn remove(&self, op: Shared) { - match self.index_of(&*op.rd()) { + match self.index_of(&op.rd()) { Some(index) => self.ops().wr().remove(index), None => panic!("could not find op in block"), }; @@ -393,12 +394,12 @@ impl Block { if !arguments.is_empty() { write!(f, "({arguments})")?; } - write!(f, ":\n")?; + writeln!(f, ":")?; } for op in self.ops().rd().iter() { write!(f, "{}", crate::ir::spaces(indent))?; op.rd().display(f, indent)?; - write!(f, "\n")?; + writeln!(f)?; } Ok(()) } diff --git a/xrcf/src/ir/mod.rs b/xrcf/src/ir/mod.rs index 7523000a..67fa39c6 100644 --- a/xrcf/src/ir/mod.rs +++ b/xrcf/src/ir/mod.rs @@ -86,11 +86,12 @@ fn test_llvm_string_to_bytes() { /// Convert a vector of bytes to a string while handling LLVM escape sequences. /// -// Explicitly print the null byte too or else the vector length will not match -// the text that is shown. - -// A backslash with two hex characters defines the byte in LLVM IR in hex, so -// \00 is the null byte in LLVM IR. +/// Explicitly print the null byte too or else the vector length will not match +/// the text that is shown. +/// +/// A backslash with two hex characters defines the byte in LLVM IR in hex, so A +/// backslash with two hex characters defines the byte in LLVM IR in hex, so \00 +/// is the null byte in LLVM IR. pub fn bytes_to_llvm_string(bytes: &[u8]) -> String { let src = String::from_utf8(bytes.to_vec()).unwrap(); src.replace("\0", "\\00").replace("\n", "\\0A") @@ -104,13 +105,11 @@ fn test_bytes_to_llvm_string() { } pub fn escape(src: &str) -> String { - let src = src.replace("\n", "\\n"); - src + src.replace("\n", "\\n") } pub fn unescape(src: &str) -> String { - let src = src.replace("\\n", "\n"); - src + src.replace("\\n", "\n") } /// Generate a new name as part of printing. diff --git a/xrcf/src/ir/module.rs b/xrcf/src/ir/module.rs index 80896175..27c5a47a 100644 --- a/xrcf/src/ir/module.rs +++ b/xrcf/src/ir/module.rs @@ -1,12 +1,12 @@ +use crate::frontend::Parse; +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; +use crate::frontend::TokenKind; use crate::ir::Block; use crate::ir::Op; use crate::ir::Operation; use crate::ir::OperationName; use crate::ir::Region; -use crate::parser::Parse; -use crate::parser::Parser; -use crate::parser::ParserDispatch; -use crate::parser::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; @@ -58,7 +58,9 @@ impl ModuleOp { None => return Err(anyhow::anyhow!("Expected 1 block in module, got 0")), }; match block.rd().ops().rd().first() { + #[allow(clippy::needless_return)] None => return Err(anyhow::anyhow!("Expected 1 op, got 0")), + #[allow(clippy::needless_return)] Some(op) => return Ok(op.clone()), }; } diff --git a/xrcf/src/ir/op.rs b/xrcf/src/ir/op.rs index c45a4e0e..9ecd6382 100644 --- a/xrcf/src/ir/op.rs +++ b/xrcf/src/ir/op.rs @@ -1,4 +1,6 @@ use crate::convert::RewriteResult; +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; use crate::ir::Attribute; use crate::ir::Block; use crate::ir::Operation; @@ -6,8 +8,6 @@ use crate::ir::OperationName; use crate::ir::Region; use crate::ir::Value; use crate::ir::Values; -use crate::parser::Parser; -use crate::parser::ParserDispatch; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; @@ -83,7 +83,7 @@ pub trait Op { false } fn attribute(&self, key: &str) -> Option> { - Some(self.operation().rd().attributes().get(key)?) + self.operation().rd().attributes().get(key) } /// Insert `earlier` before `self` inside `self`'s parent block. fn insert_before(&self, earlier: Shared) { diff --git a/xrcf/src/ir/op_operand.rs b/xrcf/src/ir/op_operand.rs index 8c8bc17a..75bfc618 100644 --- a/xrcf/src/ir/op_operand.rs +++ b/xrcf/src/ir/op_operand.rs @@ -1,3 +1,6 @@ +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; +use crate::frontend::TokenKind; use crate::ir::Block; use crate::ir::BlockLabel; use crate::ir::Constant; @@ -5,9 +8,6 @@ use crate::ir::Op; use crate::ir::Operation; use crate::ir::Type; use crate::ir::Value; -use crate::parser::Parser; -use crate::parser::ParserDispatch; -use crate::parser::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; @@ -180,7 +180,7 @@ impl Parser { Ok(Shared::new(operand.into())) } else { let msg = "Expected operand."; - let msg = self.error(&next, msg); + let msg = self.error(next, msg); return Err(anyhow::anyhow!(msg)); } } diff --git a/xrcf/src/ir/operation.rs b/xrcf/src/ir/operation.rs index 190e9000..02ef14ac 100644 --- a/xrcf/src/ir/operation.rs +++ b/xrcf/src/ir/operation.rs @@ -1,3 +1,6 @@ +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; +use crate::frontend::TokenKind; use crate::ir::AnonymousResult; use crate::ir::Attributes; use crate::ir::Block; @@ -14,9 +17,6 @@ use crate::ir::UnsetOpResult; use crate::ir::Users; use crate::ir::Value; use crate::ir::Values; -use crate::parser::Parser; -use crate::parser::ParserDispatch; -use crate::parser::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; @@ -125,7 +125,7 @@ pub fn display_region_inside_func( if let Some(region) = region { let region = region.rd(); if region.blocks().into_iter().next().is_none() { - write!(f, "\n") + writeln!(f) } else { region.display(f, indent) } @@ -137,16 +137,14 @@ pub fn display_region_inside_func( /// Set the value at `index` or grow the vector by one if `index` equals the /// length of the vector. fn set_or_grow_by_one(vec: &mut Vec, index: usize, value: T) { - if index < vec.len() { - vec[index] = value; - } else if index == vec.len() { - vec.push(value); - } else { - panic!( + match index.cmp(&vec.len()) { + std::cmp::Ordering::Less => vec[index] = value, + std::cmp::Ordering::Equal => vec.push(value), + std::cmp::Ordering::Greater => panic!( "tried to set value at index {} but length is {}", index, vec.len() - ); + ), } } diff --git a/xrcf/src/ir/region.rs b/xrcf/src/ir/region.rs index f36aec05..470b5c54 100644 --- a/xrcf/src/ir/region.rs +++ b/xrcf/src/ir/region.rs @@ -26,7 +26,7 @@ pub struct Region { /// will point to blocks that occur later. If we would refresh the name during /// printing of the block (like we do with ssa variables), then the operands /// would print outdated names. -fn set_fresh_block_labels(blocks: &Vec>) { +fn set_fresh_block_labels(blocks: &[Shared]) { let mut label_index: usize = 1; for block in blocks.iter() { let block = block.rd(); @@ -102,7 +102,7 @@ impl Region { self.parent = parent; } pub fn display(&self, f: &mut Formatter<'_>, indent: i32) -> std::fmt::Result { - write!(f, " {{\n")?; + writeln!(f, " {{")?; let blocks = self.blocks(); let blocks = blocks.vec(); let blocks = blocks.rd(); diff --git a/xrcf/src/ir/typ.rs b/xrcf/src/ir/typ.rs index e39722f5..92b41f09 100644 --- a/xrcf/src/ir/typ.rs +++ b/xrcf/src/ir/typ.rs @@ -1,14 +1,14 @@ +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; +use crate::frontend::TokenKind; use crate::ir::OpOperand; use crate::ir::OpOperands; -use crate::parser::Parser; -use crate::parser::ParserDispatch; -use crate::parser::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; use std::fmt::Display; use std::fmt::Formatter; - +use std::str::FromStr; pub trait Type { /// Display the type. /// @@ -88,10 +88,14 @@ impl IntegerType { pub fn new(num_bits: u64) -> Self { Self { num_bits } } - pub fn from_str(s: &str) -> Self { +} + +impl std::str::FromStr for IntegerType { + type Err = (); + fn from_str(s: &str) -> Result { let s = s.strip_prefix("i").expect("no i prefix"); let num_bits = s.parse::().unwrap(); - Self { num_bits } + Ok(Self { num_bits }) } } @@ -145,7 +149,7 @@ impl APInt { } } pub fn from_str(typ: &str, value: &str) -> Self { - let typ = IntegerType::from_str(typ); + let typ = IntegerType::from_str(typ).unwrap(); let value = value.parse::().unwrap(); Self::new(typ.num_bits, value, true) } @@ -175,7 +179,7 @@ impl Display for APInt { /// A collection of `Type`s. /// /// Provides some convenience methods around [Type]s. -#[derive(Clone)] +#[derive(Clone, Default)] pub struct Types { types: Vec>, } @@ -197,12 +201,6 @@ impl Types { } } -impl Default for Types { - fn default() -> Self { - Self { types: vec![] } - } -} - impl Display for Types { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let joined = self diff --git a/xrcf/src/ir/value.rs b/xrcf/src/ir/value.rs index 7ec5ea7c..954c5624 100644 --- a/xrcf/src/ir/value.rs +++ b/xrcf/src/ir/value.rs @@ -1,3 +1,6 @@ +use crate::frontend::Parser; +use crate::frontend::ParserDispatch; +use crate::frontend::TokenKind; use crate::ir::generate_new_name; use crate::ir::Attribute; use crate::ir::Block; @@ -9,9 +12,6 @@ use crate::ir::Type; use crate::ir::TypeConvert; use crate::ir::Types; use crate::ir::VariableRenamer; -use crate::parser::Parser; -use crate::parser::ParserDispatch; -use crate::parser::TokenKind; use crate::shared::Shared; use crate::shared::SharedExt; use anyhow::Result; @@ -394,6 +394,9 @@ impl Users { Users::OpOperands(users) => users.len(), } } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } } pub struct Variadic; @@ -538,7 +541,7 @@ impl Value { let ptr = BlockPtr::new(block); Value::BlockPtr(ptr) } - fn find_users(&self, ops: &Vec>) -> Vec> { + fn find_users(&self, ops: &[Shared]) -> Vec> { let mut out = Vec::new(); for op in ops.iter() { for operand in op.rd().operation().rd().operands().into_iter() { @@ -552,8 +555,8 @@ impl Value { } fn block_arg_users(&self, arg: &BlockArgument) -> Vec> { let parent = arg.parent(); - let parent = if parent.is_some() { - parent.unwrap() + let parent = if let Some(parent) = parent { + parent } else { panic!("BlockArgument {arg} has no parent operation"); }; diff --git a/xrcf/src/lib.rs b/xrcf/src/lib.rs index 1450d7cd..4dd926dc 100644 --- a/xrcf/src/lib.rs +++ b/xrcf/src/lib.rs @@ -37,12 +37,14 @@ //! //! So, the long-term goal of this project is to provide an easy-to-use set of tools that can be used to build your own compiler. //! In other words, it should be easy to build a compiler that can transform your favorite language to this project's core IR, and then it should be easy to transform this to various platforms such as GPUs, CPUs, and TPUs. +#![allow(clippy::new_without_default)] +#![allow(clippy::arc_with_non_send_sync)] mod canonicalize; pub mod convert; pub mod dialect; +pub mod frontend; pub mod ir; -pub mod parser; pub mod shared; pub mod targ3t; #[cfg(feature = "test-utils")] diff --git a/xrcf/src/targ3t/llvmir/op.rs b/xrcf/src/targ3t/llvmir/op.rs index c0fe6103..3f0d490d 100644 --- a/xrcf/src/targ3t/llvmir/op.rs +++ b/xrcf/src/targ3t/llvmir/op.rs @@ -93,7 +93,7 @@ impl Op for AddOp { let operation = self.operation().rd(); write!(f, "{} = add ", operation.results())?; display_operands(f, &operation.operands())?; - write!(f, "\n") + writeln!(f) } } @@ -327,7 +327,7 @@ impl Op for FuncOp { write!(f, ")")?; let operation = self.operation().rd(); - display_region_inside_func(f, &*operation, indent) + display_region_inside_func(f, &operation, indent) } } @@ -374,9 +374,9 @@ impl Op for ModuleOp { &self.operation } fn display(&self, f: &mut Formatter<'_>, indent: i32) -> std::fmt::Result { - write!(f, "; ModuleID = '{}'\n", self.module_id)?; + writeln!(f, "; ModuleID = '{}'", self.module_id)?; write!(f, r#"source_filename = "{}""#, self.source_filename)?; - write!(f, "\n\n")?; + writeln!(f, "\n")?; if let Some(region) = self.operation().rd().region() { for block in region.rd().blocks().into_iter() { block.rd().display(f, indent)?; @@ -518,6 +518,9 @@ impl StoreOp { pub fn len(&self) -> Option { self.len } + pub fn is_empty(&self) -> bool { + self.len() == Some(0) + } } impl Op for StoreOp { diff --git a/xrcf/src/targ3t/llvmir/typ.rs b/xrcf/src/targ3t/llvmir/typ.rs index 90948f6d..ce47ded1 100644 --- a/xrcf/src/targ3t/llvmir/typ.rs +++ b/xrcf/src/targ3t/llvmir/typ.rs @@ -11,8 +11,9 @@ pub struct ArrayType { element_type: Shared, } -impl ArrayType { - pub fn from_str(s: &str) -> Self { +impl std::str::FromStr for ArrayType { + type Err = anyhow::Error; + fn from_str(s: &str) -> Result { assert!(s.starts_with("["), "Expected {} to start with [", s); todo!("ArrayType not impl") } @@ -69,8 +70,12 @@ impl PointerType { pub fn new() -> Self { Self {} } - pub fn from_str(_s: &str) -> Self { - Self {} +} + +impl std::str::FromStr for PointerType { + type Err = anyhow::Error; + fn from_str(_s: &str) -> Result { + Ok(Self {}) } } diff --git a/xrcf/src/tester.rs b/xrcf/src/tester.rs index ee9480d5..5a9a1717 100644 --- a/xrcf/src/tester.rs +++ b/xrcf/src/tester.rs @@ -1,8 +1,8 @@ use crate::convert::RewriteResult; +use crate::frontend::DefaultParserDispatch; +use crate::frontend::Parser; use crate::init_subscriber; use crate::ir::Op; -use crate::parser::DefaultParserDispatch; -use crate::parser::Parser; use crate::shared::Shared; use crate::shared::SharedExt; use crate::transform; diff --git a/xrcf/src/transform.rs b/xrcf/src/transform.rs index 84b2948c..df1c1123 100644 --- a/xrcf/src/transform.rs +++ b/xrcf/src/transform.rs @@ -18,7 +18,6 @@ use std::fmt; use std::fmt::Display; use tracing::subscriber::SetGlobalDefaultError; use tracing::Level; -use tracing_subscriber; /// A transformation pass (e.g., `--convert-func-to-llvm`). #[derive(Clone)] @@ -43,9 +42,6 @@ impl SinglePass { pass: pass.to_string(), } } - pub fn to_string(&self) -> String { - self.pass.clone() - } } /// A collection of [SinglePass]es. @@ -173,7 +169,7 @@ impl TransformDispatch for DefaultTransformDispatch { ConvertFuncToLLVM::NAME => ConvertFuncToLLVM::convert(op.clone()), ConvertMLIRToLLVMIR::NAME => ConvertMLIRToLLVMIR::convert(op.clone()), ConvertSCFToCF::NAME => ConvertSCFToCF::convert(op.clone()), - _ => return Err(anyhow::anyhow!("Unknown pass: {}", pass)), + _ => Err(anyhow::anyhow!("Unknown pass: {}", pass)), } } } diff --git a/xrcf/tests/arith.rs b/xrcf/tests/arith.rs index d16afc7c..47265bdc 100644 --- a/xrcf/tests/arith.rs +++ b/xrcf/tests/arith.rs @@ -19,7 +19,7 @@ fn parse_module() { } "}; let (_module, actual) = Tester::parse(src); - Tester::check_lines_contain(&actual, &src, Location::caller()); + Tester::check_lines_contain(&actual, src, Location::caller()); } #[test] diff --git a/xrcf/tests/canonicalize.rs b/xrcf/tests/canonicalize.rs index 62cefd5a..9beab1f1 100644 --- a/xrcf/tests/canonicalize.rs +++ b/xrcf/tests/canonicalize.rs @@ -3,10 +3,10 @@ extern crate xrcf; use indoc::indoc; use std::panic::Location; use xrcf::dialect::arith; +use xrcf::frontend::DefaultParserDispatch; +use xrcf::frontend::Parser; use xrcf::ir; use xrcf::ir::Op; -use xrcf::parser::DefaultParserDispatch; -use xrcf::parser::Parser; use xrcf::shared::SharedExt; use xrcf::tester::Tester; diff --git a/xrcf/tests/convert/cf_to_llvm.rs b/xrcf/tests/convert/cf_to_llvm.rs index d3b17abb..20845284 100644 --- a/xrcf/tests/convert/cf_to_llvm.rs +++ b/xrcf/tests/convert/cf_to_llvm.rs @@ -48,7 +48,7 @@ fn test_if_else() { } "#}; let (module, actual) = Tester::parse(src); - Tester::check_lines_exact(&actual, &src, Location::caller()); + Tester::check_lines_exact(&actual, src, Location::caller()); Tester::verify(module); let (module, actual) = Tester::transform(flags(), src); Tester::check_lines_exact(&actual, expected, Location::caller()); diff --git a/xrcf/tests/convert/func_to_llvm.rs b/xrcf/tests/convert/func_to_llvm.rs index 39ef6d75..eacf161a 100644 --- a/xrcf/tests/convert/func_to_llvm.rs +++ b/xrcf/tests/convert/func_to_llvm.rs @@ -64,7 +64,7 @@ fn test_hello_world() { llvm.func @something() -> i32 "#}; let (_module, actual) = Tester::parse(src); - Tester::check_lines_contain(&actual, &src, Location::caller()); + Tester::check_lines_contain(&actual, src, Location::caller()); let (module, actual) = Tester::transform(flags(), src); Tester::verify(module); Tester::check_lines_contain(&actual, expected, Location::caller()); @@ -102,7 +102,7 @@ fn test_hello_world() { } "#}; let (_module, actual) = Tester::parse(src); - Tester::check_lines_contain(&actual, &src, Location::caller()); + Tester::check_lines_contain(&actual, src, Location::caller()); let (module, actual) = Tester::transform(flags(), src); Tester::verify(module); Tester::check_lines_contain(&actual, expected, Location::caller()); diff --git a/xrcf/tests/convert/mlir_to_llvmir.rs b/xrcf/tests/convert/mlir_to_llvmir.rs index 497e4583..d0e1add2 100644 --- a/xrcf/tests/convert/mlir_to_llvmir.rs +++ b/xrcf/tests/convert/mlir_to_llvmir.rs @@ -76,7 +76,7 @@ fn test_add_one() { } "#}; let (_module, actual) = Tester::parse(src); - Tester::check_lines_contain(&actual, &src, Location::caller()); + Tester::check_lines_contain(&actual, src, Location::caller()); let (module, actual) = Tester::transform(flags(), src); Tester::verify(module); Tester::check_lines_contain(&actual, expected, Location::caller()); @@ -119,7 +119,7 @@ fn test_hello_world() { !0 = !{i32 2, !"Debug Info Version", i32 3} "#}; let (_module, actual) = Tester::parse(src); - Tester::check_lines_contain(&actual, &src, Location::caller()); + Tester::check_lines_contain(&actual, src, Location::caller()); let (module, actual) = Tester::transform(flags(), src); Tester::verify(module); Tester::check_lines_contain(&actual, expected, Location::caller()); @@ -233,7 +233,7 @@ fn test_if_else() { !0 = !{i32 2, !"Debug Info Version", i32 3} "#}; let (_module, actual) = Tester::parse(src); - Tester::check_lines_exact(&actual, &src, Location::caller()); + Tester::check_lines_exact(&actual, src, Location::caller()); let (module, actual) = Tester::transform(flags(), src); Tester::verify(module); Tester::check_lines_exact(&actual, expected, Location::caller()); diff --git a/xrcf/tests/convert/scf_to_cf.rs b/xrcf/tests/convert/scf_to_cf.rs index 4d76b381..66d303b2 100644 --- a/xrcf/tests/convert/scf_to_cf.rs +++ b/xrcf/tests/convert/scf_to_cf.rs @@ -46,7 +46,7 @@ fn test_if_with_yield() { "#}; let (module, actual) = Tester::parse(src); Tester::verify(module); - Tester::check_lines_contain(&actual, &src, Location::caller()); + Tester::check_lines_contain(&actual, src, Location::caller()); let (module, actual) = Tester::transform(flags(), src); Tester::verify(module); Tester::check_lines_exact(&actual, expected, Location::caller()); @@ -84,7 +84,7 @@ fn test_if_without_yield() { "#}; let (module, actual) = Tester::parse(src); Tester::verify(module); - Tester::check_lines_contain(&actual, &src, Location::caller()); + Tester::check_lines_contain(&actual, src, Location::caller()); let (module, actual) = Tester::transform(flags(), src); Tester::verify(module); Tester::check_lines_contain(&actual, expected, Location::caller());