Skip to content

Fix manual unwrap or lint to respect msrv for unwrap or default() #14879

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions .cursor/rules/data-flow-patterns.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
description: Documents data flow patterns for static analysis and linting rules in Rust code.
globs: **/src/**/*.rs,**/clippy_lints/**/*.rs,**/clippy_config/**/*.rs
alwaysApply: false
---


# data-flow-patterns

The data flow in this linting system follows these core patterns:

1. Lint Registration Flow
- Lints are registered through `RegistrationGroups` in lib.rs
- Groups are organized by category (Correctness, Style, Complexity, etc.)
- Each lint registration contains metadata like name, description, level
- Registration maps to specific analysis implementations

2. Lint Analysis Flow
- Source code is parsed into AST/MIR representations
- Lint implementations analyze specific patterns in the code
- Results are collected into a centralized reporting system
- Early vs Late pass analysis controls when lints are applied

3. Configuration Processing Flow
- Configuration is loaded from clippy.toml and environment
- Rules are validated and normalized through conf.rs
- Configuration flows to individual lint implementations
- Default configurations are merged with user overrides

4. Data Model Validation Flow
- Type-based validation rules check compatibility
- Memory safety requirements are enforced through ownership analysis
- Reference validity is tracked across code paths
- Custom type constraints are applied based on lint requirements

5. Suggestion Generation Flow
- Issues detected by lints generate suggestion spans
- Suggestions include code replacements and rationale
- Multiple suggestions may be generated per issue
- Suggestions preserve original code formatting

Key Files:
- clippy_lints/src/lib.rs - Core registration system
- clippy_config/src/conf.rs - Configuration processing
- clippy_lints/src/declared_lints.rs - Lint definitions
- clippy_lints/src/non_copy_const.rs - Data validation

The system implements an extensible pipeline for static code analysis with strict separation between registration, analysis, and reporting phases.

$END$
50 changes: 50 additions & 0 deletions .cursor/rules/lint-analysis-algorithms.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
description: Specification for analyzing and documenting lint algorithms, rules and validations in Rust static analysis tools
globs: src/clippy_lints/**/*.rs,src/**/lint*.rs,src/**/rules/**/*.rs,src/**/check*.rs
alwaysApply: false
---


# lint-analysis-algorithms

The core business logic encompasses specialized static analysis algorithms for detecting code patterns and enforcing domain rules in Rust. Key components include:

1. Pattern Matching Analysis
- AST traversal for identifying specific code structures requiring linting
- Type analysis and validation during pattern matching
- Context tracking for multi-block pattern validation
- Template matching against known anti-patterns

2. Reference Safety Rules
- Borrow checker augmentation for reference analysis
- Lifetime validation for borrowed values
- Mutable reference access pattern checking
- Reference scoping and drop timing validation

3. Type System Integration
- Layout compatibility verification for transmutes
- Generic parameter substitution tracking
- Trait bound satisfaction checking
- Zero-sized type special case handling

4. Domain Rule Enforcement
- Documentation style and completeness validation
- API visibility and access pattern checks
- Naming convention verification
- Resource safety guarantees

5. Suggestion Generation
- Context-aware code transformation suggestions
- Macro expansion preservation in suggestions
- Comment and attribute retention during fixes
- Edition-specific code recommendations

The algorithms focus on static verification of Rust-specific safety requirements and coding conventions, with extensive customization points for project-specific rules.

Core file paths:
- clippy_lints/src/methods/*.rs
- clippy_lints/src/types/*.rs
- clippy_lints/src/matches/*.rs
- clippy_lints/src/attrs/*.rs

$END$
43 changes: 43 additions & 0 deletions .cursor/rules/lint-data-model.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
description: Core lint metadata models and data structures used for evaluating and tracking lint rules and their relationships with Rust's type system
globs: clippy_lints/src/**.rs,clippy_config/src/**.rs
alwaysApply: false
---


# lint-data-model

## Core Lint State Model
- Tracks lint metadata including name, description, level (deny/warn/allow)
- Maintains contextual relationships between lints and their diagnostics
- Special handling for edition-specific lint configurations
- Enforces lint deprecation policies through staged transitions

## Lint Category Hierarchies
- Implements layered categorization for lints:
- Style (code formatting/convention violations)
- Correctness (potential runtime errors)
- Complexity (code structure issues)
- Performance (inefficient patterns)
- Restriction (banned patterns/code constructs)
- Pedantic (best practice violations)
- Nursery (new/unstable lints)

## Configuration Management
- Handles configuration hierarchies and inheritance
- Implements context-aware configuration application based on file paths
- Manages per-crate and per-module lint configurations
- Supports nested configuration overrides with precedence rules

## Diagnostic Relationship Model
- Maps lints to compiler diagnostic codes
- Tracks diagnostic severities and suggested fixes
- Manages related diagnostic notes and explanations
- Handles diagnostic suppression chains

Key Files:
- clippy_config/src/conf.rs
- clippy_lints/src/lib.rs
- clippy_lints/src/declared_lints.rs

$END$
53 changes: 53 additions & 0 deletions .cursor/rules/type-validation-system.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
---
description: Specification for the type validation and safety system used in Clippy linting rules and checks.
globs: clippy_lints/**/*.rs,clippy_config/**/*.rs
alwaysApply: false
---


# type-validation-system

The type validation system comprises several key components implementing specialized safety and validation rules:

1. Cast Safety Validation:
- Validates numeric type conversions for potential data loss
- Enforces pointer safety rules during casting operations
- Contains domain rules for casting between collection types
- Handles specialized validation for floating point casts

2. Reference Type Safety:
- Validates proper handling of references vs raw pointers
- Implements borrowing pattern detection and safety rules
- Contains custom validation for self-referential structs
- Handles complex lifetime relationship validation

3. Collection Type Validation:
- Enforces collection type safety policies
- Validates element type compatibility in collections
- Implements specialized slice operation safety
- Contains custom validation for generic type parameters

4. Specialized Domain Rules:
- Custom validation for mutable reference patterns
- Zero-sized type handling and validation
- Orphan implementation checking
- Associated type relationship validation

Key implementations:
- clippy_lints/src/casts/*.rs: Core casting validation
- clippy_lints/src/types/*.rs: Type relationship checking
- clippy_lints/src/transmute/*.rs: Memory transmutation safety

The system enforces domain-specific type safety policies through static analysis, focusing on:
- Reference and pointer safety guarantees
- Collection type compatibility
- Memory layout validation
- Generic type parameter bounds

Notable validations include:
- Transmute operation safety
- Zero-cost abstraction validation
- Reference lifetime analysis
- Collection element type compatibility

$END$
64 changes: 64 additions & 0 deletions .cursorrules
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@

START SPECIFICATION:
---
description: This overview should be applied when analyzing Clippy's linting system components, particularly focusing on custom business rules, lint implementations, and domain-specific code analysis patterns.
globs: clippy_lints/src/**,clippy_config/src/**,clippy_dev/src/**
alwaysApply: false
---


# main-overview

## Development Guidelines

- Only modify code directly relevant to the specific request. Avoid changing unrelated functionality.
- Never replace code with placeholders like `# ... rest of the processing ...`. Always include complete code.
- Break problems into smaller steps. Think through each step separately before implementing.
- Always provide a complete PLAN with REASONING based on evidence from code and logs before making changes.
- Explain your OBSERVATIONS clearly, then provide REASONING to identify the exact issue. Add console logs when needed to gather more information.


Clippy implements a sophisticated static analysis system for Rust code through several key components:

1. Configuration Management (clippy_config/src/conf.rs)
- Enforces validation rules for linting configuration
- Implements custom documentation processing with code block preservation
- Controls field visibility and access patterns
- Validates naming conventions with configurable exceptions

2. Core Linting System (clippy_lints/src/lib.rs)
- Organizes lints into functional categories (Correctness, Style, Complexity, etc.)
- Implements two-phase lint checking:
- Early pass: Syntax-level validation
- Late pass: Semantic analysis
- Manages centralized lint explanations and configuration metadata

3. Code Pattern Analysis (clippy_lints/src/matches/mod.rs)
- Detects redundant match patterns and suggests simplifications
- Validates mutex safety in pattern matching
- Enforces pattern matching exhaustiveness
- Handles reference types and binding modes

4. Memory Safety Validation (clippy_lints/src/transmute/)
- Validates transmute operations between types
- Enforces pointer safety and alignment rules
- Detects invalid collection transmutes
- Prevents unsafe pointer casts

5. Documentation Enforcement (clippy_lints/src/doc/mod.rs)
- Enforces structured documentation requirements:
- Safety sections for unsafe code
- Error documentation for Result types
- Panic documentation where relevant
- Validates documentation formatting and structure

The system is organized around a plugin architecture where individual lints implement specific business rules for code analysis. Each lint can provide custom suggestions for code improvement while maintaining semantic correctness.

Key policy enforcement happens through:
- Configuration validation (clippy_config)
- Lint registration and management (clippy_lints/src/lib.rs)
- Custom pattern analysis (clippy_lints/src/matches)
- Safety rule enforcement (clippy_lints/src/transmute)

$END$
END SPECIFICATION
22 changes: 22 additions & 0 deletions .giga/specifications.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[
{
"fileName": "main-overview.mdc",
"description": "Complete overview of Clippy's architecture, including the lint pass system, core components, and high-level workflow of lint processing"
},
{
"fileName": "lint-data-model.mdc",
"description": "Documentation of core lint data structures, including lint attributes, levels, categories, and their relationships with the Rust compiler's internal representations"
},
{
"fileName": "lint-analysis-algorithms.mdc",
"description": "Detailed documentation of key algorithms used in lint analysis, including pattern matching, AST traversal, and type checking implementations"
},
{
"fileName": "data-flow-patterns.mdc",
"description": "Documentation of how data flows through the lint system, including lint registration, application, and suggestion generation processes"
},
{
"fileName": "type-validation-system.mdc",
"description": "Detailed documentation of the type validation system, focusing on transmute checks, casting validations, and type safety enforcement algorithms"
}
]
9 changes: 8 additions & 1 deletion clippy_lints/src/matches/manual_unwrap_or.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use clippy_utils::consts::ConstEvalCtxt;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::source::{SpanRangeExt as _, indent_of, reindent_multiline};
use rustc_ast::{BindingMode, ByRef};
use rustc_errors::Applicability;
Expand Down Expand Up @@ -82,6 +83,7 @@ fn handle(
body_some: &Expr<'_>,
body_none: &Expr<'_>,
binding_id: HirId,
msrv: Msrv,
) {
// Only deal with situations where both alternatives return the same non-adjusted type.
if cx.typeck_results().expr_ty(body_some) != cx.typeck_results().expr_ty(body_none) {
Expand Down Expand Up @@ -112,6 +114,8 @@ fn handle(
&& let GenericArgKind::Type(condition_ty) = condition_ty.unpack()
&& implements_trait(cx, condition_ty, default_trait_id, &[])
&& is_default_equivalent(cx, peel_blocks(body_none))
// Check if MSRV meets the requirement for unwrap_or_default (stabilized in 1.16)
&& msrv.meets(cx, msrvs::UNWRAP_OR_DEFAULT)
{
// We now check if the condition is a None variant, in which case we need to specify the type
if path_res(cx, condition)
Expand Down Expand Up @@ -186,6 +190,7 @@ pub fn check_match<'tcx>(
expr: &'tcx Expr<'tcx>,
scrutinee: &'tcx Expr<'tcx>,
arms: &'tcx [Arm<'tcx>],
msrv: Msrv,
) {
if let [arm1, arm2] = arms
// Make sure there are no guards to keep things simple
Expand All @@ -194,7 +199,7 @@ pub fn check_match<'tcx>(
// Get the some and none bodies and the binding id of the some arm
&& let Some(((body_some, binding_id), body_none)) = get_some_and_none_bodies(cx, arm1, arm2)
{
handle(cx, expr, "match", scrutinee, body_some, body_none, binding_id);
handle(cx, expr, "match", scrutinee, body_some, body_none, binding_id, msrv);
}
}

Expand All @@ -205,6 +210,7 @@ pub fn check_if_let<'tcx>(
scrutinee: &'tcx Expr<'tcx>,
then_expr: &'tcx Expr<'tcx>,
else_expr: &'tcx Expr<'tcx>,
msrv: Msrv,
) {
if let Some(binding_id) = get_some(cx, pat) {
handle(
Expand All @@ -215,6 +221,7 @@ pub fn check_if_let<'tcx>(
peel_blocks(then_expr),
peel_blocks(else_expr),
binding_id,
msrv,
);
}
}
Loading
Loading