Skip to content

clippy enum_glob_use#8121

Open
ShaharNaveh wants to merge 3 commits into
RustPython:mainfrom
ShaharNaveh:clippy-rules-1
Open

clippy enum_glob_use#8121
ShaharNaveh wants to merge 3 commits into
RustPython:mainfrom
ShaharNaveh:clippy-rules-1

Conversation

@ShaharNaveh

@ShaharNaveh ShaharNaveh commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Summary

Summary by CodeRabbit

Release Notes

  • Refactor
    • Standardized internal enum matching and error/display formatting to use explicit, fully-qualified variant references across the codebase, keeping behavior the same.
  • Chores
    • Added a new Clippy lint rule (enum_glob_use) to the workspace lint configuration to encourage clearer enum usage.
  • Tests
    • No user-visible changes reported.

@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds enum_glob_use = "warn" to the workspace Clippy lint configuration in Cargo.toml, then resolves all resulting warnings by replacing glob-imported enum variant patterns (use SomeEnum::*) with explicitly qualified SomeEnum::Variant paths across 19 files spanning the compiler, VM, stdlib, and derive-impl crates. No logic or public API changes.

Changes

enum_glob_use Clippy lint enforcement

Layer / File(s) Summary
Lint rule added to workspace config
Cargo.toml
Adds enum_glob_use = "warn" to [workspace.lints.clippy], enabling the lint that drives all downstream fixes.
Compiler-core enum qualification
crates/compiler-core/src/bytecode.rs, crates/compiler-core/src/marshal.rs
borrow_constant, PartialEq, Hash, and BorrowedConstant::to_owned in bytecode.rs switch from glob-imported names to explicit Self::.../ConstantData::... paths. Type::try_from in marshal.rs replaces use Type::* with Self::... arms.
Codegen enum qualification
crates/codegen/src/compile.rs, crates/codegen/src/symboltable.rs
compile_addcompare uses explicit ComparisonOperator::... paths. scan_pattern switches to ast::Pattern::... qualification and gains explicit handling for MatchClass, MatchStar, MatchAs, and MatchOr.
Common crate enum qualification
crates/common/src/cformat.rs, crates/common/src/str.rs
CFormatErrorType, CFloatType, CNumberType, and StrKind variant matches are fully qualified across Display, case(), format_number(), parse_format_type(), and BitOr.
derive-impl enum qualification
crates/derive-impl/src/pyclass.rs, crates/derive-impl/src/util.rs
AttrName::... variants qualified in impl_item_new. syn::Item::... and FnArg::... patterns qualified in pyclass_ident_and_attrs, pyexception_ident_and_attrs, infer_native_call_flags, and func_sig. spanned::Spanned added to imports.
stdlib enum qualification
crates/stdlib/src/array.rs, crates/stdlib/src/binascii.rs, crates/stdlib/src/unicodedata.rs
MachineFormatCode::..., DecodeError::..., and NormalizeForm::... variants qualified in their respective match sites.
VM enum qualification
crates/vm/src/buffer.rs, crates/vm/src/builtins/dict.rs, crates/vm/src/builtins/float.rs, crates/vm/src/codecs.rs, crates/vm/src/protocol/callable.rs, crates/vm/src/stdlib/_imp.rs, crates/vm/src/stdlib/marshal.rs, crates/vm/src/stdlib/winsound.rs
FormatType, PyArithmeticValue, StandardError, TraceEvent, FrozenError, DumpableValue, and PlaySoundError variants are all qualified explicitly; marshal.rs also imports DumpableValue directly; winsound.rs imports PlaySoundError and refactors map_play_err as a generic function.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • RustPython/RustPython#7764: Both PRs touch the workspace Clippy lint configuration in Cargo.toml, with the retrieved PR enabling broader pedantic lints.
  • RustPython/RustPython#7875: Both PRs modify the Clippy workspace lint configuration in Cargo.toml, with the retrieved PR restructuring the nursery lints.

Suggested reviewers

  • youknowone

Poem

🐇 A rabbit hops through the code with care,
Glob imports scattered everywhere!
Now each variant stands tall and bright,
EnumType::Variant — a glorious sight.
No more wildcard shadows to confuse,
Just explicit paths the compiler can use! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main change: adding the clippy enum_glob_use lint rule to Cargo.toml and systematically removing glob enum imports throughout the codebase in favor of explicit variant paths.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
crates/codegen/src/compile.rs (1)

7009-7046: ⚡ Quick win

Extract the operator mapping to eliminate duplication. Per the coding guidelines ("When branches differ only in a value but share common logic, extract the differing value first"), the six match arms are identical except for the ComparisonOperator variant and the input pattern. Extract the mapping into a single inner match, then emit once.

