Skip to content

Commit

Permalink
Fix rustc and clippy warnings (#492)
Browse files Browse the repository at this point in the history
* Fix most rustc warnings

* Fix clippy warnings

* Abstract LLVMConstArray

* Fix CI
  • Loading branch information
DaniPopes authored May 16, 2024
1 parent 6c0fb56 commit 7684346
Show file tree
Hide file tree
Showing 43 changed files with 309 additions and 290 deletions.
44 changes: 23 additions & 21 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ on: [push, pull_request]
env:
CARGO_TERM_COLOR: always
DOC_LLVM_FEATURE: llvm17-0
DOC_LLVM_VERSION: '17.0'
DOC_LLVM_VERSION: "17.0"
DOC_PATH: target/doc

jobs:
Expand All @@ -14,9 +14,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Install Rust Stable
run: rustup toolchain install stable
uses: dtolnay/rust-toolchain@stable
- name: Install typos
run: cargo install typos-cli
uses: taiki-e/install-action@typos
- name: Run typos
run: typos .
tests:
Expand All @@ -39,22 +39,24 @@ jobs:
- ["15.0", "15-0"]
- ["16.0", "16-0"]
- ["17.0", "17-0"]
# only use ubuntu-22.04 for llvm 16 and higher
include:
- os: ubuntu-20.04
# only use ubuntu-22.04 for llvm 16 and higher
- os: ubuntu-22.04
llvm-version: ["16.0", "16-0"]
- os: ubuntu-22.04
llvm-version: ["17.0", "17-0"]
steps:
- name: Checkout Repo
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Install LLVM and Clang
uses: KyleMayes/install-llvm-action@v1
with:
version: ${{ matrix.llvm-version[0] }}
- name: llvm-config
run: llvm-config --version --bindir --libdir
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable
- name: Build
run: cargo build --release --features llvm${{ matrix.llvm-version[1] }} --verbose
- name: Run tests
Expand All @@ -67,19 +69,19 @@ jobs:
needs: [typos, tests]
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
steps:
- uses: actions/checkout@v3
- uses: KyleMayes/install-llvm-action@v1
with:
version: ${{ env.DOC_LLVM_VERSION }}
- name: Install Rust Nightly
run: rustup toolchain install nightly
- name: Build Documentation
run: cargo +nightly doc --features ${{ env.DOC_LLVM_FEATURE }},nightly --verbose
- name: Doc Index Page Redirection
run: echo '<meta http-equiv="refresh" content="1; url=inkwell/index.html">' > ${{ env.DOC_PATH }}/index.html
- name: Deploy Documentation
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ${{ env.DOC_PATH }}
force_orphan: true
- uses: actions/checkout@v4
- uses: KyleMayes/install-llvm-action@v1
with:
version: ${{ env.DOC_LLVM_VERSION }}
- name: Install Rust Nightly
uses: dtolnay/rust-toolchain@nightly
- name: Build Documentation
run: cargo +nightly doc --features ${{ env.DOC_LLVM_FEATURE }},nightly --verbose
- name: Doc Index Page Redirection
run: echo '<meta http-equiv="refresh" content="1; url=inkwell/index.html">' > ${{ env.DOC_PATH }}/index.html
- name: Deploy Documentation
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ${{ env.DOC_PATH }}
force_orphan: true
11 changes: 8 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ edition = "2021"

[features]
default = ["target-all"]

# Please update internal_macros::FEATURE_VERSIONS when adding a new LLVM version
llvm4-0 = ["llvm-sys-40"]
llvm5-0 = ["llvm-sys-50"]
Expand All @@ -29,6 +30,7 @@ llvm15-0 = ["llvm-sys-150"]
llvm16-0 = ["llvm-sys-160"]
llvm17-0 = ["llvm-sys-170"]
llvm18-0 = ["llvm-sys-180"]

# Don't link against LLVM libraries. This is useful if another dependency is
# installing LLVM. See llvm-sys for more details. We can't enable a single
# `no-llvm-linking` feature across the board of llvm versions, as it'll cause
Expand Down Expand Up @@ -133,9 +135,8 @@ experimental = ["static-alloc"]
nightly = ["inkwell_internals/nightly"]

[dependencies]
either = "1.5"
inkwell_internals = { path = "./internal_macros", version = "0.9.0" }
libc = "0.2"

llvm-sys-40 = { package = "llvm-sys", version = "40.4", optional = true }
llvm-sys-50 = { package = "llvm-sys", version = "50.4", optional = true }
llvm-sys-60 = { package = "llvm-sys", version = "60.6", optional = true }
Expand All @@ -151,9 +152,13 @@ llvm-sys-150 = { package = "llvm-sys", version = "150.0.3", optional = true }
llvm-sys-160 = { package = "llvm-sys", version = "160.1.0", optional = true }
llvm-sys-170 = { package = "llvm-sys", version = "170.0.1", optional = true }
llvm-sys-180 = { package = "llvm-sys", version = "180.0.0", optional = true }

either = "1.5"
libc = "0.2"
once_cell = "1.16"
static-alloc = { version = "0.2", optional = true }
thiserror = "1.0.48"

static-alloc = { version = "0.2", optional = true }
serde = { version = "1.0", default-features = false, features = ["derive"], optional = true }

[dev-dependencies]
Expand Down
4 changes: 1 addition & 3 deletions examples/kaleidoscope/implementation_typed_pointers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,10 @@ pub struct LexError {
}

impl LexError {
#[allow(unused)]
pub fn new(msg: &'static str) -> LexError {
LexError { error: msg, index: 0 }
}

#[allow(unused)]
pub fn with_index(msg: &'static str, index: usize) -> LexError {
LexError { error: msg, index }
}
Expand Down Expand Up @@ -884,7 +882,7 @@ impl<'a, 'ctx> Compiler<'a, 'ctx> {
} => {
let mut old_bindings = Vec::new();

for &(ref var_name, ref initializer) in variables {
for (var_name, initializer) in variables {
let var_name = var_name.as_str();

let initial_val = match *initializer {
Expand Down
3 changes: 1 addition & 2 deletions examples/kaleidoscope/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ use inkwell::{
use inkwell_internals::llvm_versions;

mod implementation_typed_pointers;

use crate::implementation_typed_pointers::*;
pub use implementation_typed_pointers::*;

// ======================================================================================
// PROGRAM ==============================================================================
Expand Down
8 changes: 2 additions & 6 deletions src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,14 +369,10 @@ impl AttributeLoc {
match self {
AttributeLoc::Return => 0,
AttributeLoc::Param(index) => {
assert!(
index <= u32::max_value() - 2,
"Param index must be <= u32::max_value() - 2"
);

assert!(index <= u32::MAX - 2, "Param index must be <= u32::MAX - 2");
index + 1
},
AttributeLoc::Function => u32::max_value(),
AttributeLoc::Function => u32::MAX,
}
}
}
8 changes: 4 additions & 4 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ impl<'ctx> Builder<'ctx> {
///
/// builder.position_at_end(basic_block);
///
/// let pi = f32_type.const_float(::std::f64::consts::PI);
/// let pi = f32_type.const_float(std::f64::consts::PI);
///
/// builder.build_return(Some(&pi)).unwrap();
///
Expand Down Expand Up @@ -542,7 +542,7 @@ impl<'ctx> Builder<'ctx> {
///
/// builder.position_at_end(basic_block);
///
/// let pi = f32_type.const_float(::std::f64::consts::PI);
/// let pi = f32_type.const_float(std::f64::consts::PI);
///
/// builder.build_return(Some(&pi)).unwrap();
///
Expand Down Expand Up @@ -900,7 +900,7 @@ impl<'ctx> Builder<'ctx> {
///
/// builder.position_at_end(basic_block);
///
/// let pi = f32_type.const_float(::std::f64::consts::PI);
/// let pi = f32_type.const_float(std::f64::consts::PI);
///
/// builder.build_return(Some(&pi)).unwrap();
///
Expand Down Expand Up @@ -3390,7 +3390,7 @@ impl<'ctx> Builder<'ctx> {
feature = "llvm17-0",
feature = "llvm18-0"
)))]
if ptr.get_type().get_element_type().to_basic_type_enum() != cmp.get_type() {
if ptr.get_type().get_element_type().as_basic_type_enum() != cmp.get_type() {
return Err(BuilderError::PointeeTypeMismatch(
"The pointer does not point to an element of the value type.",
));
Expand Down
9 changes: 6 additions & 3 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ use llvm_sys::core::{
LLVMCreateStringAttribute, LLVMDoubleTypeInContext, LLVMFP128TypeInContext, LLVMFloatTypeInContext,
LLVMGetGlobalContext, LLVMGetMDKindIDInContext, LLVMHalfTypeInContext, LLVMInsertBasicBlockInContext,
LLVMInt16TypeInContext, LLVMInt1TypeInContext, LLVMInt32TypeInContext, LLVMInt64TypeInContext,
LLVMInt8TypeInContext, LLVMIntTypeInContext, LLVMMDNodeInContext, LLVMMDStringInContext,
LLVMModuleCreateWithNameInContext, LLVMPPCFP128TypeInContext, LLVMStructCreateNamed, LLVMStructTypeInContext,
LLVMVoidTypeInContext, LLVMX86FP80TypeInContext,
LLVMInt8TypeInContext, LLVMIntTypeInContext, LLVMModuleCreateWithNameInContext, LLVMPPCFP128TypeInContext,
LLVMStructCreateNamed, LLVMStructTypeInContext, LLVMVoidTypeInContext, LLVMX86FP80TypeInContext,
};
#[allow(deprecated)]
use llvm_sys::core::{LLVMMDNodeInContext, LLVMMDStringInContext};
use llvm_sys::ir_reader::LLVMParseIRInContext;
use llvm_sys::prelude::{LLVMContextRef, LLVMDiagnosticInfoRef, LLVMTypeRef, LLVMValueRef};
use llvm_sys::target::{LLVMIntPtrTypeForASInContext, LLVMIntPtrTypeInContext};
Expand Down Expand Up @@ -328,6 +329,7 @@ impl ContextImpl {
}
}

#[allow(deprecated)]
fn metadata_node<'ctx>(&self, values: &[BasicMetadataValueEnum<'ctx>]) -> MetadataValue<'ctx> {
let mut tuple_values: Vec<LLVMValueRef> = values.iter().map(|val| val.as_value_ref()).collect();
unsafe {
Expand All @@ -339,6 +341,7 @@ impl ContextImpl {
}
}

#[allow(deprecated)]
fn metadata_string<'ctx>(&self, string: &str) -> MetadataValue<'ctx> {
let c_string = to_c_str(string);

Expand Down
1 change: 1 addition & 0 deletions src/debug_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ impl<'ctx> DIScope<'ctx> {
/// Specific scopes (i.e. `DILexicalBlock`) can be turned into a `DIScope` with the
/// `AsDIScope::as_debug_info_scope` trait method.
pub trait AsDIScope<'ctx> {
#[allow(clippy::wrong_self_convention)]
fn as_debug_info_scope(self) -> DIScope<'ctx>;
}

Expand Down
4 changes: 2 additions & 2 deletions src/execution_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ impl<'ctx> ExecutionEngine<'ctx> {
let cstring_args: Vec<_> = args.iter().map(|&arg| to_c_str(arg)).collect();
let raw_args: Vec<*const _> = cstring_args.iter().map(|arg| arg.as_ptr()).collect();

let environment_variables = vec![]; // TODO: Support envp. Likely needs to be null terminated
let environment_variables = []; // TODO: Support envp. Likely needs to be null terminated

LLVMRunFunctionAsMain(
self.execution_engine_inner(),
Expand Down Expand Up @@ -475,7 +475,7 @@ impl Deref for ExecEngineInner<'_> {
type Target = LLVMExecutionEngineRef;

fn deref(&self) -> &Self::Target {
&*self.0
&self.0
}
}

Expand Down
9 changes: 2 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//! * Most functions which take a string slice as input may possibly panic in the unlikely event that a c style string cannot be created based on it. (IE if your slice already has a null byte in it)

#![deny(missing_debug_implementations)]
#![allow(clippy::missing_safety_doc, clippy::too_many_arguments, clippy::result_unit_err)]
#![cfg_attr(feature = "nightly", feature(doc_cfg))]

#[macro_use]
Expand Down Expand Up @@ -147,15 +148,9 @@ assert_unique_used_features! {
///
/// # Remarks
/// See also: https://llvm.org/doxygen/NVPTXBaseInfo_8h_source.html
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[derive(Debug, PartialEq, Eq, Copy, Clone, Default)]
pub struct AddressSpace(u32);

impl Default for AddressSpace {
fn default() -> Self {
AddressSpace(0)
}
}

impl From<u16> for AddressSpace {
fn from(val: u16) -> Self {
AddressSpace(val as u32)
Expand Down
2 changes: 2 additions & 0 deletions src/memory_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use llvm_sys::core::{
LLVMCreateMemoryBufferWithMemoryRangeCopy, LLVMCreateMemoryBufferWithSTDIN, LLVMDisposeMemoryBuffer,
LLVMGetBufferSize, LLVMGetBufferStart,
};
#[allow(deprecated)]
use llvm_sys::object::LLVMCreateObjectFile;
use llvm_sys::prelude::LLVMMemoryBufferRef;

Expand Down Expand Up @@ -123,6 +124,7 @@ impl MemoryBuffer {
/// Convert this `MemoryBuffer` into an `ObjectFile`. LLVM does not currently
/// provide any way to determine the cause of error if conversion fails.
pub fn create_object_file(self) -> Result<ObjectFile, ()> {
#[allow(deprecated)]
let object_file = unsafe { LLVMCreateObjectFile(self.memory_buffer) };

forget(self);
Expand Down
3 changes: 2 additions & 1 deletion src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,7 @@ impl<'ctx> Module<'ctx> {
}

/// Prints the content of the `Module` to a `String`.
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
self.print_to_string().to_string()
}
Expand Down Expand Up @@ -1507,7 +1508,7 @@ impl<'ctx> Module<'ctx> {
machine.target_machine,
options.options_ref,
);
if error == std::ptr::null_mut() {
if error.is_null() {
Ok(())
} else {
let message = LLVMGetErrorMessage(error);
Expand Down
2 changes: 2 additions & 0 deletions src/object_file.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(deprecated)]

use llvm_sys::object::{
LLVMDisposeObjectFile, LLVMDisposeRelocationIterator, LLVMDisposeSectionIterator, LLVMDisposeSymbolIterator,
LLVMGetRelocationOffset, LLVMGetRelocationSymbol, LLVMGetRelocationType, LLVMGetRelocationTypeName,
Expand Down
13 changes: 6 additions & 7 deletions src/support/error_handling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use llvm_sys::LLVMDiagnosticSeverity;
// wrap the provided function input ptr into a &CStr somehow
// TODOC: Can be used like this:
// extern "C" fn print_before_exit(msg: *const i8) {
// let c_str = unsafe { ::std::ffi::CStr::from_ptr(msg) };
// let c_str = unsafe { std::ffi::CStr::from_ptr(msg) };
//
// eprintln!("LLVM fatally errored: {:?}", c_str);
// }
Expand Down Expand Up @@ -42,12 +42,11 @@ impl DiagnosticInfo {
}

pub(crate) fn severity_is_error(&self) -> bool {
unsafe {
match LLVMGetDiagInfoSeverity(self.diagnostic_info) {
LLVMDiagnosticSeverity::LLVMDSError => true,
_ => false,
}
}
self.severity() == LLVMDiagnosticSeverity::LLVMDSError
}

fn severity(&self) -> LLVMDiagnosticSeverity {
unsafe { LLVMGetDiagInfoSeverity(self.diagnostic_info) }
}
}

Expand Down
7 changes: 4 additions & 3 deletions src/support/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ impl LLVMString {
/// as much as possible to save memory since it is allocated by
/// LLVM. It's essentially a `CString` with a custom LLVM
/// deallocator
#[allow(clippy::inherent_to_string_shadow_display)]
pub fn to_string(&self) -> String {
(*self).to_string_lossy().into_owned()
}
Expand Down Expand Up @@ -135,7 +136,7 @@ pub fn get_llvm_version() -> (u32, u32, u32) {

unsafe { LLVMGetVersion(&mut major, &mut minor, &mut patch) };

return (major, minor, patch);
(major, minor, patch)
}

/// Possible errors that can occur when loading a library
Expand Down Expand Up @@ -186,7 +187,7 @@ pub fn search_for_address_of_symbol(symbol: &str) -> Option<usize> {
if address.is_null() {
return None;
}
return Some(address as usize);
Some(address as usize)
}

#[test]
Expand All @@ -213,7 +214,7 @@ pub fn enable_llvm_pretty_stack_trace() {
/// A) Finds a terminating null byte in the Rust string and can reference it directly like a C string.
///
/// B) Finds no null byte and allocates a new C string based on the input Rust string.
pub(crate) fn to_c_str<'s>(mut s: &'s str) -> Cow<'s, CStr> {
pub(crate) fn to_c_str(mut s: &str) -> Cow<'_, CStr> {
if s.is_empty() {
s = "\0";
}
Expand Down
Loading

0 comments on commit 7684346

Please sign in to comment.