Base: codex-main originale (prima del fork aKode)
This commit is contained in:
6
tools/argument-comment-lint/.cargo/config.toml
Normal file
6
tools/argument-comment-lint/.cargo/config.toml
Normal file
@@ -0,0 +1,6 @@
|
||||
[target.'cfg(all())']
|
||||
rustflags = ["-C", "linker=dylint-link"]
|
||||
|
||||
# For Rust versions 1.74.0 and onward, the following alternative can be used
|
||||
# (see https://github.com/rust-lang/cargo/pull/12535):
|
||||
# linker = "dylint-link"
|
||||
1
tools/argument-comment-lint/.gitignore
vendored
Normal file
1
tools/argument-comment-lint/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/target
|
||||
32
tools/argument-comment-lint/BUILD.bazel
Normal file
32
tools/argument-comment-lint/BUILD.bazel
Normal file
@@ -0,0 +1,32 @@
|
||||
load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library")
|
||||
|
||||
exports_files(["lint_aspect.bzl"])
|
||||
|
||||
rust_library(
|
||||
name = "argument-comment-lint-lib",
|
||||
srcs = [
|
||||
"src/comment_parser.rs",
|
||||
"src/lib.rs",
|
||||
],
|
||||
crate_features = ["bazel_native"],
|
||||
crate_name = "argument_comment_lint",
|
||||
crate_root = "src/lib.rs",
|
||||
edition = "2024",
|
||||
tags = ["manual"],
|
||||
visibility = ["//visibility:public"],
|
||||
deps = ["@argument_comment_lint_crates//:clippy_utils"],
|
||||
)
|
||||
|
||||
rust_binary(
|
||||
name = "argument-comment-lint-driver",
|
||||
srcs = ["driver.rs"],
|
||||
crate_name = "argument_comment_lint_driver",
|
||||
crate_root = "driver.rs",
|
||||
edition = "2024",
|
||||
tags = ["manual"],
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
":argument-comment-lint-lib",
|
||||
"@zlib//:z",
|
||||
],
|
||||
)
|
||||
1362
tools/argument-comment-lint/Cargo.lock
generated
Normal file
1362
tools/argument-comment-lint/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
24
tools/argument-comment-lint/Cargo.toml
Normal file
24
tools/argument-comment-lint/Cargo.toml
Normal file
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "argument_comment_lint"
|
||||
version = "0.1.0"
|
||||
description = "Dylint lints for Rust /*param*/ argument comments"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[features]
|
||||
bazel_native = []
|
||||
|
||||
[dependencies]
|
||||
clippy_utils = { git = "https://github.com/rust-lang/rust-clippy", rev = "21baba9c10c5d179915cae82e6247bc2337872fb" }
|
||||
dylint_linting = "6.3.0"
|
||||
|
||||
[dev-dependencies]
|
||||
dylint_testing = "6.3.0"
|
||||
|
||||
[workspace]
|
||||
|
||||
[package.metadata.rust-analyzer]
|
||||
rustc_private = true
|
||||
176
tools/argument-comment-lint/README.md
Normal file
176
tools/argument-comment-lint/README.md
Normal file
@@ -0,0 +1,176 @@
|
||||
# argument-comment-lint
|
||||
|
||||
Isolated [Dylint](https://github.com/trailofbits/dylint) library for enforcing
|
||||
Rust argument comments in the exact `/*param*/` shape.
|
||||
|
||||
Prefer self-documenting APIs over comment-heavy call sites when possible. If a
|
||||
call site would otherwise read like `foo(false)` or `bar(None)`, consider an
|
||||
enum, named helper, newtype, or another idiomatic Rust API shape first, and
|
||||
use an argument comment only when a smaller compatibility-preserving change is
|
||||
more appropriate.
|
||||
|
||||
It provides two lints:
|
||||
|
||||
- `argument_comment_mismatch` (`warn` by default): validates that a present
|
||||
`/*param*/` comment matches the resolved callee parameter name.
|
||||
- `uncommented_anonymous_literal_argument` (`allow` by default): flags
|
||||
anonymous literal-like arguments such as `None`, `true`, `false`, and numeric
|
||||
literals when they do not have a preceding `/*param*/` comment.
|
||||
|
||||
String and char literals are exempt because they are often already
|
||||
self-descriptive at the callsite.
|
||||
|
||||
The sole non-self method argument is also exempt when the method name matches
|
||||
the resolved parameter name. For example, `.enabled(false)` is already
|
||||
self-descriptive when it resolves to `fn enabled(self, enabled: bool)`. An
|
||||
explicit argument comment is still checked for a mismatch.
|
||||
|
||||
## Behavior
|
||||
|
||||
Given:
|
||||
|
||||
```rust
|
||||
fn create_openai_url(base_url: Option<String>, retry_count: usize) -> String {
|
||||
let _ = (base_url, retry_count);
|
||||
String::new()
|
||||
}
|
||||
```
|
||||
|
||||
This is accepted:
|
||||
|
||||
```rust
|
||||
create_openai_url(/*base_url*/ None, /*retry_count*/ 3);
|
||||
```
|
||||
|
||||
This is warned on by `argument_comment_mismatch`:
|
||||
|
||||
```rust
|
||||
create_openai_url(/*api_base*/ None, 3);
|
||||
```
|
||||
|
||||
This is only warned on when `uncommented_anonymous_literal_argument` is enabled:
|
||||
|
||||
```rust
|
||||
create_openai_url(None, 3);
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
Install the required tooling once:
|
||||
|
||||
```bash
|
||||
rustup toolchain install nightly-2026-08-20 \
|
||||
--component llvm-tools-preview \
|
||||
--component rustc-dev \
|
||||
--component rust-src
|
||||
rustup run nightly-2026-08-20 cargo install --locked \
|
||||
cargo-dylint@6.3.0 dylint-link@6.3.0
|
||||
```
|
||||
|
||||
Run the lint crate tests:
|
||||
|
||||
```bash
|
||||
cd tools/argument-comment-lint
|
||||
cargo test
|
||||
```
|
||||
|
||||
GitHub releases also publish a DotSlash file named
|
||||
`argument-comment-lint` for macOS arm64, Linux arm64, Linux x64, and Windows
|
||||
x64. The published package contains a small runner executable, a bundled
|
||||
`cargo-dylint`, and the prebuilt lint library.
|
||||
|
||||
The package is not a full Rust toolchain. Running the prebuilt path still
|
||||
requires the pinned nightly toolchain to be installed via `rustup`:
|
||||
|
||||
```bash
|
||||
rustup toolchain install nightly-2026-08-20 \
|
||||
--component llvm-tools-preview \
|
||||
--component rustc-dev \
|
||||
--component rust-src
|
||||
```
|
||||
|
||||
The checked-in DotSlash file lives at `tools/argument-comment-lint/argument-comment-lint`.
|
||||
`run-prebuilt-linter.py` resolves that file via `dotslash` and is the path used by
|
||||
targeted package runs such as `just argument-comment-lint -p codex-core`.
|
||||
Repo-wide runs now go through a native Bazel aspect that invokes a custom
|
||||
`rustc_driver` and reuses Bazel-managed Rust dependency metadata instead of
|
||||
spawning `cargo dylint` once per crate. The source-build path remains available
|
||||
in `run.py` for people iterating on the lint crate itself.
|
||||
|
||||
The Unix archive layout is:
|
||||
|
||||
```text
|
||||
argument-comment-lint/
|
||||
bin/
|
||||
argument-comment-lint
|
||||
cargo-dylint
|
||||
lib/
|
||||
libargument_comment_lint@<nightly>-<target>.dylib|so
|
||||
```
|
||||
|
||||
On Windows the same layout is published as a `.zip`, with `.exe` and `.dll`
|
||||
filenames instead.
|
||||
|
||||
DotSlash resolves the package entrypoint to `argument-comment-lint/bin/argument-comment-lint`
|
||||
(or `.exe` on Windows). That runner finds the sibling bundled `cargo-dylint`
|
||||
binary and the single packaged Dylint library under `lib/`, normalizes the
|
||||
library filename to the nightly channel without the host triple when
|
||||
needed, and then invokes `cargo-dylint dylint --lib-path <that-library>` with
|
||||
the repo's default `DYLINT_RUSTFLAGS` and `CARGO_INCREMENTAL=0` settings.
|
||||
|
||||
The repository's `run-prebuilt-linter.py` wrapper invokes the bundled
|
||||
`cargo-dylint` and normalizes the library filename itself. It makes sure
|
||||
the `rustup` shims stay ahead of any direct toolchain
|
||||
`cargo` binary on `PATH`, and sets `RUSTUP_HOME` from `rustup show home` when
|
||||
the environment does not already provide it. That extra `RUSTUP_HOME` export is
|
||||
required for the current Windows Dylint driver path.
|
||||
|
||||
If you are changing the lint crate itself, use the source-build wrapper:
|
||||
|
||||
```bash
|
||||
./tools/argument-comment-lint/run.py -p codex-core
|
||||
```
|
||||
|
||||
Run the lint against `codex-rs` from the repo root:
|
||||
|
||||
```bash
|
||||
just argument-comment-lint
|
||||
bazel build --config=argument-comment-lint -- \
|
||||
$(./tools/argument-comment-lint/list-bazel-targets.sh)
|
||||
./tools/argument-comment-lint/run-prebuilt-linter.py -p codex-core
|
||||
just argument-comment-lint -p codex-core
|
||||
```
|
||||
|
||||
If no package selection is provided, `just argument-comment-lint` now defaults
|
||||
to the Bazel aspect path over `//codex-rs/...`. The Python wrappers remain the
|
||||
package-scoped escape hatch and still default the underlying Cargo invocation
|
||||
to `--all-targets` unless you explicitly narrow the target set, so targeted
|
||||
wrapper runs cover test-only call sites by default. The Bazel entrypoints use
|
||||
`tools/argument-comment-lint/list-bazel-targets.sh` to add the internal
|
||||
manual `*-unit-tests-bin` Rust targets explicitly, so inline `#[cfg(test)]`
|
||||
call sites are covered without pulling in unrelated manual release targets.
|
||||
|
||||
Repo runs also promote `argument_comment_mismatch` and
|
||||
`uncommented_anonymous_literal_argument` to errors by default:
|
||||
|
||||
```bash
|
||||
./tools/argument-comment-lint/run-prebuilt-linter.py -p codex-core
|
||||
```
|
||||
|
||||
The wrapper does that by setting `DYLINT_RUSTFLAGS`, and it leaves an explicit
|
||||
existing setting alone. It also defaults `CARGO_INCREMENTAL=0` unless you have
|
||||
already set it, because the current nightly Dylint flow can otherwise hit a
|
||||
rustc incremental compilation ICE locally. To override that behavior for an ad
|
||||
hoc run:
|
||||
|
||||
```bash
|
||||
DYLINT_RUSTFLAGS="-A argument-comment-mismatch -A uncommented-anonymous-literal-argument" \
|
||||
CARGO_INCREMENTAL=1 \
|
||||
./tools/argument-comment-lint/run.py -p codex-core
|
||||
```
|
||||
|
||||
To override an explicitly narrow target selection, or to be explicit in scripts:
|
||||
|
||||
```bash
|
||||
./tools/argument-comment-lint/run-prebuilt-linter.py -p codex-core -- --all-targets
|
||||
```
|
||||
79
tools/argument-comment-lint/argument-comment-lint
Executable file
79
tools/argument-comment-lint/argument-comment-lint
Executable file
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env dotslash
|
||||
|
||||
{
|
||||
"name": "argument-comment-lint",
|
||||
"platforms": {
|
||||
"macos-aarch64": {
|
||||
"size": 3342901,
|
||||
"hash": "blake3",
|
||||
"digest": "eba9eb7196d34af64ef282f33f1588000857e9161a19ba9447038ef5e623bd99",
|
||||
"format": "tar.gz",
|
||||
"path": "argument-comment-lint/bin/argument-comment-lint",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/openai/codex/releases/download/rust-v0.164.0/argument-comment-lint-aarch64-apple-darwin.tar.gz"
|
||||
},
|
||||
{
|
||||
"type": "github-release",
|
||||
"repo": "https://github.com/openai/codex",
|
||||
"tag": "rust-v0.164.0",
|
||||
"name": "argument-comment-lint-aarch64-apple-darwin.tar.gz"
|
||||
}
|
||||
]
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"size": 3809665,
|
||||
"hash": "blake3",
|
||||
"digest": "f8c51999175df9bfd545b5454356c1bba62e0957d99ef06198a93283c01dc560",
|
||||
"format": "tar.gz",
|
||||
"path": "argument-comment-lint/bin/argument-comment-lint",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/openai/codex/releases/download/rust-v0.164.0/argument-comment-lint-x86_64-unknown-linux-gnu.tar.gz"
|
||||
},
|
||||
{
|
||||
"type": "github-release",
|
||||
"repo": "https://github.com/openai/codex",
|
||||
"tag": "rust-v0.164.0",
|
||||
"name": "argument-comment-lint-x86_64-unknown-linux-gnu.tar.gz"
|
||||
}
|
||||
]
|
||||
},
|
||||
"linux-aarch64": {
|
||||
"size": 3735760,
|
||||
"hash": "blake3",
|
||||
"digest": "350baa8efbef8f743da3f74947e3598d0fe79666cefc4fcec25618e01c74e5cb",
|
||||
"format": "tar.gz",
|
||||
"path": "argument-comment-lint/bin/argument-comment-lint",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/openai/codex/releases/download/rust-v0.164.0/argument-comment-lint-aarch64-unknown-linux-gnu.tar.gz"
|
||||
},
|
||||
{
|
||||
"type": "github-release",
|
||||
"repo": "https://github.com/openai/codex",
|
||||
"tag": "rust-v0.164.0",
|
||||
"name": "argument-comment-lint-aarch64-unknown-linux-gnu.tar.gz"
|
||||
}
|
||||
]
|
||||
},
|
||||
"windows-x86_64": {
|
||||
"size": 3271160,
|
||||
"hash": "blake3",
|
||||
"digest": "a2d1c8f71d9acf3885dd469876a249b769dd93e117c7a43192994e18d43e9027",
|
||||
"format": "zip",
|
||||
"path": "argument-comment-lint/bin/argument-comment-lint.exe",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/openai/codex/releases/download/rust-v0.164.0/argument-comment-lint-x86_64-pc-windows-msvc.zip"
|
||||
},
|
||||
{
|
||||
"type": "github-release",
|
||||
"repo": "https://github.com/openai/codex",
|
||||
"tag": "rust-v0.164.0",
|
||||
"name": "argument-comment-lint-x86_64-pc-windows-msvc.zip"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
43
tools/argument-comment-lint/driver.rs
Normal file
43
tools/argument-comment-lint/driver.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
#![feature(rustc_private)]
|
||||
|
||||
extern crate rustc_driver;
|
||||
extern crate rustc_interface;
|
||||
|
||||
use std::env;
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
|
||||
fn main() {
|
||||
let mut callbacks = Callbacks;
|
||||
let args = rustc_args(env::args_os().skip(1).collect());
|
||||
rustc_driver::run_compiler(&args, &mut callbacks);
|
||||
}
|
||||
|
||||
struct Callbacks;
|
||||
|
||||
impl rustc_driver::Callbacks for Callbacks {
|
||||
fn config(&mut self, config: &mut rustc_interface::Config) {
|
||||
let previous = config.register_lints.take();
|
||||
config.register_lints = Some(Box::new(move |sess, lint_store| {
|
||||
if let Some(previous) = &previous {
|
||||
previous(sess, lint_store);
|
||||
}
|
||||
argument_comment_lint::register_lints(sess, lint_store);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
fn rustc_args(args: Vec<OsString>) -> Vec<String> {
|
||||
let mut rustc_args: Vec<String> = args
|
||||
.into_iter()
|
||||
.map(|arg| arg.to_string_lossy().into_owned())
|
||||
.collect();
|
||||
if rustc_args.first().is_none_or(|arg| !is_rustc(arg)) {
|
||||
rustc_args.insert(0, "rustc".to_string());
|
||||
}
|
||||
rustc_args
|
||||
}
|
||||
|
||||
fn is_rustc(arg: &str) -> bool {
|
||||
Path::new(arg).file_stem().and_then(|stem| stem.to_str()) == Some("rustc")
|
||||
}
|
||||
188
tools/argument-comment-lint/lint_aspect.bzl
Normal file
188
tools/argument-comment-lint/lint_aspect.bzl
Normal file
@@ -0,0 +1,188 @@
|
||||
"""Bazel aspect for running argument-comment-lint on Rust targets."""
|
||||
|
||||
load("@rules_rust//rust:defs.bzl", "rust_common")
|
||||
load("@rules_rust//rust/private:rust.bzl", "RUSTC_ATTRS")
|
||||
load(
|
||||
"@rules_rust//rust/private:rustc.bzl",
|
||||
"collect_deps",
|
||||
"collect_inputs",
|
||||
"construct_arguments",
|
||||
)
|
||||
load(
|
||||
"@rules_rust//rust/private:utils.bzl",
|
||||
"determine_output_hash",
|
||||
"find_cc_toolchain",
|
||||
"find_toolchain",
|
||||
)
|
||||
|
||||
_STRICT_LINT_FLAGS = [
|
||||
"-Dargument-comment-mismatch",
|
||||
"-Duncommented-anonymous-literal-argument",
|
||||
"-Aunknown-lints",
|
||||
]
|
||||
|
||||
def _find_rustc_driver_library(toolchain):
|
||||
for file in toolchain.rustc_lib.to_list():
|
||||
if file.basename.startswith("librustc_driver-") or file.basename.startswith("rustc_driver-"):
|
||||
return file
|
||||
return None
|
||||
|
||||
def _prepend_runtime_path(env, key, path, separator):
|
||||
previous = env.get(key)
|
||||
env[key] = "{}{}{}".format(path, separator, previous) if previous else path
|
||||
|
||||
def _set_driver_runtime_env(env, toolchain):
|
||||
driver_library = _find_rustc_driver_library(toolchain)
|
||||
if not driver_library:
|
||||
return
|
||||
|
||||
library_dir = driver_library.dirname
|
||||
if driver_library.basename.endswith(".dll"):
|
||||
_prepend_runtime_path(env, "PATH", library_dir, ";")
|
||||
return
|
||||
|
||||
# The lint driver runs in exec configuration. Under remote execution the
|
||||
# exec OS can differ from the Rust target OS, so populate both Unix loader
|
||||
# variables from the located driver library instead of keying off target_os.
|
||||
_prepend_runtime_path(env, "LD_LIBRARY_PATH", library_dir, ":")
|
||||
_prepend_runtime_path(env, "DYLD_LIBRARY_PATH", library_dir, ":")
|
||||
|
||||
def _get_argument_comment_lint_ready_crate_info(target, aspect_ctx):
|
||||
if target.label.workspace_root.startswith("external"):
|
||||
return None
|
||||
|
||||
if aspect_ctx:
|
||||
ignore_tags = [
|
||||
"no_argument_comment_lint",
|
||||
"no-lint",
|
||||
"no_lint",
|
||||
"nolint",
|
||||
]
|
||||
for tag in aspect_ctx.rule.attr.tags:
|
||||
if tag.replace("-", "_").lower() in ignore_tags:
|
||||
return None
|
||||
|
||||
if rust_common.crate_info in target:
|
||||
return target[rust_common.crate_info]
|
||||
if rust_common.test_crate_info in target:
|
||||
return target[rust_common.test_crate_info].crate
|
||||
return None
|
||||
|
||||
def _rust_argument_comment_lint_aspect_impl(target, ctx):
|
||||
if OutputGroupInfo in target and hasattr(target[OutputGroupInfo], "argument_comment_lint_checks"):
|
||||
return []
|
||||
|
||||
crate_info = _get_argument_comment_lint_ready_crate_info(target, ctx)
|
||||
if not crate_info:
|
||||
return []
|
||||
|
||||
toolchain = find_toolchain(ctx)
|
||||
cc_toolchain, feature_configuration = find_cc_toolchain(ctx)
|
||||
|
||||
dep_info, build_info, _ = collect_deps(
|
||||
deps = crate_info.deps.to_list(),
|
||||
proc_macro_deps = crate_info.proc_macro_deps.to_list(),
|
||||
aliases = crate_info.aliases,
|
||||
)
|
||||
|
||||
compile_inputs, out_dir, build_env_files, build_flags_files, linkstamp_outs, ambiguous_libs = collect_inputs(
|
||||
ctx,
|
||||
ctx.rule.file,
|
||||
ctx.rule.files,
|
||||
depset([]),
|
||||
toolchain,
|
||||
cc_toolchain,
|
||||
feature_configuration,
|
||||
crate_info,
|
||||
dep_info,
|
||||
build_info,
|
||||
[],
|
||||
)
|
||||
|
||||
success_marker = ctx.actions.declare_file(
|
||||
ctx.label.name + ".argument_comment_lint.ok",
|
||||
sibling = crate_info.output,
|
||||
)
|
||||
|
||||
args, env = construct_arguments(
|
||||
ctx = ctx,
|
||||
attr = ctx.rule.attr,
|
||||
file = ctx.file,
|
||||
toolchain = toolchain,
|
||||
tool_file = ctx.executable._driver,
|
||||
cc_toolchain = cc_toolchain,
|
||||
feature_configuration = feature_configuration,
|
||||
crate_info = crate_info,
|
||||
dep_info = dep_info,
|
||||
linkstamp_outs = linkstamp_outs,
|
||||
ambiguous_libs = ambiguous_libs,
|
||||
output_hash = determine_output_hash(crate_info.root, ctx.label),
|
||||
rust_flags = [],
|
||||
out_dir = out_dir,
|
||||
build_env_files = build_env_files,
|
||||
build_flags_files = build_flags_files,
|
||||
emit = ["dep-info", "metadata"],
|
||||
skip_expanding_rustc_env = True,
|
||||
)
|
||||
|
||||
if crate_info.is_test:
|
||||
args.rustc_flags.add("--test")
|
||||
|
||||
args.process_wrapper_flags.add("--touch-file", success_marker)
|
||||
args.rustc_flags.add_all(_STRICT_LINT_FLAGS)
|
||||
_set_driver_runtime_env(env, toolchain)
|
||||
|
||||
driver_runfiles = ctx.attr._driver[DefaultInfo].default_runfiles.files
|
||||
action_inputs = depset(
|
||||
transitive = [
|
||||
compile_inputs,
|
||||
driver_runfiles,
|
||||
toolchain.rustc_lib,
|
||||
],
|
||||
)
|
||||
|
||||
ctx.actions.run(
|
||||
executable = toolchain.process_wrapper,
|
||||
inputs = action_inputs,
|
||||
outputs = [success_marker],
|
||||
env = env,
|
||||
tools = [ctx.executable._driver],
|
||||
execution_requirements = {
|
||||
"no-sandbox": "1",
|
||||
},
|
||||
arguments = args.all,
|
||||
mnemonic = "ArgumentCommentLint",
|
||||
progress_message = "ArgumentCommentLint %{label}",
|
||||
toolchain = "@rules_rust//rust:toolchain_type",
|
||||
)
|
||||
|
||||
return [OutputGroupInfo(argument_comment_lint_checks = depset([success_marker]))]
|
||||
|
||||
rust_argument_comment_lint_aspect = aspect(
|
||||
implementation = _rust_argument_comment_lint_aspect_impl,
|
||||
fragments = ["cpp"],
|
||||
attrs = {
|
||||
"_driver": attr.label(
|
||||
default = Label("//tools/argument-comment-lint:argument-comment-lint-driver"),
|
||||
executable = True,
|
||||
cfg = "exec",
|
||||
),
|
||||
} | RUSTC_ATTRS,
|
||||
toolchains = [
|
||||
str(Label("@rules_rust//rust:toolchain_type")),
|
||||
config_common.toolchain_type("@bazel_tools//tools/cpp:toolchain_type", mandatory = False),
|
||||
],
|
||||
required_providers = [
|
||||
[rust_common.crate_info],
|
||||
[rust_common.test_crate_info],
|
||||
],
|
||||
doc = """\
|
||||
Runs argument-comment-lint on Rust targets using Bazel's Rust dependency graph.
|
||||
|
||||
Example:
|
||||
|
||||
```output
|
||||
$ bazel build --config=argument-comment-lint //codex-rs/...
|
||||
```
|
||||
""",
|
||||
)
|
||||
36
tools/argument-comment-lint/list-bazel-targets.sh
Executable file
36
tools/argument-comment-lint/list-bazel-targets.sh
Executable file
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
cd "${repo_root}"
|
||||
|
||||
# Bazel wildcard builds skip manual targets, which misses the internal
|
||||
# `*-unit-tests-bin` rust_test targets generated by `codex_rust_crate()`.
|
||||
# Add only those manual rust_test targets explicitly so inline `#[cfg(test)]`
|
||||
# call sites are linted without pulling in unrelated manual release targets.
|
||||
manual_rust_test_targets="$(
|
||||
./.github/scripts/run-bazel-query-ci.sh \
|
||||
--output=label \
|
||||
-- 'kind("rust_test rule", attr(tags, "manual", //codex-rs/...))'
|
||||
)"
|
||||
if [[ "${RUNNER_OS:-}" != "Windows" ]]; then
|
||||
manual_rust_test_targets="$(printf '%s\n' "${manual_rust_test_targets}" | grep -v -- '-windows-cross-bin$' || true)"
|
||||
fi
|
||||
|
||||
# Convert semantic lint opt-outs into negative target patterns so wildcard
|
||||
# builds do not analyze toolchains used only by those wrappers.
|
||||
excluded_targets="$(
|
||||
./.github/scripts/run-bazel-query-ci.sh \
|
||||
--output=label \
|
||||
-- 'attr(tags, "no-argument-comment-lint", //codex-rs/...)'
|
||||
)"
|
||||
|
||||
# The lint configuration does not register the transitioned Windows toolchain.
|
||||
printf '%s\n' \
|
||||
"//codex-rs/..." \
|
||||
"-//codex-rs/core/tests/remote_env_windows:smoke-test"
|
||||
if [[ -n "${excluded_targets}" ]]; then
|
||||
printf '%s\n' "${excluded_targets}" | sed 's/^/-/'
|
||||
fi
|
||||
printf '%s\n' "${manual_rust_test_targets}"
|
||||
48
tools/argument-comment-lint/run-prebuilt-linter.py
Executable file
48
tools/argument-comment-lint/run-prebuilt-linter.py
Executable file
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from wrapper_common import (
|
||||
build_final_args,
|
||||
exec_command,
|
||||
fetch_packaged_entrypoint,
|
||||
find_packaged_cargo_dylint,
|
||||
normalize_packaged_library,
|
||||
parse_wrapper_args,
|
||||
prefer_rustup_shims,
|
||||
repo_root,
|
||||
set_default_lint_env,
|
||||
)
|
||||
|
||||
|
||||
def main() -> "Never":
|
||||
root = repo_root()
|
||||
parsed = parse_wrapper_args(sys.argv[1:])
|
||||
final_args = build_final_args(parsed, root / "codex-rs" / "Cargo.toml")
|
||||
|
||||
env = os.environ.copy()
|
||||
prefer_rustup_shims(env)
|
||||
set_default_lint_env(env)
|
||||
|
||||
package_entrypoint = fetch_packaged_entrypoint(
|
||||
root / "tools" / "argument-comment-lint" / "argument-comment-lint",
|
||||
env,
|
||||
)
|
||||
cargo_dylint = find_packaged_cargo_dylint(package_entrypoint)
|
||||
library_path = normalize_packaged_library(package_entrypoint)
|
||||
|
||||
command = [str(cargo_dylint), "dylint", "--lib-path", str(library_path)]
|
||||
if not parsed.has_library_selection:
|
||||
command.append("--all")
|
||||
command.extend(final_args)
|
||||
exec_command(command, env)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
43
tools/argument-comment-lint/run.py
Executable file
43
tools/argument-comment-lint/run.py
Executable file
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from wrapper_common import (
|
||||
build_final_args,
|
||||
ensure_source_prerequisites,
|
||||
exec_command,
|
||||
parse_wrapper_args,
|
||||
repo_root,
|
||||
set_default_lint_env,
|
||||
)
|
||||
|
||||
|
||||
def main() -> "Never":
|
||||
root = repo_root()
|
||||
parsed = parse_wrapper_args(sys.argv[1:])
|
||||
final_args = build_final_args(parsed, root / "codex-rs" / "Cargo.toml")
|
||||
|
||||
env = os.environ.copy()
|
||||
ensure_source_prerequisites(env)
|
||||
set_default_lint_env(env)
|
||||
|
||||
command = [
|
||||
"cargo",
|
||||
"dylint",
|
||||
"--path",
|
||||
str(root / "tools" / "argument-comment-lint"),
|
||||
]
|
||||
if not parsed.has_library_selection:
|
||||
command.append("--all")
|
||||
command.extend(final_args)
|
||||
exec_command(command, env)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
3
tools/argument-comment-lint/rust-toolchain
Normal file
3
tools/argument-comment-lint/rust-toolchain
Normal file
@@ -0,0 +1,3 @@
|
||||
[toolchain]
|
||||
channel = "nightly-2026-08-20"
|
||||
components = ["llvm-tools-preview", "rustc-dev", "rust-src"]
|
||||
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"));
|
||||
}
|
||||
136
tools/argument-comment-lint/test_wrapper_common.py
Normal file
136
tools/argument-comment-lint/test_wrapper_common.py
Normal file
@@ -0,0 +1,136 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import wrapper_common
|
||||
|
||||
|
||||
class WrapperCommonTest(unittest.TestCase):
|
||||
def test_defaults_to_workspace_and_all_targets(self) -> None:
|
||||
parsed = wrapper_common.parse_wrapper_args([])
|
||||
final_args = wrapper_common.build_final_args(
|
||||
parsed, Path("/repo/codex-rs/Cargo.toml")
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
final_args,
|
||||
[
|
||||
"--manifest-path",
|
||||
"/repo/codex-rs/Cargo.toml",
|
||||
"--workspace",
|
||||
"--no-deps",
|
||||
"--",
|
||||
"--all-targets",
|
||||
],
|
||||
)
|
||||
|
||||
def test_forwarded_cargo_args_keep_single_separator(self) -> None:
|
||||
parsed = wrapper_common.parse_wrapper_args(
|
||||
["-p", "codex-core", "--", "--tests"]
|
||||
)
|
||||
final_args = wrapper_common.build_final_args(
|
||||
parsed, Path("/repo/codex-rs/Cargo.toml")
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
final_args,
|
||||
[
|
||||
"--manifest-path",
|
||||
"/repo/codex-rs/Cargo.toml",
|
||||
"--no-deps",
|
||||
"-p",
|
||||
"codex-core",
|
||||
"--",
|
||||
"--tests",
|
||||
],
|
||||
)
|
||||
|
||||
def test_fix_does_not_add_all_targets(self) -> None:
|
||||
parsed = wrapper_common.parse_wrapper_args(["--fix", "-p", "codex-core"])
|
||||
final_args = wrapper_common.build_final_args(
|
||||
parsed, Path("/repo/codex-rs/Cargo.toml")
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
final_args,
|
||||
[
|
||||
"--manifest-path",
|
||||
"/repo/codex-rs/Cargo.toml",
|
||||
"--no-deps",
|
||||
"--fix",
|
||||
"-p",
|
||||
"codex-core",
|
||||
],
|
||||
)
|
||||
|
||||
def test_explicit_manifest_and_workspace_are_preserved(self) -> None:
|
||||
parsed = wrapper_common.parse_wrapper_args(
|
||||
[
|
||||
"--manifest-path",
|
||||
"/tmp/custom/Cargo.toml",
|
||||
"--workspace",
|
||||
"--no-deps",
|
||||
"--",
|
||||
"--bins",
|
||||
]
|
||||
)
|
||||
final_args = wrapper_common.build_final_args(
|
||||
parsed, Path("/repo/codex-rs/Cargo.toml")
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
final_args,
|
||||
[
|
||||
"--manifest-path",
|
||||
"/tmp/custom/Cargo.toml",
|
||||
"--workspace",
|
||||
"--no-deps",
|
||||
"--",
|
||||
"--bins",
|
||||
],
|
||||
)
|
||||
|
||||
def test_explicit_package_manifest_does_not_force_workspace(self) -> None:
|
||||
parsed = wrapper_common.parse_wrapper_args(
|
||||
[
|
||||
"--manifest-path",
|
||||
"/tmp/custom/Cargo.toml",
|
||||
]
|
||||
)
|
||||
final_args = wrapper_common.build_final_args(
|
||||
parsed, Path("/repo/codex-rs/Cargo.toml")
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
final_args,
|
||||
[
|
||||
"--no-deps",
|
||||
"--manifest-path",
|
||||
"/tmp/custom/Cargo.toml",
|
||||
"--",
|
||||
"--all-targets",
|
||||
],
|
||||
)
|
||||
|
||||
def test_default_lint_env_promotes_both_strict_lints(self) -> None:
|
||||
env: dict[str, str] = {}
|
||||
|
||||
wrapper_common.set_default_lint_env(env)
|
||||
|
||||
self.assertEqual(
|
||||
env["DYLINT_RUSTFLAGS"],
|
||||
"-D argument-comment-mismatch "
|
||||
"-D uncommented-anonymous-literal-argument "
|
||||
"-A unknown_lints",
|
||||
)
|
||||
self.assertEqual(env["CARGO_INCREMENTAL"], "0")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
9
tools/argument-comment-lint/ui/allow_char_literals.rs
Normal file
9
tools/argument-comment-lint/ui/allow_char_literals.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
#![warn(uncommented_anonymous_literal_argument)]
|
||||
|
||||
fn split_top_level(body: &str, delimiter: char) {
|
||||
let _ = (body, delimiter);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
split_top_level("a|b|c", '|');
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#![warn(argument_comment_mismatch)]
|
||||
#![warn(uncommented_anonymous_literal_argument)]
|
||||
|
||||
struct Builder;
|
||||
|
||||
impl Builder {
|
||||
fn enabled(self, enabled: bool) -> Self {
|
||||
let _ = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
fn retry_count(self, retry_count: usize) -> Self {
|
||||
let _ = retry_count;
|
||||
self
|
||||
}
|
||||
|
||||
fn base_url(self, base_url: Option<String>) -> Self {
|
||||
let _ = base_url;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let _ = Builder.enabled(false).retry_count(3).base_url(None);
|
||||
}
|
||||
9
tools/argument-comment-lint/ui/allow_string_literals.rs
Normal file
9
tools/argument-comment-lint/ui/allow_string_literals.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
#![warn(uncommented_anonymous_literal_argument)]
|
||||
|
||||
fn describe(prefix: &str, suffix: &str) {
|
||||
let _ = (prefix, suffix);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
describe("openai", r"https://api.openai.com/v1");
|
||||
}
|
||||
12
tools/argument-comment-lint/ui/comment_matches.rs
Normal file
12
tools/argument-comment-lint/ui/comment_matches.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
#![warn(argument_comment_mismatch)]
|
||||
|
||||
fn create_openai_url(base_url: Option<String>, retry_count: usize) -> String {
|
||||
let _ = (base_url, retry_count);
|
||||
String::new()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let base_url = Some(String::from("https://api.openai.com"));
|
||||
create_openai_url(base_url, 3);
|
||||
create_openai_url(/*base_url*/ None, 3);
|
||||
}
|
||||
17
tools/argument-comment-lint/ui/comment_matches_multiline.rs
Normal file
17
tools/argument-comment-lint/ui/comment_matches_multiline.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
#![warn(argument_comment_mismatch)]
|
||||
#![warn(uncommented_anonymous_literal_argument)]
|
||||
|
||||
fn run_git_for_stdout(repo_root: &str, args: Vec<&str>, env: Option<&str>) -> String {
|
||||
let _ = (repo_root, args, env);
|
||||
String::new()
|
||||
}
|
||||
|
||||
// Keep the call split across lines so this fixture tests multiline arguments.
|
||||
#[rustfmt::skip]
|
||||
fn main() {
|
||||
let _ = run_git_for_stdout(
|
||||
"/tmp/repo",
|
||||
vec!["rev-parse", "HEAD"],
|
||||
/*env*/ None,
|
||||
);
|
||||
}
|
||||
20
tools/argument-comment-lint/ui/comment_mismatch.rs
Normal file
20
tools/argument-comment-lint/ui/comment_mismatch.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
#![warn(argument_comment_mismatch)]
|
||||
|
||||
fn create_openai_url(base_url: Option<String>) -> String {
|
||||
let _ = base_url;
|
||||
String::new()
|
||||
}
|
||||
|
||||
struct Options;
|
||||
|
||||
impl Options {
|
||||
fn enabled(self, enabled: bool) -> Self {
|
||||
let _ = enabled;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let _ = create_openai_url(/*api_base*/ None);
|
||||
let _ = Options.enabled(/*value*/ false);
|
||||
}
|
||||
23
tools/argument-comment-lint/ui/comment_mismatch.stderr
Normal file
23
tools/argument-comment-lint/ui/comment_mismatch.stderr
Normal file
@@ -0,0 +1,23 @@
|
||||
warning: argument comment `/*api_base*/` does not match parameter `base_url`
|
||||
--> $DIR/comment_mismatch.rs:18:44
|
||||
|
|
||||
LL | let _ = create_openai_url(/*api_base*/ None);
|
||||
| ^^^^
|
||||
|
|
||||
= help: use `/*base_url*/`
|
||||
note: the lint level is defined here
|
||||
--> $DIR/comment_mismatch.rs:1:9
|
||||
|
|
||||
LL | #![warn(argument_comment_mismatch)]
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
warning: argument comment `/*value*/` does not match parameter `enabled`
|
||||
--> $DIR/comment_mismatch.rs:19:39
|
||||
|
|
||||
LL | let _ = Options.enabled(/*value*/ false);
|
||||
| ^^^^^
|
||||
|
|
||||
= help: use `/*enabled*/`
|
||||
|
||||
warning: 2 warnings emitted
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
#![warn(uncommented_anonymous_literal_argument)]
|
||||
|
||||
fn main() {
|
||||
let line = "{\"type\":\"response_item\"}";
|
||||
let _ = line.starts_with('{');
|
||||
let _ = line.find("type");
|
||||
let parts = ["type", "response_item"];
|
||||
let _ = parts.join("\n");
|
||||
}
|
||||
14
tools/argument-comment-lint/ui/multiple_method_arguments.rs
Normal file
14
tools/argument-comment-lint/ui/multiple_method_arguments.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
#![warn(uncommented_anonymous_literal_argument)]
|
||||
|
||||
struct Options;
|
||||
|
||||
impl Options {
|
||||
fn enabled(self, enabled: bool, retry_count: usize) -> Self {
|
||||
let _ = (enabled, retry_count);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let _ = Options.enabled(false, /*retry_count*/ 3);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
warning: anonymous literal-like argument for parameter `enabled`
|
||||
--> $DIR/multiple_method_arguments.rs:13:29
|
||||
|
|
||||
LL | let _ = Options.enabled(false, /*retry_count*/ 3);
|
||||
| ^^^^^ help: prepend the parameter name comment: `/*enabled*/ false`
|
||||
|
|
||||
note: the lint level is defined here
|
||||
--> $DIR/multiple_method_arguments.rs:1:9
|
||||
|
|
||||
LL | #![warn(uncommented_anonymous_literal_argument)]
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
warning: 1 warning emitted
|
||||
|
||||
21
tools/argument-comment-lint/ui/uncommented_literal.rs
Normal file
21
tools/argument-comment-lint/ui/uncommented_literal.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
#![warn(uncommented_anonymous_literal_argument)]
|
||||
|
||||
struct Client;
|
||||
|
||||
impl Client {
|
||||
fn set_flag(&self, enabled: bool) {}
|
||||
}
|
||||
|
||||
fn create_openai_url(base_url: Option<String>, retry_count: usize) -> String {
|
||||
let _ = (base_url, retry_count);
|
||||
String::new()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let client = Client;
|
||||
let _ = create_openai_url(None, 3);
|
||||
client.set_flag(true);
|
||||
|
||||
type OptionalString = Option<String>;
|
||||
let _ = create_openai_url(OptionalString::None, /*retry_count*/ 3);
|
||||
}
|
||||
32
tools/argument-comment-lint/ui/uncommented_literal.stderr
Normal file
32
tools/argument-comment-lint/ui/uncommented_literal.stderr
Normal file
@@ -0,0 +1,32 @@
|
||||
warning: anonymous literal-like argument for parameter `base_url`
|
||||
--> $DIR/uncommented_literal.rs:16:31
|
||||
|
|
||||
LL | let _ = create_openai_url(None, 3);
|
||||
| ^^^^ help: prepend the parameter name comment: `/*base_url*/ None`
|
||||
|
|
||||
note: the lint level is defined here
|
||||
--> $DIR/uncommented_literal.rs:1:9
|
||||
|
|
||||
LL | #![warn(uncommented_anonymous_literal_argument)]
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
warning: anonymous literal-like argument for parameter `retry_count`
|
||||
--> $DIR/uncommented_literal.rs:16:37
|
||||
|
|
||||
LL | let _ = create_openai_url(None, 3);
|
||||
| ^ help: prepend the parameter name comment: `/*retry_count*/ 3`
|
||||
|
||||
warning: anonymous literal-like argument for parameter `enabled`
|
||||
--> $DIR/uncommented_literal.rs:17:21
|
||||
|
|
||||
LL | client.set_flag(true);
|
||||
| ^^^^ help: prepend the parameter name comment: `/*enabled*/ true`
|
||||
|
||||
warning: anonymous literal-like argument for parameter `base_url`
|
||||
--> $DIR/uncommented_literal.rs:20:31
|
||||
|
|
||||
LL | let _ = create_openai_url(OptionalString::None, /*retry_count*/ 3);
|
||||
| ^^^^^^^^^^^^^^^^^^^^ help: prepend the parameter name comment: `/*base_url*/ OptionalString::None`
|
||||
|
||||
warning: 4 warnings emitted
|
||||
|
||||
285
tools/argument-comment-lint/wrapper_common.py
Normal file
285
tools/argument-comment-lint/wrapper_common.py
Normal file
@@ -0,0 +1,285 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from typing import MutableMapping, Sequence
|
||||
|
||||
STRICT_LINTS = [
|
||||
"argument-comment-mismatch",
|
||||
"uncommented-anonymous-literal-argument",
|
||||
]
|
||||
NOISE_LINT = "unknown_lints"
|
||||
TOOLCHAIN_CHANNEL = "nightly-2026-08-20"
|
||||
|
||||
_TARGET_SELECTION_ARGS = {
|
||||
"--all-targets",
|
||||
"--lib",
|
||||
"--bins",
|
||||
"--tests",
|
||||
"--examples",
|
||||
"--benches",
|
||||
"--doc",
|
||||
}
|
||||
_TARGET_SELECTION_PREFIXES = ("--bin=", "--test=", "--example=", "--bench=")
|
||||
_TARGET_SELECTION_WITH_VALUE = {"--bin", "--test", "--example", "--bench"}
|
||||
_NIGHTLY_LIBRARY_PATTERN = re.compile(r"^(.+@nightly-[0-9]{4}-[0-9]{2}-[0-9]{2})-.+$")
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParsedWrapperArgs:
|
||||
lint_args: list[str]
|
||||
cargo_args: list[str]
|
||||
has_manifest_path: bool = False
|
||||
has_package_selection: bool = False
|
||||
has_no_deps: bool = False
|
||||
has_library_selection: bool = False
|
||||
has_cargo_target_selection: bool = False
|
||||
has_fix: bool = False
|
||||
|
||||
|
||||
def repo_root() -> Path:
|
||||
return Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def parse_wrapper_args(argv: Sequence[str]) -> ParsedWrapperArgs:
|
||||
parsed = ParsedWrapperArgs(lint_args=[], cargo_args=[])
|
||||
after_separator = False
|
||||
expect_value: str | None = None
|
||||
|
||||
for arg in argv:
|
||||
if after_separator:
|
||||
parsed.cargo_args.append(arg)
|
||||
if arg in _TARGET_SELECTION_ARGS or arg in _TARGET_SELECTION_WITH_VALUE:
|
||||
parsed.has_cargo_target_selection = True
|
||||
elif arg.startswith(_TARGET_SELECTION_PREFIXES):
|
||||
parsed.has_cargo_target_selection = True
|
||||
continue
|
||||
|
||||
if arg == "--":
|
||||
after_separator = True
|
||||
continue
|
||||
|
||||
parsed.lint_args.append(arg)
|
||||
|
||||
if expect_value is not None:
|
||||
if expect_value == "manifest_path":
|
||||
parsed.has_manifest_path = True
|
||||
elif expect_value == "package_selection":
|
||||
parsed.has_package_selection = True
|
||||
elif expect_value == "library_selection":
|
||||
parsed.has_library_selection = True
|
||||
expect_value = None
|
||||
continue
|
||||
|
||||
if arg == "--manifest-path":
|
||||
expect_value = "manifest_path"
|
||||
elif arg.startswith("--manifest-path="):
|
||||
parsed.has_manifest_path = True
|
||||
elif arg in {"-p", "--package"}:
|
||||
expect_value = "package_selection"
|
||||
elif arg.startswith("--package="):
|
||||
parsed.has_package_selection = True
|
||||
elif arg == "--fix":
|
||||
parsed.has_fix = True
|
||||
elif arg == "--workspace":
|
||||
parsed.has_package_selection = True
|
||||
elif arg == "--no-deps":
|
||||
parsed.has_no_deps = True
|
||||
elif arg in {"--lib", "--lib-path"}:
|
||||
expect_value = "library_selection"
|
||||
elif arg.startswith("--lib=") or arg.startswith("--lib-path="):
|
||||
parsed.has_library_selection = True
|
||||
|
||||
return parsed
|
||||
|
||||
|
||||
def build_final_args(parsed: ParsedWrapperArgs, manifest_path: Path) -> list[str]:
|
||||
final_args: list[str] = []
|
||||
cargo_args = list(parsed.cargo_args)
|
||||
|
||||
if not parsed.has_manifest_path:
|
||||
final_args.extend(["--manifest-path", str(manifest_path)])
|
||||
if not parsed.has_package_selection and not parsed.has_manifest_path:
|
||||
final_args.append("--workspace")
|
||||
if not parsed.has_no_deps:
|
||||
final_args.append("--no-deps")
|
||||
if not parsed.has_fix and not parsed.has_cargo_target_selection:
|
||||
cargo_args.append("--all-targets")
|
||||
final_args.extend(parsed.lint_args)
|
||||
if cargo_args:
|
||||
final_args.extend(["--", *cargo_args])
|
||||
return final_args
|
||||
|
||||
|
||||
def append_env_flag(env: MutableMapping[str, str], key: str, flag: str) -> None:
|
||||
value = env.get(key)
|
||||
if value is None or value == "":
|
||||
env[key] = flag
|
||||
return
|
||||
if flag not in value:
|
||||
env[key] = f"{value} {flag}"
|
||||
|
||||
|
||||
def set_default_lint_env(env: MutableMapping[str, str]) -> None:
|
||||
for strict_lint in STRICT_LINTS:
|
||||
append_env_flag(env, "DYLINT_RUSTFLAGS", f"-D {strict_lint}")
|
||||
append_env_flag(env, "DYLINT_RUSTFLAGS", f"-A {NOISE_LINT}")
|
||||
if not env.get("CARGO_INCREMENTAL"):
|
||||
env["CARGO_INCREMENTAL"] = "0"
|
||||
|
||||
|
||||
def die(message: str) -> "Never":
|
||||
print(message, file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def require_command(name: str, install_message: str | None = None) -> str:
|
||||
executable = shutil.which(name)
|
||||
if executable is None:
|
||||
if install_message is None:
|
||||
die(f"{name} is required but was not found on PATH.")
|
||||
die(install_message)
|
||||
return executable
|
||||
|
||||
|
||||
def run_capture(
|
||||
args: Sequence[str], env: MutableMapping[str, str] | None = None
|
||||
) -> str:
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
list(args),
|
||||
capture_output=True,
|
||||
check=True,
|
||||
env=None if env is None else dict(env),
|
||||
text=True,
|
||||
)
|
||||
except subprocess.CalledProcessError as error:
|
||||
command = shlex.join(str(part) for part in error.cmd)
|
||||
stderr = error.stderr.strip()
|
||||
stdout = error.stdout.strip()
|
||||
output = stderr or stdout
|
||||
if output:
|
||||
die(f"{command} failed:\n{output}")
|
||||
die(f"{command} failed with exit code {error.returncode}")
|
||||
return completed.stdout.strip()
|
||||
|
||||
|
||||
def ensure_source_prerequisites(env: MutableMapping[str, str]) -> None:
|
||||
require_command(
|
||||
"rustup",
|
||||
"argument-comment-lint source wrapper requires rustup.\n"
|
||||
f"Install the {TOOLCHAIN_CHANNEL} toolchain with:\n"
|
||||
f" rustup toolchain install {TOOLCHAIN_CHANNEL} \\\n"
|
||||
" --component llvm-tools-preview \\\n"
|
||||
" --component rustc-dev \\\n"
|
||||
" --component rust-src",
|
||||
)
|
||||
toolchains = run_capture(["rustup", "toolchain", "list"], env=env)
|
||||
if not any(line.startswith(TOOLCHAIN_CHANNEL) for line in toolchains.splitlines()):
|
||||
die(
|
||||
"argument-comment-lint source wrapper requires the "
|
||||
f"{TOOLCHAIN_CHANNEL} toolchain with rustc-dev support.\n"
|
||||
"Install it with:\n"
|
||||
f" rustup toolchain install {TOOLCHAIN_CHANNEL} \\\n"
|
||||
" --component llvm-tools-preview \\\n"
|
||||
" --component rustc-dev \\\n"
|
||||
" --component rust-src"
|
||||
)
|
||||
|
||||
require_command(
|
||||
"cargo-dylint",
|
||||
"argument-comment-lint source wrapper requires cargo-dylint and dylint-link.\n"
|
||||
"Install them with:\n"
|
||||
f" rustup run {TOOLCHAIN_CHANNEL} cargo install --locked "
|
||||
"cargo-dylint@6.3.0 dylint-link@6.3.0",
|
||||
)
|
||||
require_command(
|
||||
"dylint-link",
|
||||
"argument-comment-lint source wrapper requires cargo-dylint and dylint-link.\n"
|
||||
"Install them with:\n"
|
||||
f" rustup run {TOOLCHAIN_CHANNEL} cargo install --locked "
|
||||
"cargo-dylint@6.3.0 dylint-link@6.3.0",
|
||||
)
|
||||
|
||||
|
||||
def prefer_rustup_shims(env: MutableMapping[str, str]) -> None:
|
||||
if env.get("CODEX_ARGUMENT_COMMENT_LINT_SKIP_RUSTUP_SHIMS") == "1":
|
||||
return
|
||||
|
||||
rustup = shutil.which("rustup", path=env.get("PATH"))
|
||||
if rustup is None:
|
||||
return
|
||||
|
||||
rustup_bin_dir = str(Path(rustup).resolve().parent)
|
||||
path_entries = [
|
||||
entry
|
||||
for entry in env.get("PATH", "").split(os.pathsep)
|
||||
if entry and entry != rustup_bin_dir
|
||||
]
|
||||
env["PATH"] = os.pathsep.join([rustup_bin_dir, *path_entries])
|
||||
|
||||
if not env.get("RUSTUP_HOME"):
|
||||
rustup_home = run_capture(["rustup", "show", "home"], env=env)
|
||||
if rustup_home:
|
||||
env["RUSTUP_HOME"] = rustup_home
|
||||
|
||||
|
||||
def fetch_packaged_entrypoint(
|
||||
dotslash_manifest: Path, env: MutableMapping[str, str]
|
||||
) -> Path:
|
||||
require_command(
|
||||
"dotslash",
|
||||
"argument-comment-lint prebuilt wrapper requires dotslash.\n"
|
||||
"Install dotslash, or use:\n"
|
||||
" ./tools/argument-comment-lint/run.py ...",
|
||||
)
|
||||
entrypoint = run_capture(
|
||||
["dotslash", "--", "fetch", str(dotslash_manifest)], env=env
|
||||
)
|
||||
return Path(entrypoint).resolve()
|
||||
|
||||
|
||||
def find_packaged_cargo_dylint(package_entrypoint: Path) -> Path:
|
||||
bin_dir = package_entrypoint.parent
|
||||
cargo_dylint = bin_dir / "cargo-dylint"
|
||||
if not cargo_dylint.is_file():
|
||||
cargo_dylint = bin_dir / "cargo-dylint.exe"
|
||||
if not cargo_dylint.is_file():
|
||||
die(f"bundled cargo-dylint executable not found under {bin_dir}")
|
||||
return cargo_dylint
|
||||
|
||||
|
||||
def normalize_packaged_library(package_entrypoint: Path) -> Path:
|
||||
library_dir = package_entrypoint.parent.parent / "lib"
|
||||
libraries = sorted(path for path in library_dir.glob("*@*") if path.is_file())
|
||||
if not libraries:
|
||||
die(f"no packaged Dylint library found in {library_dir}")
|
||||
if len(libraries) != 1:
|
||||
die(f"expected exactly one packaged Dylint library in {library_dir}")
|
||||
|
||||
library_path = libraries[0]
|
||||
match = _NIGHTLY_LIBRARY_PATTERN.match(library_path.stem)
|
||||
if match is None:
|
||||
return library_path
|
||||
|
||||
temp_dir = Path(tempfile.mkdtemp(prefix="argument-comment-lint."))
|
||||
normalized_library_path = temp_dir / f"{match.group(1)}{library_path.suffix}"
|
||||
shutil.copy2(library_path, normalized_library_path)
|
||||
return normalized_library_path
|
||||
|
||||
|
||||
def exec_command(command: Sequence[str], env: MutableMapping[str, str]) -> "Never":
|
||||
try:
|
||||
completed = subprocess.run(list(command), env=dict(env), check=False)
|
||||
except FileNotFoundError:
|
||||
die(f"{command[0]} is required but was not found on PATH.")
|
||||
raise SystemExit(completed.returncode)
|
||||
73
tools/buildifier
Executable file
73
tools/buildifier
Executable file
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env dotslash
|
||||
|
||||
{
|
||||
"name": "buildifier",
|
||||
"platforms": {
|
||||
"macos-aarch64": {
|
||||
"size": 7565746,
|
||||
"hash": "sha256",
|
||||
"digest": "62836a9667fa0db309b0d91e840f0a3f2813a9c8ea3e44b9cd58187c90bc88ba",
|
||||
"path": "buildifier",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/bazelbuild/buildtools/releases/download/v8.5.1/buildifier-darwin-arm64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"macos-x86_64": {
|
||||
"size": 7737072,
|
||||
"hash": "sha256",
|
||||
"digest": "31de189e1a3fe53aa9e8c8f74a0309c325274ad19793393919e1ca65163ca1a4",
|
||||
"path": "buildifier",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/bazelbuild/buildtools/releases/download/v8.5.1/buildifier-darwin-amd64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"linux-aarch64": {
|
||||
"size": 7483831,
|
||||
"hash": "sha256",
|
||||
"digest": "947bf6700d708026b2057b09bea09abbc3cafc15d9ecea35bb3885c4b09ccd04",
|
||||
"path": "buildifier",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/bazelbuild/buildtools/releases/download/v8.5.1/buildifier-linux-arm64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"size": 7757842,
|
||||
"hash": "sha256",
|
||||
"digest": "887377fc64d23a850f4d18a077b5db05b19913f4b99b270d193f3c7334b5a9a7",
|
||||
"path": "buildifier",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/bazelbuild/buildtools/releases/download/v8.5.1/buildifier-linux-amd64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"windows-aarch64": {
|
||||
"size": 7451648,
|
||||
"hash": "sha256",
|
||||
"digest": "55a276ad8b1ff46be48bf64e432264034ea69a45aa3914e89c1d1936f5c2d85c",
|
||||
"path": "buildifier.exe",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/bazelbuild/buildtools/releases/download/v8.5.1/buildifier-windows-arm64.exe"
|
||||
}
|
||||
]
|
||||
},
|
||||
"windows-x86_64": {
|
||||
"size": 7861760,
|
||||
"hash": "sha256",
|
||||
"digest": "f4ecb9c73de2bc38b845d4ee27668f6248c4813a6647db4b4931a7556052e4e1",
|
||||
"path": "buildifier.exe",
|
||||
"providers": [
|
||||
{
|
||||
"url": "https://github.com/bazelbuild/buildtools/releases/download/v8.5.1/buildifier-windows-amd64.exe"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user