♻️ Proposed refactor to reduce duplication
 fn compile_addcompare(&mut self, op: &ast::CmpOp) {
-    match op {
-        ast::CmpOp::Eq => emit!(
-            self,
-            Instruction::CompareOp {
-                opname: ComparisonOperator::Equal
-            }
-        ),
-        ast::CmpOp::NotEq => emit!(
-            self,
-            Instruction::CompareOp {
-                opname: ComparisonOperator::NotEqual
-            }
-        ),
-        ast::CmpOp::Lt => emit!(
-            self,
-            Instruction::CompareOp {
-                opname: ComparisonOperator::Less
-            }
-        ),
-        ast::CmpOp::LtE => emit!(
-            self,
-            Instruction::CompareOp {
-                opname: ComparisonOperator::LessOrEqual
-            }
-        ),
-        ast::CmpOp::Gt => emit!(
-            self,
-            Instruction::CompareOp {
-                opname: ComparisonOperator::Greater
-            }
-        ),
-        ast::CmpOp::GtE => {
-            emit!(
-                self,
-                Instruction::CompareOp {
-                    opname: ComparisonOperator::GreaterOrEqual
-                }
-            )
-        }
-    }
+    let opname = match op {
+        ast::CmpOp::Eq => ComparisonOperator::Equal,
+        ast::CmpOp::NotEq => ComparisonOperator::NotEqual,
+        ast::CmpOp::Lt => ComparisonOperator::Less,
+        ast::CmpOp::LtE => ComparisonOperator::LessOrEqual,
+        ast::CmpOp::Gt => ComparisonOperator::Greater,
+        ast::CmpOp::GtE => ComparisonOperator::GreaterOrEqual,
+    };
+    emit!(
+        self,
+        Instruction::CompareOp { opname }
+    );
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/codegen/src/compile.rs` around lines 7009 - 7046, The match arms for
ast::CmpOp variants (Eq, NotEq, Lt, LtE, Gt, GtE) contain duplicated logic with
only the ComparisonOperator variant differing. Extract the operator mapping into
an inner match statement that converts the ast::CmpOp to its corresponding
ComparisonOperator, then emit the CompareOp instruction once using the result of
that mapping, eliminating the six repetitive emit! calls.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@crates/codegen/src/compile.rs`:
- Around line 7009-7046: The match arms for ast::CmpOp variants (Eq, NotEq, Lt,
LtE, Gt, GtE) contain duplicated logic with only the ComparisonOperator variant
differing. Extract the operator mapping into an inner match statement that
converts the ast::CmpOp to its corresponding ComparisonOperator, then emit the
CompareOp instruction once using the result of that mapping, eliminating the six
repetitive emit! calls.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 4094b456-50fe-48e6-ada7-a78eada8aa48

📥 Commits

Reviewing files that changed from the base of the PR and between 808b071 and 810c902.

📒 Files selected for processing (19)
  • Cargo.toml
  • crates/codegen/src/compile.rs
  • crates/codegen/src/symboltable.rs
  • crates/common/src/cformat.rs
  • crates/common/src/str.rs
  • crates/compiler-core/src/bytecode.rs
  • crates/compiler-core/src/marshal.rs
  • crates/derive-impl/src/pyclass.rs
  • crates/derive-impl/src/util.rs
  • crates/stdlib/src/array.rs
  • crates/stdlib/src/binascii.rs
  • crates/stdlib/src/unicodedata.rs
  • crates/vm/src/buffer.rs
  • crates/vm/src/builtins/dict.rs
  • crates/vm/src/builtins/float.rs
  • crates/vm/src/codecs.rs
  • crates/vm/src/protocol/callable.rs
  • crates/vm/src/stdlib/_imp.rs
  • crates/vm/src/stdlib/marshal.rs

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
crates/vm/src/stdlib/winsound.rs (1)

71-83: ⚡ Quick win

Consider simplifying the generic signature to impl Trait.

The generic type parameter F is not necessary here. The function could use the simpler and more idiomatic impl FnOnce(PlaySoundError) -> PyBaseExceptionRef + '_ return type, which would work equally well at all call sites (lines 91, 99, 154) while reducing complexity.

♻️ Proposed simplification
-fn map_play_err<F>(vm: &VirtualMachine) -> F
-where
-    F: FnOnce(PlaySoundError) -> PyBaseExceptionRef + '_,
-{
+fn map_play_err(vm: &VirtualMachine) -> impl FnOnce(PlaySoundError) -> PyBaseExceptionRef + '_ {
     |err| match err {
         PlaySoundError::MemoryAsyncRejected => {
             vm.new_runtime_error("Cannot play asynchronously from memory")
         }
         PlaySoundError::MemoryFlagWithoutBuffer | PlaySoundError::CallFailed => {
             vm.new_runtime_error("Failed to play sound")
         }
     }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/vm/src/stdlib/winsound.rs` around lines 71 - 83, Simplify the generic
signature of the map_play_err function by removing the explicit generic type
parameter F and using impl Trait syntax instead. Change the return type to use
impl FnOnce(PlaySoundError) -> PyBaseExceptionRef + '_ directly, which is more
idiomatic and achieves the same result at all call sites while reducing
unnecessary complexity.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@crates/vm/src/stdlib/winsound.rs`:
- Around line 71-83: Simplify the generic signature of the map_play_err function
by removing the explicit generic type parameter F and using impl Trait syntax
instead. Change the return type to use impl FnOnce(PlaySoundError) ->
PyBaseExceptionRef + '_ directly, which is more idiomatic and achieves the same
result at all call sites while reducing unnecessary complexity.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: bcf065b2-8e98-448f-acb5-86c4c4104562

📥 Commits

Reviewing files that changed from the base of the PR and between 810c902 and b840410.

📒 Files selected for processing (1)
  • crates/vm/src/stdlib/winsound.rs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant