Base: codex-main originale (prima del fork aKode)
This commit is contained in:
301
tools/argument-comment-lint/src/bin/argument-comment-lint.rs
Normal file
301
tools/argument-comment-lint/src/bin/argument-comment-lint.rs
Normal file
@@ -0,0 +1,301 @@
|
||||
use std::env;
|
||||
use std::ffi::OsString;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::process::ExitCode;
|
||||
use std::time::SystemTime;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
const STRICT_LINTS: [&str; 2] = [
|
||||
"argument-comment-mismatch",
|
||||
"uncommented-anonymous-literal-argument",
|
||||
];
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(code) => code,
|
||||
Err(err) => {
|
||||
eprintln!("{err}");
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> Result<ExitCode, String> {
|
||||
let exe_path =
|
||||
env::current_exe().map_err(|err| format!("failed to locate current executable: {err}"))?;
|
||||
let bin_dir = exe_path.parent().ok_or_else(|| {
|
||||
format!(
|
||||
"failed to locate parent directory for executable {}",
|
||||
exe_path.display()
|
||||
)
|
||||
})?;
|
||||
let package_root = bin_dir.parent().ok_or_else(|| {
|
||||
format!(
|
||||
"failed to locate package root for executable {}",
|
||||
exe_path.display()
|
||||
)
|
||||
})?;
|
||||
let cargo_dylint = bin_dir.join(cargo_dylint_binary_name());
|
||||
let library_dir = package_root.join("lib");
|
||||
let library_path = prepare_library_path_for_dylint(&find_bundled_library(&library_dir)?)?;
|
||||
|
||||
ensure_exists(&cargo_dylint, "bundled cargo-dylint executable")?;
|
||||
ensure_exists(
|
||||
&library_dir,
|
||||
"bundled argument-comment lint library directory",
|
||||
)?;
|
||||
|
||||
let args: Vec<OsString> = env::args_os().skip(1).collect();
|
||||
let mut command = Command::new(&cargo_dylint);
|
||||
command.arg("dylint");
|
||||
command.arg("--lib-path").arg(&library_path);
|
||||
if !has_library_selection(&args) {
|
||||
command.arg("--all");
|
||||
}
|
||||
command.args(&args);
|
||||
set_default_env(&mut command)?;
|
||||
|
||||
let status = command
|
||||
.status()
|
||||
.map_err(|err| format!("failed to execute {}: {err}", cargo_dylint.display()))?;
|
||||
Ok(exit_code_from_status(status.code()))
|
||||
}
|
||||
|
||||
fn has_library_selection(args: &[OsString]) -> bool {
|
||||
let mut expect_value = false;
|
||||
for arg in args {
|
||||
if expect_value {
|
||||
return true;
|
||||
}
|
||||
|
||||
match arg.to_string_lossy().as_ref() {
|
||||
"--" => break,
|
||||
"--lib" | "--lib-path" => {
|
||||
expect_value = true;
|
||||
}
|
||||
"--lib=" | "--lib-path=" => return true,
|
||||
value if value.starts_with("--lib=") || value.starts_with("--lib-path=") => {
|
||||
return true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn set_default_env(command: &mut Command) -> Result<(), String> {
|
||||
if let Some(flags) = env::var_os("DYLINT_RUSTFLAGS") {
|
||||
let mut flags = flags.to_string_lossy().to_string();
|
||||
for strict_lint in STRICT_LINTS {
|
||||
append_flag_if_missing(&mut flags, &format!("-D {strict_lint}"));
|
||||
}
|
||||
append_flag_if_missing(&mut flags, "-A unknown_lints");
|
||||
command.env("DYLINT_RUSTFLAGS", flags);
|
||||
} else {
|
||||
command.env("DYLINT_RUSTFLAGS", strict_rustflags());
|
||||
}
|
||||
|
||||
if env::var_os("CARGO_INCREMENTAL").is_none() {
|
||||
command.env("CARGO_INCREMENTAL", "0");
|
||||
}
|
||||
|
||||
if env::var_os("RUSTUP_HOME").is_none()
|
||||
&& let Some(rustup_home) = infer_rustup_home()?
|
||||
{
|
||||
command.env("RUSTUP_HOME", rustup_home);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn strict_rustflags() -> String {
|
||||
let strict_flags = STRICT_LINTS
|
||||
.iter()
|
||||
.map(|lint| format!("-D {lint}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
format!("{strict_flags} -A unknown_lints")
|
||||
}
|
||||
|
||||
fn append_flag_if_missing(flags: &mut String, flag: &str) {
|
||||
if flags.contains(flag) {
|
||||
return;
|
||||
}
|
||||
|
||||
if !flags.is_empty() {
|
||||
flags.push(' ');
|
||||
}
|
||||
flags.push_str(flag);
|
||||
}
|
||||
|
||||
fn cargo_dylint_binary_name() -> &'static str {
|
||||
if cfg!(windows) {
|
||||
"cargo-dylint.exe"
|
||||
} else {
|
||||
"cargo-dylint"
|
||||
}
|
||||
}
|
||||
|
||||
fn infer_rustup_home() -> Result<Option<OsString>, String> {
|
||||
let output = Command::new("rustup")
|
||||
.args(["show", "home"])
|
||||
.output()
|
||||
.map_err(|err| format!("failed to query rustup home via `rustup show home`: {err}"))?;
|
||||
if !output.status.success() {
|
||||
return Err(format!(
|
||||
"`rustup show home` failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
));
|
||||
}
|
||||
|
||||
let home = String::from_utf8(output.stdout)
|
||||
.map_err(|err| format!("`rustup show home` returned invalid UTF-8: {err}"))?;
|
||||
let home = home.trim();
|
||||
if home.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(OsString::from(home)))
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_exists(path: &Path, label: &str) -> Result<(), String> {
|
||||
if path.exists() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("{label} not found at {}", path.display()))
|
||||
}
|
||||
}
|
||||
|
||||
fn find_bundled_library(library_dir: &Path) -> Result<PathBuf, String> {
|
||||
let entries = fs::read_dir(library_dir).map_err(|err| {
|
||||
format!(
|
||||
"failed to read bundled library directory {}: {err}",
|
||||
library_dir.display()
|
||||
)
|
||||
})?;
|
||||
let mut candidates = entries
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| path.is_file())
|
||||
.filter(|path| {
|
||||
path.file_name()
|
||||
.map(|name| name.to_string_lossy().contains('@'))
|
||||
.unwrap_or(false)
|
||||
});
|
||||
|
||||
let Some(first) = candidates.next() else {
|
||||
return Err(format!(
|
||||
"no packaged Dylint library found in {}",
|
||||
library_dir.display()
|
||||
));
|
||||
};
|
||||
if candidates.next().is_some() {
|
||||
return Err(format!(
|
||||
"expected exactly one packaged Dylint library in {}",
|
||||
library_dir.display()
|
||||
));
|
||||
}
|
||||
|
||||
Ok(first)
|
||||
}
|
||||
|
||||
fn prepare_library_path_for_dylint(library_path: &Path) -> Result<PathBuf, String> {
|
||||
let Some(normalized_filename) = normalize_nightly_library_filename(library_path) else {
|
||||
return Ok(library_path.to_path_buf());
|
||||
};
|
||||
|
||||
let temp_dir = env::temp_dir().join(format!(
|
||||
"argument-comment-lint-{}-{}",
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|err| format!("failed to compute timestamp for temp dir: {err}"))?
|
||||
.as_nanos()
|
||||
));
|
||||
fs::create_dir_all(&temp_dir).map_err(|err| {
|
||||
format!(
|
||||
"failed to create temporary directory {}: {err}",
|
||||
temp_dir.display()
|
||||
)
|
||||
})?;
|
||||
let normalized_path = temp_dir.join(normalized_filename);
|
||||
fs::copy(library_path, &normalized_path).map_err(|err| {
|
||||
format!(
|
||||
"failed to copy packaged library {} to {}: {err}",
|
||||
library_path.display(),
|
||||
normalized_path.display()
|
||||
)
|
||||
})?;
|
||||
Ok(normalized_path)
|
||||
}
|
||||
|
||||
fn normalize_nightly_library_filename(library_path: &Path) -> Option<String> {
|
||||
let stem = library_path.file_stem()?.to_string_lossy();
|
||||
let extension = library_path.extension()?.to_string_lossy();
|
||||
let (lib_name, toolchain) = stem.rsplit_once('@')?;
|
||||
let normalized_toolchain = normalize_nightly_toolchain(toolchain)?;
|
||||
Some(format!("{lib_name}@{normalized_toolchain}.{extension}"))
|
||||
}
|
||||
|
||||
fn normalize_nightly_toolchain(toolchain: &str) -> Option<String> {
|
||||
let parts: Vec<_> = toolchain.split('-').collect();
|
||||
if parts.len() > 4
|
||||
&& parts[0] == "nightly"
|
||||
&& parts[1].len() == 4
|
||||
&& parts[2].len() == 2
|
||||
&& parts[3].len() == 2
|
||||
&& parts[1..4]
|
||||
.iter()
|
||||
.all(|part| part.chars().all(|ch| ch.is_ascii_digit()))
|
||||
{
|
||||
Some(format!("nightly-{}-{}-{}", parts[1], parts[2], parts[3]))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn exit_code_from_status(code: Option<i32>) -> ExitCode {
|
||||
code.and_then(|value| u8::try_from(value).ok())
|
||||
.map_or_else(|| ExitCode::from(1), ExitCode::from)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::normalize_nightly_library_filename;
|
||||
use super::strict_rustflags;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn strips_host_triple_from_nightly_filename() {
|
||||
assert_eq!(
|
||||
normalize_nightly_library_filename(Path::new(
|
||||
"libargument_comment_lint@nightly-2025-09-18-aarch64-apple-darwin.dylib"
|
||||
)),
|
||||
Some(String::from(
|
||||
"libargument_comment_lint@nightly-2025-09-18.dylib"
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_unqualified_nightly_filename_alone() {
|
||||
assert_eq!(
|
||||
normalize_nightly_library_filename(Path::new(
|
||||
"libargument_comment_lint@nightly-2025-09-18.dylib"
|
||||
)),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_rustflags_promotes_both_enforced_lints() {
|
||||
assert_eq!(
|
||||
strict_rustflags(),
|
||||
"-D argument-comment-mismatch -D uncommented-anonymous-literal-argument -A unknown_lints"
|
||||
);
|
||||
}
|
||||
}
|
||||
63
tools/argument-comment-lint/src/comment_parser.rs
Normal file
63
tools/argument-comment-lint/src/comment_parser.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
pub fn parse_argument_comment(text: &str) -> Option<&str> {
|
||||
let trimmed = text.trim_end();
|
||||
let comment_start = trimmed.rfind("/*")?;
|
||||
let comment = &trimmed[comment_start..];
|
||||
let name = comment.strip_prefix("/*")?.strip_suffix("*/")?;
|
||||
is_identifier(name).then_some(name)
|
||||
}
|
||||
|
||||
pub fn parse_argument_comment_prefix(text: &str) -> Option<&str> {
|
||||
let trimmed = text.trim_start();
|
||||
let comment = trimmed.strip_prefix("/*")?;
|
||||
let (name, _) = comment.split_once("*/")?;
|
||||
is_identifier(name).then_some(name)
|
||||
}
|
||||
|
||||
fn is_identifier(text: &str) -> bool {
|
||||
let mut chars = text.chars();
|
||||
let Some(first) = chars.next() else {
|
||||
return false;
|
||||
};
|
||||
if !(first == '_' || first.is_ascii_alphabetic()) {
|
||||
return false;
|
||||
}
|
||||
chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parse_argument_comment;
|
||||
use super::parse_argument_comment_prefix;
|
||||
|
||||
#[test]
|
||||
fn parses_trailing_comment() {
|
||||
assert_eq!(parse_argument_comment("(/*base_url*/ "), Some("base_url"));
|
||||
assert_eq!(
|
||||
parse_argument_comment(", /*timeout_ms*/ "),
|
||||
Some("timeout_ms")
|
||||
);
|
||||
assert_eq!(
|
||||
parse_argument_comment(".method::<u8>(/*base_url*/ "),
|
||||
Some("base_url")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_matching_shapes() {
|
||||
assert_eq!(parse_argument_comment("(\n"), None);
|
||||
assert_eq!(parse_argument_comment("(/* base_url*/ "), None);
|
||||
assert_eq!(parse_argument_comment("(/*base_url */ "), None);
|
||||
assert_eq!(parse_argument_comment("(/*base_url=*/ "), None);
|
||||
assert_eq!(parse_argument_comment("(/*1base_url*/ "), None);
|
||||
assert_eq!(parse_argument_comment_prefix("/*env=*/ None"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_prefix_comment() {
|
||||
assert_eq!(parse_argument_comment_prefix("/*env*/ None"), Some("env"));
|
||||
assert_eq!(
|
||||
parse_argument_comment_prefix("\n /*retry_count*/ 3"),
|
||||
Some("retry_count")
|
||||
);
|
||||
}
|
||||
}
|
||||
298
tools/argument-comment-lint/src/lib.rs
Normal file
298
tools/argument-comment-lint/src/lib.rs
Normal file
@@ -0,0 +1,298 @@
|
||||
#![feature(rustc_private)]
|
||||
|
||||
mod comment_parser;
|
||||
|
||||
extern crate rustc_ast;
|
||||
extern crate rustc_errors;
|
||||
extern crate rustc_hir;
|
||||
extern crate rustc_lint;
|
||||
extern crate rustc_middle;
|
||||
extern crate rustc_session;
|
||||
extern crate rustc_span;
|
||||
|
||||
use clippy_utils::diagnostics::span_lint_and_help;
|
||||
use clippy_utils::diagnostics::span_lint_and_sugg;
|
||||
use clippy_utils::fn_def_id;
|
||||
use clippy_utils::peel_blocks;
|
||||
use clippy_utils::res::MaybeDef;
|
||||
use clippy_utils::res::MaybeQPath;
|
||||
use clippy_utils::source::snippet;
|
||||
use rustc_ast::LitKind;
|
||||
use rustc_errors::Applicability;
|
||||
use rustc_hir::Expr;
|
||||
use rustc_hir::ExprKind;
|
||||
use rustc_hir::UnOp;
|
||||
use rustc_hir::attrs::lang_items::LangItem;
|
||||
use rustc_hir::def::DefKind;
|
||||
use rustc_lint::LateContext;
|
||||
use rustc_lint::LateLintPass;
|
||||
use rustc_span::BytePos;
|
||||
use rustc_span::Span;
|
||||
|
||||
use crate::comment_parser::parse_argument_comment;
|
||||
use crate::comment_parser::parse_argument_comment_prefix;
|
||||
|
||||
#[cfg(not(feature = "bazel_native"))]
|
||||
dylint_linting::dylint_library!();
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub fn register_lints(_sess: &rustc_session::Session, lint_store: &mut rustc_lint::LintStore) {
|
||||
lint_store.register_lints(&[
|
||||
ARGUMENT_COMMENT_MISMATCH,
|
||||
UNCOMMENTED_ANONYMOUS_LITERAL_ARGUMENT,
|
||||
]);
|
||||
lint_store.register_late_lint_pass(Box::new(|_| Box::new(ArgumentCommentLint)));
|
||||
}
|
||||
|
||||
rustc_session::declare_lint! {
|
||||
/// ### What it does
|
||||
///
|
||||
/// Checks `/*param*/` argument comments and verifies that the comment
|
||||
/// matches the resolved callee parameter name.
|
||||
///
|
||||
/// ### Why is this bad?
|
||||
///
|
||||
/// A mismatched comment is worse than no comment because it actively
|
||||
/// misleads the reader.
|
||||
///
|
||||
/// ### Known problems
|
||||
///
|
||||
/// This lint only runs when the callee resolves to a concrete function or
|
||||
/// method with available parameter names.
|
||||
///
|
||||
/// ### Example
|
||||
///
|
||||
/// ```rust
|
||||
/// fn create_openai_url(base_url: Option<String>) -> String {
|
||||
/// String::new()
|
||||
/// }
|
||||
///
|
||||
/// create_openai_url(/*api_base*/ None);
|
||||
/// ```
|
||||
///
|
||||
/// Use instead:
|
||||
///
|
||||
/// ```rust
|
||||
/// fn create_openai_url(base_url: Option<String>) -> String {
|
||||
/// String::new()
|
||||
/// }
|
||||
///
|
||||
/// create_openai_url(/*base_url*/ None);
|
||||
/// ```
|
||||
pub ARGUMENT_COMMENT_MISMATCH,
|
||||
Warn,
|
||||
"argument comment does not match the resolved parameter name"
|
||||
}
|
||||
|
||||
rustc_session::declare_lint! {
|
||||
/// ### What it does
|
||||
///
|
||||
/// Requires a `/*param*/` comment before anonymous literal-like
|
||||
/// arguments such as `None`, booleans, and numeric literals.
|
||||
/// A method's sole non-self argument is exempt when its name matches the
|
||||
/// method name.
|
||||
///
|
||||
/// ### Why is this bad?
|
||||
///
|
||||
/// Bare literal-like arguments make call sites harder to read because the
|
||||
/// meaning of the value is hidden in the callee signature.
|
||||
///
|
||||
/// ### Known problems
|
||||
///
|
||||
/// This lint is opinionated, so it is `allow` by default.
|
||||
///
|
||||
/// ### Example
|
||||
///
|
||||
/// ```rust
|
||||
/// fn create_openai_url(base_url: Option<String>) -> String {
|
||||
/// String::new()
|
||||
/// }
|
||||
///
|
||||
/// create_openai_url(None);
|
||||
/// ```
|
||||
///
|
||||
/// Use instead:
|
||||
///
|
||||
/// ```rust
|
||||
/// fn create_openai_url(base_url: Option<String>) -> String {
|
||||
/// String::new()
|
||||
/// }
|
||||
///
|
||||
/// create_openai_url(/*base_url*/ None);
|
||||
/// ```
|
||||
pub UNCOMMENTED_ANONYMOUS_LITERAL_ARGUMENT,
|
||||
Allow,
|
||||
"anonymous literal-like argument is missing a `/*param*/` comment"
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ArgumentCommentLint;
|
||||
|
||||
enum CallKind {
|
||||
Function,
|
||||
Method { name: String },
|
||||
}
|
||||
|
||||
rustc_session::impl_lint_pass!(
|
||||
ArgumentCommentLint => [ARGUMENT_COMMENT_MISMATCH, UNCOMMENTED_ANONYMOUS_LITERAL_ARGUMENT]
|
||||
);
|
||||
|
||||
impl<'tcx> LateLintPass<'tcx> for ArgumentCommentLint {
|
||||
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
|
||||
if expr.span.from_expansion() {
|
||||
return;
|
||||
}
|
||||
|
||||
match expr.kind {
|
||||
ExprKind::Call(callee, args) => {
|
||||
self.check_call(cx, expr, callee.span, args, CallKind::Function);
|
||||
}
|
||||
ExprKind::MethodCall(method, receiver, args, _) => {
|
||||
self.check_call(
|
||||
cx,
|
||||
expr,
|
||||
receiver.span,
|
||||
args,
|
||||
CallKind::Method {
|
||||
name: method.ident.name.to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ArgumentCommentLint {
|
||||
fn check_call<'tcx>(
|
||||
&self,
|
||||
cx: &LateContext<'tcx>,
|
||||
call: &'tcx Expr<'tcx>,
|
||||
first_gap_anchor: Span,
|
||||
args: &'tcx [Expr<'tcx>],
|
||||
call_kind: CallKind,
|
||||
) {
|
||||
let Some(def_id) = fn_def_id(cx, call) else {
|
||||
return;
|
||||
};
|
||||
if !def_id.is_local() && !is_workspace_crate_name(cx.tcx.crate_name(def_id.krate).as_str())
|
||||
{
|
||||
return;
|
||||
}
|
||||
if !matches!(cx.tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Method parameter lists include `self`, which is not present in `args`.
|
||||
let (parameter_offset, method_name) = match &call_kind {
|
||||
CallKind::Function => (0, None),
|
||||
CallKind::Method { name } => (1, Some(name.as_str())),
|
||||
};
|
||||
let parameter_names: Vec<_> = cx.tcx.fn_arg_idents(def_id).iter().copied().collect();
|
||||
for (index, arg) in args.iter().enumerate() {
|
||||
if arg.span.from_expansion() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(expected_name) = parameter_names.get(index + parameter_offset) else {
|
||||
continue;
|
||||
};
|
||||
let Some(expected_name) = expected_name else {
|
||||
continue;
|
||||
};
|
||||
let expected_name = expected_name.name.to_string();
|
||||
if !is_meaningful_parameter_name(&expected_name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let boundary_span = if index == 0 {
|
||||
first_gap_anchor
|
||||
} else {
|
||||
args[index - 1].span
|
||||
};
|
||||
let gap_span = boundary_span.between(arg.span);
|
||||
let gap_text = snippet(cx, gap_span, "");
|
||||
let arg_text = snippet(cx, arg.span, "..");
|
||||
let lookbehind_start = BytePos(arg.span.lo().0.saturating_sub(64));
|
||||
let lookbehind_text =
|
||||
snippet(cx, arg.span.shrink_to_lo().with_lo(lookbehind_start), "");
|
||||
let argument_comment = parse_argument_comment(gap_text.as_ref())
|
||||
.or_else(|| parse_argument_comment(lookbehind_text.as_ref()))
|
||||
.or_else(|| parse_argument_comment_prefix(arg_text.as_ref()));
|
||||
|
||||
if let Some(actual_name) = argument_comment {
|
||||
if actual_name != expected_name {
|
||||
span_lint_and_help(
|
||||
cx,
|
||||
ARGUMENT_COMMENT_MISMATCH,
|
||||
arg.span,
|
||||
format!(
|
||||
"argument comment `/*{actual_name}*/` does not match parameter `{expected_name}`"
|
||||
),
|
||||
None,
|
||||
format!("use `/*{expected_name}*/`"),
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Don't require a clarifying comment for self-documenting arguments whose names
|
||||
// match the method.
|
||||
if args.len() == 1 && method_name == Some(expected_name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if !is_anonymous_literal_like(cx, arg) {
|
||||
continue;
|
||||
}
|
||||
|
||||
span_lint_and_sugg(
|
||||
cx,
|
||||
UNCOMMENTED_ANONYMOUS_LITERAL_ARGUMENT,
|
||||
arg.span,
|
||||
format!("anonymous literal-like argument for parameter `{expected_name}`"),
|
||||
"prepend the parameter name comment",
|
||||
format!("/*{expected_name}*/ {arg_text}"),
|
||||
Applicability::MachineApplicable,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_anonymous_literal_like(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
|
||||
let expr = peel_blocks(expr);
|
||||
match expr.kind {
|
||||
ExprKind::Lit(lit) => !matches!(
|
||||
lit.node,
|
||||
LitKind::Str(..) | LitKind::ByteStr(..) | LitKind::CStr(..) | LitKind::Char(..)
|
||||
),
|
||||
ExprKind::Unary(UnOp::Neg, inner) => matches!(peel_blocks(inner).kind, ExprKind::Lit(_)),
|
||||
ExprKind::Path(_) => expr
|
||||
.res(cx)
|
||||
.ctor_parent(cx)
|
||||
.is_lang_item(cx, LangItem::OptionNone),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_meaningful_parameter_name(name: &str) -> bool {
|
||||
!name.is_empty() && !name.starts_with('_')
|
||||
}
|
||||
|
||||
fn is_workspace_crate_name(name: &str) -> bool {
|
||||
name.starts_with("codex_") || matches!(name, "app_test_support" | "core_test_support")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ui() {
|
||||
dylint_testing::ui_test(env!("CARGO_PKG_NAME"), "ui");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_crate_filter_accepts_first_party_names_only() {
|
||||
assert!(is_workspace_crate_name("codex_core"));
|
||||
assert!(is_workspace_crate_name("codex_tui"));
|
||||
assert!(is_workspace_crate_name("core_test_support"));
|
||||
assert!(!is_workspace_crate_name("std"));
|
||||
assert!(!is_workspace_crate_name("tokio"));
|
||||
}
|
||||
Reference in New Issue
Block a user