Skip to content

Commit 1aa0e99

Browse files
authored
style(clippy): apply pedantic rules
Refs: #418
1 parent 201990e commit 1aa0e99

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+1312
-582
lines changed

.github/workflows/build.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ jobs:
6868
- name: Run rustfmt
6969
run: cargo fmt --all -- --check
7070
- name: Run clippy
71-
run: cargo clippy --all -- -D warnings
71+
run: cargo clippy --workspace --all-targets --all-features -- -W clippy::pedantic -D warnings
7272
# Docs
7373
- name: Run rustdoc
7474
run: cargo rustdoc -- -D warnings

build.rs

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
//! This script is responsible for generating the bindings to the PHP Zend API.
33
//! It also checks the PHP version for compatibility with ext-php-rs and sets
44
//! configuration flags accordingly.
5+
#![allow(clippy::inconsistent_digit_grouping)]
56
#[cfg_attr(windows, path = "windows_build.rs")]
67
#[cfg_attr(not(windows), path = "unix_build.rs")]
78
mod impl_;
@@ -19,21 +20,25 @@ use anyhow::{anyhow, bail, Context, Result};
1920
use bindgen::RustTarget;
2021
use impl_::Provider;
2122

22-
const MIN_PHP_API_VER: u32 = 20200930;
23-
const MAX_PHP_API_VER: u32 = 20240924;
23+
const MIN_PHP_API_VER: u32 = 2020_09_30;
24+
const MAX_PHP_API_VER: u32 = 2024_09_24;
2425

2526
/// Provides information about the PHP installation.
2627
pub trait PHPProvider<'a>: Sized {
2728
/// Create a new PHP provider.
29+
#[allow(clippy::missing_errors_doc)]
2830
fn new(info: &'a PHPInfo) -> Result<Self>;
2931

3032
/// Retrieve a list of absolute include paths.
33+
#[allow(clippy::missing_errors_doc)]
3134
fn get_includes(&self) -> Result<Vec<PathBuf>>;
3235

3336
/// Retrieve a list of macro definitions to pass to the compiler.
37+
#[allow(clippy::missing_errors_doc)]
3438
fn get_defines(&self) -> Result<Vec<(&'static str, &'static str)>>;
3539

3640
/// Writes the bindings to a file.
41+
#[allow(clippy::missing_errors_doc)]
3742
fn write_bindings(&self, bindings: String, writer: &mut impl Write) -> Result<()> {
3843
for line in bindings.lines() {
3944
writeln!(writer, "{line}")?;
@@ -42,12 +47,14 @@ pub trait PHPProvider<'a>: Sized {
4247
}
4348

4449
/// Prints any extra link arguments.
50+
#[allow(clippy::missing_errors_doc)]
4551
fn print_extra_link_args(&self) -> Result<()> {
4652
Ok(())
4753
}
4854
}
4955

5056
/// Finds the location of an executable `name`.
57+
#[must_use]
5158
pub fn find_executable(name: &str) -> Option<PathBuf> {
5259
const WHICH: &str = if cfg!(windows) { "where" } else { "which" };
5360
let cmd = Command::new(WHICH).arg(name).output().ok()?;
@@ -59,7 +66,7 @@ pub fn find_executable(name: &str) -> Option<PathBuf> {
5966
}
6067
}
6168

62-
/// Returns an environment variable's value as a PathBuf
69+
/// Returns an environment variable's value as a `PathBuf`
6370
pub fn path_from_env(key: &str) -> Option<PathBuf> {
6471
std::env::var_os(key).map(PathBuf::from)
6572
}
@@ -85,6 +92,9 @@ pub struct PHPInfo(String);
8592

8693
impl PHPInfo {
8794
/// Get the PHP info.
95+
///
96+
/// # Errors
97+
/// - `php -i` command failed to execute successfully
8898
pub fn get(php: &Path) -> Result<Self> {
8999
let cmd = Command::new(php)
90100
.arg("-i")
@@ -108,6 +118,9 @@ impl PHPInfo {
108118
}
109119

110120
/// Checks if thread safety is enabled.
121+
///
122+
/// # Errors
123+
/// - `PHPInfo` does not contain thread satety information
111124
pub fn thread_safety(&self) -> Result<bool> {
112125
Ok(self
113126
.get_key("Thread Safety")
@@ -116,6 +129,9 @@ impl PHPInfo {
116129
}
117130

118131
/// Checks if PHP was built with debug.
132+
///
133+
/// # Errors
134+
/// - `PHPInfo` does not contain debug build information
119135
pub fn debug(&self) -> Result<bool> {
120136
Ok(self
121137
.get_key("Debug Build")
@@ -124,12 +140,18 @@ impl PHPInfo {
124140
}
125141

126142
/// Get the php version.
143+
///
144+
/// # Errors
145+
/// - `PHPInfo` does not contain version number
127146
pub fn version(&self) -> Result<&str> {
128147
self.get_key("PHP Version")
129148
.context("Failed to get PHP version")
130149
}
131150

132151
/// Get the zend version.
152+
///
153+
/// # Errors
154+
/// - `PHPInfo` does not contain php api version
133155
pub fn zend_version(&self) -> Result<u32> {
134156
self.get_key("PHP API")
135157
.context("Failed to get Zend version")
@@ -202,7 +224,7 @@ fn generate_bindings(defines: &[(&str, &str)], includes: &[PathBuf]) -> Result<S
202224
.layout_tests(env::var("EXT_PHP_RS_TEST").is_ok())
203225
.rust_target(RustTarget::Nightly);
204226

205-
for binding in ALLOWED_BINDINGS.iter() {
227+
for binding in ALLOWED_BINDINGS {
206228
bindgen = bindgen
207229
.allowlist_function(binding)
208230
.allowlist_type(binding)
@@ -230,6 +252,11 @@ fn generate_bindings(defines: &[(&str, &str)], includes: &[PathBuf]) -> Result<S
230252
/// Checks the PHP Zend API version for compatibility with ext-php-rs, setting
231253
/// any configuration flags required.
232254
fn check_php_version(info: &PHPInfo) -> Result<()> {
255+
const PHP_81_API_VER: u32 = 2021_09_02;
256+
const PHP_82_API_VER: u32 = 2022_08_29;
257+
const PHP_83_API_VER: u32 = 2023_08_31;
258+
const PHP_84_API_VER: u32 = 2024_09_24;
259+
233260
let version = info.zend_version()?;
234261

235262
if !(MIN_PHP_API_VER..=MAX_PHP_API_VER).contains(&version) {
@@ -245,14 +272,6 @@ fn check_php_version(info: &PHPInfo) -> Result<()> {
245272
//
246273
// The PHP version cfg flags should also stack - if you compile on PHP 8.2 you
247274
// should get both the `php81` and `php82` flags.
248-
const PHP_81_API_VER: u32 = 20210902;
249-
250-
const PHP_82_API_VER: u32 = 20220829;
251-
252-
const PHP_83_API_VER: u32 = 20230831;
253-
254-
const PHP_84_API_VER: u32 = 20240924;
255-
256275
println!(
257276
"cargo::rustc-check-cfg=cfg(php80, php81, php82, php83, php84, php_zts, php_debug, docs)"
258277
);

crates/cli/build.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,5 @@
44
//! time.
55
66
fn main() {
7-
println!("cargo:rustc-link-arg-bins=-rdynamic")
7+
println!("cargo:rustc-link-arg-bins=-rdynamic");
88
}

crates/cli/src/lib.rs

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,17 @@ macro_rules! stub_symbols {
3636
pub type CrateResult = AResult<()>;
3737

3838
/// Runs the CLI application. Returns nothing in a result on success.
39+
///
40+
/// # Errors
41+
///
42+
/// Returns an error if the application fails to run.
3943
pub fn run() -> CrateResult {
4044
let mut args: Vec<_> = std::env::args().collect();
4145

4246
// When called as a cargo subcommand, the second argument given will be the
4347
// subcommand, in this case `php`. We don't want this so we remove from args and
4448
// pass it to clap.
45-
if args.get(1).map(|nth| nth == "php").unwrap_or(false) {
49+
if args.get(1).is_some_and(|nth| nth == "php") {
4650
args.remove(1);
4751
}
4852

@@ -91,6 +95,7 @@ struct Install {
9195
/// Changes the path that the extension is copied to. This will not
9296
/// activate the extension unless `ini_path` is also passed.
9397
#[arg(long)]
98+
#[allow(clippy::struct_field_names)]
9499
install_dir: Option<PathBuf>,
95100
/// Path to the `php.ini` file to update with the new extension.
96101
#[arg(long)]
@@ -166,7 +171,7 @@ impl Args {
166171

167172
impl Install {
168173
pub fn handle(self) -> CrateResult {
169-
let artifact = find_ext(&self.manifest)?;
174+
let artifact = find_ext(self.manifest.as_ref())?;
170175
let ext_path = build_ext(&artifact, self.release)?;
171176

172177
let (mut ext_dir, mut php_ini) = if let Some(install_dir) = self.install_dir {
@@ -213,11 +218,11 @@ impl Install {
213218
let mut new_lines = vec![];
214219
for line in BufReader::new(&file).lines() {
215220
let line = line.with_context(|| "Failed to read line from `php.ini`")?;
216-
if !line.contains(&ext_line) {
217-
new_lines.push(line);
218-
} else {
221+
if line.contains(&ext_line) {
219222
bail!("Extension already enabled.");
220223
}
224+
225+
new_lines.push(line);
221226
}
222227

223228
// Comment out extension if user specifies disable flag
@@ -255,10 +260,14 @@ fn get_ext_dir() -> AResult<PathBuf> {
255260
"Extension directory returned from PHP is not a valid directory: {:?}",
256261
ext_dir
257262
);
258-
} else {
259-
std::fs::create_dir(&ext_dir)
260-
.with_context(|| format!("Failed to create extension directory at {ext_dir:?}"))?;
261263
}
264+
265+
std::fs::create_dir(&ext_dir).with_context(|| {
266+
format!(
267+
"Failed to create extension directory at {}",
268+
ext_dir.display()
269+
)
270+
})?;
262271
}
263272
Ok(ext_dir)
264273
}
@@ -288,7 +297,7 @@ impl Remove {
288297
pub fn handle(self) -> CrateResult {
289298
use std::env::consts;
290299

291-
let artifact = find_ext(&self.manifest)?;
300+
let artifact = find_ext(self.manifest.as_ref())?;
292301

293302
let (mut ext_path, mut php_ini) = if let Some(install_dir) = self.install_dir {
294303
(install_dir, None)
@@ -361,7 +370,7 @@ impl Stubs {
361370
let ext_path = if let Some(ext_path) = self.ext {
362371
ext_path
363372
} else {
364-
let target = find_ext(&self.manifest)?;
373+
let target = find_ext(self.manifest.as_ref())?;
365374
build_ext(&target, false)?.into()
366375
};
367376

@@ -410,7 +419,7 @@ impl Stubs {
410419
}
411420

412421
/// Attempts to find an extension in the target directory.
413-
fn find_ext(manifest: &Option<PathBuf>) -> AResult<cargo_metadata::Target> {
422+
fn find_ext(manifest: Option<&PathBuf>) -> AResult<cargo_metadata::Target> {
414423
// TODO(david): Look for cargo manifest option or env
415424
let mut cmd = cargo_metadata::MetadataCommand::new();
416425
if let Some(manifest) = manifest {
@@ -493,13 +502,13 @@ fn build_ext(target: &Target, release: bool) -> AResult<Utf8PathBuf> {
493502
}
494503
}
495504
cargo_metadata::Message::BuildFinished(b) => {
496-
if !b.success {
497-
bail!("Compilation failed, cancelling installation.")
498-
} else {
505+
if b.success {
499506
break;
500507
}
508+
509+
bail!("Compilation failed, cancelling installation.")
501510
}
502-
_ => continue,
511+
_ => {}
503512
}
504513
}
505514

crates/macros/src/extern_.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use proc_macro2::TokenStream;
22
use quote::quote;
33
use syn::{
4-
punctuated::Punctuated, spanned::Spanned as _, ForeignItemFn, ItemForeignMod, ReturnType,
5-
Signature, Token,
4+
punctuated::Punctuated, spanned::Spanned as _, token::Unsafe, ForeignItemFn, ItemForeignMod,
5+
ReturnType, Signature, Token,
66
};
77

88
use crate::prelude::*;
@@ -23,7 +23,7 @@ fn parse_function(mut func: ForeignItemFn) -> Result<TokenStream> {
2323
let ForeignItemFn {
2424
attrs, vis, sig, ..
2525
} = &mut func;
26-
sig.unsafety = Some(Default::default()); // Function must be unsafe.
26+
sig.unsafety = Some(Unsafe::default()); // Function must be unsafe.
2727

2828
let Signature { ident, .. } = &sig;
2929

@@ -36,13 +36,13 @@ fn parse_function(mut func: ForeignItemFn) -> Result<TokenStream> {
3636
let pat = &arg.pat;
3737
Some(quote! { &#pat })
3838
}
39-
_ => None,
39+
syn::FnArg::Receiver(_) => None,
4040
})
4141
.collect::<Option<Punctuated<_, Token![,]>>>()
4242
.ok_or_else(|| {
4343
err!(sig.span() => "`self` parameters are not permitted inside `#[php_extern]` blocks.")
4444
})?;
45-
let ret = build_return(&name, &sig.output, params);
45+
let ret = build_return(&name, &sig.output, &params);
4646

4747
Ok(quote! {
4848
#(#attrs)* #vis #sig {
@@ -60,7 +60,7 @@ fn parse_function(mut func: ForeignItemFn) -> Result<TokenStream> {
6060
fn build_return(
6161
name: &str,
6262
return_type: &ReturnType,
63-
params: Punctuated<TokenStream, Token![,]>,
63+
params: &Punctuated<TokenStream, Token![,]>,
6464
) -> TokenStream {
6565
match return_type {
6666
ReturnType::Default => quote! {

0 commit comments

Comments
 (0)