Skip to content

Add relative_path_in_macro_definition lint (#14472) #14645 #14648

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ See [Changelog Update](book/src/development/infrastructure/changelog_update.md)
document.

## Unreleased / Beta / In Rust Nightly
### New Lints
- **`relative_path_in_macro_definition`**:
Warns about relative paths to `core` or `kernel` in macro definitions, recommending absolute paths to avoid ambiguity.

[3e3715c3...master](https://github.com/rust-lang/rust-clippy/compare/3e3715c3...master)

Expand Down Expand Up @@ -6126,6 +6129,7 @@ Released 2018-09-13
[`ref_patterns`]: https://rust-lang.github.io/rust-clippy/master/index.html#ref_patterns
[`regex_creation_in_loops`]: https://rust-lang.github.io/rust-clippy/master/index.html#regex_creation_in_loops
[`regex_macro`]: https://rust-lang.github.io/rust-clippy/master/index.html#regex_macro
[`relative_path_in_macro_definition`]: https://rust-lang.github.io/rust-clippy/master/index.html#relative_path_in_macro_definition
[`renamed_function_params`]: https://rust-lang.github.io/rust-clippy/master/index.html#renamed_function_params
[`repeat_once`]: https://rust-lang.github.io/rust-clippy/master/index.html#repeat_once
[`repeat_vec_with_capacity`]: https://rust-lang.github.io/rust-clippy/master/index.html#repeat_vec_with_capacity
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/declared_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -676,6 +676,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
crate::regex::INVALID_REGEX_INFO,
crate::regex::REGEX_CREATION_IN_LOOPS_INFO,
crate::regex::TRIVIAL_REGEX_INFO,
crate::relative_path_in_macro_definition::RELATIVE_PATH_IN_MACRO_DEFINITION_INFO,
crate::repeat_vec_with_capacity::REPEAT_VEC_WITH_CAPACITY_INFO,
crate::reserve_after_initialization::RESERVE_AFTER_INITIALIZATION_INFO,
crate::return_self_not_must_use::RETURN_SELF_NOT_MUST_USE_INFO,
Expand Down
2 changes: 2 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ mod ref_option_ref;
mod ref_patterns;
mod reference;
mod regex;
mod relative_path_in_macro_definition;
mod repeat_vec_with_capacity;
mod reserve_after_initialization;
mod return_self_not_must_use;
Expand Down Expand Up @@ -986,5 +987,6 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(|_| Box::new(manual_option_as_slice::ManualOptionAsSlice::new(conf)));
store.register_late_pass(|_| Box::new(single_option_map::SingleOptionMap));
store.register_late_pass(move |_| Box::new(redundant_test_prefix::RedundantTestPrefix));
store.register_early_pass(|| Box::new(relative_path_in_macro_definition::RelativePathInMacroDefinition));
// add lints here, do not remove this comment, it's used in `new_lint`
}
93 changes: 93 additions & 0 deletions clippy_lints/src/relative_path_in_macro_definition.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
use clippy_utils::diagnostics::span_lint;
use rustc_ast::ast::{Item, ItemKind};
use rustc_ast::token::TokenKind;
use rustc_ast::tokenstream::{TokenStream, TokenTree};
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_session::declare_lint_pass;
use rustc_span::symbol::sym;

declare_clippy_lint! {
/// ### What it does
/// Checks that references to the `core` or `kernel` crate in macro definitions use absolute paths (`::core` or `::kernel`).
///
/// ### Why is this bad?
/// Using relative paths (e.g., `core::...`) in macros can lead to ambiguity if the macro is used in a context
/// where a user defines a module named `core` or `kernel`. Absolute paths ensure the macro always refers to the intended crate.
///
/// ### Example
/// ```rust
/// // Bad
/// macro_rules! my_macro {
/// () => {
/// core::mem::drop(0);
/// };
/// }
///
/// // Good
/// macro_rules! my_macro {
/// () => {
/// ::core::mem::drop(0);
/// };
/// }
/// ```
#[clippy::version = "1.88.0"]
pub RELATIVE_PATH_IN_MACRO_DEFINITION,
correctness,
"using relative paths in declarative macros can lead to context-dependent behavior"
}

declare_lint_pass!(RelativePathInMacroDefinition => [RELATIVE_PATH_IN_MACRO_DEFINITION]);

impl EarlyLintPass for RelativePathInMacroDefinition {
fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
if let ItemKind::MacroDef(_, macro_def) = &item.kind {
check_token_stream(cx, &macro_def.body.tokens);
}
}
}

fn check_token_stream(cx: &EarlyContext<'_>, tokens: &TokenStream) {
let mut iter = tokens.iter().peekable();
let mut prev_token: Option<&TokenTree> = None;

while let Some(tree) = iter.next() {
match tree {
TokenTree::Token(token, _) => {
if let TokenKind::Ident(ident, _) = token.kind
&& (ident == sym::core || ident.as_str() == "kernel")
Copy link
Contributor

Choose a reason for hiding this comment

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

We no longer need ident.as_str(). Look at clippy_utils::sym.

Copy link
Author

Choose a reason for hiding this comment

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

Thank you for your feedback and suggestion to avoid ident.as_str() and refer to clippy_utils::sym. I've encountered a compilation error with the current implementation:
error[E0425]: cannot find value kernel in module sym
--> clippy_lints/src/relative_path_in_macro_definition.rs:57:61
|
57 | && (ident == sym::core || ident == sym::kernel)
| ^^^^^^ not found in sym

The issue arises because rustc_span::symbol::sym does not define a kernel symbol, unlike core. Upon reviewing clippy_utils::sym, I found it to be a macro that wraps Symbol::intern, used for creating symbols from strings, rather than providing predefined symbols like core.
To address this, I propose using Symbol::intern("kernel") to create the kernel symbol dynamically, allowing direct comparison with ident (of type rustc_span::Ident). The updated code snippet is:
if ident == sym::core || ident == Symbol::intern("kernel") {
// ... rest of the lint logic ...
}

This approach avoids ident.as_str() as you recommended, using direct symbol comparisons for efficiency. I've tested this change locally, and it resolves the compilation error while maintaining the lint's functionality to check for relative paths to core and kernel in macro definitions.
Could you please confirm if using Symbol::intern("kernel") is acceptable for this lint, or if there's a preferred method within Clippy's codebase (e.g., using clippy_utils::sym! macro or another approach)? Thank you for your guidance!

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes, you can simply add "kernel" into that generate! macro call, then you can use clippy_utils::sym::kernel in your code.

Copy link
Author

Choose a reason for hiding this comment

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

Yes, you can simply add "kernel" into that generate! macro call, then you can use clippy_utils::sym::kernel in your code.

It seems that the definition of "sym::core" is in
https://github.com/rust-lang/rust/blob/master/compiler/rustc_span/src/symbol.rs.
But according to the discussion below, we no longer need to add the extra check. Anyway, thanks for the reply.

{
let is_path_start = iter.peek().is_some_and(|next_tree| {
if let TokenTree::Token(next_token, _) = next_tree {
next_token.kind == TokenKind::PathSep
} else {
false
}
});

if is_path_start {
let is_absolute = prev_token.is_some_and(|prev| {
if let TokenTree::Token(prev_token, _) = prev {
prev_token.kind == TokenKind::PathSep
} else {
false
}
Comment on lines +69 to +73
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
if let TokenTree::Token(prev_token, _) = prev {
prev_token.kind == TokenKind::PathSep
} else {
false
}
matches!(prev, TokenTree::Token(Token { kind: TokenKind::PathSep, .. }, _))

Copy link
Author

Choose a reason for hiding this comment

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

thx, I'll change it in v2.

});

if !is_absolute {
span_lint(
cx,
RELATIVE_PATH_IN_MACRO_DEFINITION,
token.span,
"relative path to `core` or `kernel` used in macro definition",
Copy link
Contributor

Choose a reason for hiding this comment

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

Here we should reuse the first element of the path instead of writing both options.

Copy link
Author

Choose a reason for hiding this comment

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

thx, I'll change it in v2.

);
}
}
}
},
TokenTree::Delimited(_open_span, _close_span, _delim, token_stream) => {
check_token_stream(cx, token_stream);
},
}
prev_token = Some(tree);
}
}
1 change: 1 addition & 0 deletions tests/ui/arithmetic_side_effects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
clippy::identity_op,
clippy::no_effect,
clippy::op_ref,
clippy::relative_path_in_macro_definition,
clippy::unnecessary_owned_empty_strings,
arithmetic_overflow,
unconditional_panic
Expand Down
Loading