diff --git a/.github/workflows/cargo-clippy.yml b/.github/workflows/cargo-clippy.yml new file mode 100644 index 000000000000..424f3ce7e94c --- /dev/null +++ b/.github/workflows/cargo-clippy.yml @@ -0,0 +1,72 @@ +name: Run Clippy on changed Rust code + +# Run on every PR; package selection below skips lint setup for unrelated changes. +on: + pull_request: + push: + branches: + - main + - rc/* + +permissions: + contents: read + +concurrency: + # Cancel superseded PR checks; each push gets its own group so GitHub cannot + # replace an already-pending push run with a newer one. + group: cargo-clippy-${{ github.event_name }}-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + clippy: + runs-on: ubuntu-latest + env: + CARGO_TERM_COLOR: always + steps: + - uses: actions/checkout@v5 + with: + # PRs compare the merge commit with its first parent; pushes need full + # history to compare the event's before SHA across multi-commit pushes. + fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 0 }} + - name: Test package selection + run: python3 -m unittest discover -s misc/scripts/cargo-clippy + - name: Select affected packages + id: select + env: + # Use the PR merge base's actual first parent, or the push's before SHA. + BASE: ${{ github.event_name == 'pull_request' && 'HEAD^1' || github.event.before }} + run: | + packages=$(python3 misc/scripts/cargo-clippy/cargo_clippy.py select --base "$BASE") + echo "packages=$packages" >> "$GITHUB_OUTPUT" + echo "Selected packages: $packages" | tee -a "$GITHUB_STEP_SUMMARY" + - name: Restore Cargo cache + id: cache + if: steps.select.outputs.packages != '[]' + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target + key: cargo-clippy-${{ runner.os }}-${{ hashFiles('rust-toolchain.toml', 'Cargo.lock') }}-${{ github.sha }} + restore-keys: | + cargo-clippy-${{ runner.os }}-${{ hashFiles('rust-toolchain.toml', 'Cargo.lock') }}- + - name: Show stable toolchain and cache + if: steps.select.outputs.packages != '[]' + env: + CACHE_HIT: ${{ steps.cache.outputs.cache-hit }} + run: | + rustup show active-toolchain + cargo clippy --version + echo "Exact cache hit: ${CACHE_HIT:-false}" | tee -a "$GITHUB_STEP_SUMMARY" + - name: Inject ast-generator sources + if: contains(fromJSON(steps.select.outputs.packages), 'ast-generator') + run: bazel run //rust/ast-generator:inject-sources + - name: Clippy + if: steps.select.outputs.packages != '[]' + env: + PACKAGES: ${{ steps.select.outputs.packages }} + # For the unified extractor: skip linking the native Swift shim and + # only check Rust code. + SWIFT_SYNTAX_RS_CHECK_ONLY: "1" + run: python3 misc/scripts/cargo-clippy/cargo_clippy.py lint "$PACKAGES" diff --git a/.github/workflows/cpp-bmn.yml b/.github/workflows/cpp-bmn.yml index 5749de01f8cc..066db1bdca96 100644 --- a/.github/workflows/cpp-bmn.yml +++ b/.github/workflows/cpp-bmn.yml @@ -35,8 +35,6 @@ jobs: run: cargo fmt --check - name: Check run: cargo check - - name: Clippy - run: cargo clippy --all-targets --no-deps -- -D warnings - name: Test run: cargo test diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index c737b20ce73f..89d4d91f561c 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -48,10 +48,6 @@ jobs: - name: Compilation shell: bash run: cargo check - - name: Clippy - shell: bash - run: | - cargo clippy --no-deps -- -D warnings rust-code: runs-on: ubuntu-latest defaults: @@ -67,10 +63,6 @@ jobs: - name: Compilation shell: bash run: cargo check - - name: Clippy - shell: bash - run: | - cargo clippy --no-deps -- -D warnings rust-codegen: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/tree-sitter-extractor-test.yml b/.github/workflows/tree-sitter-extractor-test.yml index 0d866d377514..97ae51ff7c15 100644 --- a/.github/workflows/tree-sitter-extractor-test.yml +++ b/.github/workflows/tree-sitter-extractor-test.yml @@ -43,9 +43,3 @@ jobs: - uses: actions/checkout@v5 - name: Check formatting run: cargo fmt -p extractor-common -p codeql-extractor --check - clippy: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v5 - - name: Run clippy - run: cargo clippy -p extractor-common -p codeql-extractor --no-deps -- -D warnings diff --git a/misc/scripts/cargo-clippy/cargo_clippy.py b/misc/scripts/cargo-clippy/cargo_clippy.py new file mode 100644 index 000000000000..5221e9091db5 --- /dev/null +++ b/misc/scripts/cargo-clippy/cargo_clippy.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Select root-workspace packages affected by a PR or push, and lint them with Clippy.""" + +import argparse +import json +import posixpath +import subprocess +import tomllib +from pathlib import Path + + +# Changes to any of these select every package. +GLOBAL_INPUTS = ( + "Cargo.toml", + "Cargo.lock", + "rust-toolchain.toml", + "clippy.toml", + ".clippy.toml", + ".cargo/", + ".github/workflows/cargo-clippy.yml", + "misc/scripts/cargo-clippy/", +) + +# Inputs read by build scripts outside their package's directory. +EXTERNAL_INPUTS = { + "python/extractor/tsg-python/tsp/src/": "python/extractor/yeast-python", + "misc/bazel/": "rust/ast-generator", + "MODULE.bazel": "rust/ast-generator", + ".bazelrc": "rust/ast-generator", + ".bazelversion": "rust/ast-generator", +} + + +# Read workspace packages and map each package to its path dependents. +def workspace(root): + manifest = tomllib.loads((root / "Cargo.toml").read_text()) + packages = {} + for member in manifest["workspace"]["members"]: + packages[member] = tomllib.loads((root / member / "Cargo.toml").read_text()) + + dependents = {member: set() for member in packages} + for member, package in packages.items(): + tables = [package, *package.get("target", {}).values()] + for table in tables: + for kind in ("dependencies", "dev-dependencies", "build-dependencies"): + for alias, dependency in table.get(kind, {}).items(): + if not isinstance(dependency, dict): + continue + relative_to = member + if dependency.get("workspace"): + dependency = manifest["workspace"]["dependencies"][alias] + relative_to = "" + if isinstance(dependency, dict) and "path" in dependency: + path = posixpath.normpath( + posixpath.join(relative_to, dependency["path"]) + ) + if path in dependents: + dependents[path].add(member) + else: + raise ValueError(f"Path dependency outside workspace: {path}") + return packages, dependents + + +# Select changed packages and their transitive dependents. +def select(root, changed): + packages, dependents = workspace(root) + owners = {**{member + "/": member for member in packages}, **EXTERNAL_INPUTS} + # Longest first, so a nested member owns its files, not its containing package. + prefixes = sorted(owners, key=len, reverse=True) + affected = set() + for path in changed: + if path.startswith(GLOBAL_INPUTS): + return sorted(package["package"]["name"] for package in packages.values()) + for prefix in prefixes: + if path.startswith(prefix): + affected.add(owners[prefix]) + break + + pending = list(affected) + while pending: + for member in dependents[pending.pop()] - affected: + affected.add(member) + pending.append(member) + return sorted(packages[member]["package"]["name"] for member in affected) + + +# List files changed since the PR base or push's before revision. +def changed_files(root, base): + if base in ("0" * 40, "0" * 64): + # A newly created branch has no previous tree, so select everything. + return ["Cargo.toml"] + if subprocess.run( + ["git", "cat-file", "-e", base + "^{commit}"], + cwd=root, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ).returncode: + # A force-push may leave the event's previous commit unavailable locally. + return ["Cargo.toml"] + return subprocess.check_output( + ["git", "diff", "--name-only", "--no-renames", "-z", base, "HEAD"], + cwd=root, + ).decode().split("\0") + + +# Run Clippy on the selected packages and return its exit code. +def lint(packages): + args = ["cargo", "clippy", "--locked", "--all-targets", "--no-deps"] + for package in packages: + args.extend(["--package", package]) + return subprocess.run([*args, "--", "-D", "warnings"]).returncode + + +# Parse the command and dispatch selection or linting. +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + select_parser = commands.add_parser( + "select", help="print the affected packages as a JSON list", + ) + select_parser.add_argument( + "--base", required=True, + help="PR merge's first parent, or push event's before SHA (zero for a new branch)", + ) + lint_parser = commands.add_parser("lint", help="run Clippy on the given packages") + lint_parser.add_argument("packages", help="JSON list printed by the select command") + args = parser.parse_args() + root = Path(__file__).resolve().parents[3] + if args.command == "select": + print(json.dumps(select(root, changed_files(root, args.base)))) + else: + raise SystemExit(lint(json.loads(args.packages))) + +if __name__ == "__main__": + main() diff --git a/misc/scripts/cargo-clippy/test_cargo_clippy.py b/misc/scripts/cargo-clippy/test_cargo_clippy.py new file mode 100644 index 000000000000..212dc9acf268 --- /dev/null +++ b/misc/scripts/cargo-clippy/test_cargo_clippy.py @@ -0,0 +1,52 @@ +import unittest +from pathlib import Path + +from cargo_clippy import changed_files, select, workspace + + +ROOT = Path(__file__).resolve().parents[3] + + +class SelectionTests(unittest.TestCase): + def test_unrelated_changes_select_nothing(self): + self.assertEqual(select(ROOT, [ + "README.md", + "rust/ql/test/example/test.rs", + "python/extractor/tsg-python/src/main.rs", + ]), []) + + def test_nested_member_and_reverse_dependencies(self): + self.assertEqual(select(ROOT, ["rust/extractor/src/main.rs"]), ["codeql-rust"]) + self.assertEqual( + select(ROOT, ["rust/extractor/macros/src/lib.rs"]), + ["codeql-rust", "rust-extractor-macros"], + ) + self.assertTrue( + {"extractor-common", "codeql-extractor"} + <= set(select(ROOT, ["shared/extractor-common/src/lib.rs"])) + ) + + def test_external_inputs(self): + self.assertIn( + "yeast-python", + select(ROOT, ["python/extractor/tsg-python/tsp/src/parser.c"]), + ) + self.assertEqual(select(ROOT, ["MODULE.bazel"]), ["ast-generator"]) + + def test_global_inputs_select_everything(self): + packages, _ = workspace(ROOT) + self.assertEqual( + select(ROOT, ["Cargo.lock"]), + sorted(package["package"]["name"] for package in packages.values()), + ) + + def test_missing_base_selects_everything(self): + packages, _ = workspace(ROOT) + self.assertEqual( + select(ROOT, changed_files(ROOT, "f" * 40)), + sorted(package["package"]["name"] for package in packages.values()), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/unified/extractor/src/languages/swift/swift.rs b/unified/extractor/src/languages/swift/swift.rs index eb667fe2a11d..8d43bb61e4eb 100644 --- a/unified/extractor/src/languages/swift/swift.rs +++ b/unified/extractor/src/languages/swift/swift.rs @@ -969,13 +969,13 @@ fn translation_rules() -> Vec> { // trailing closures. rule!( (functionCallExpr - calledExpression: @@rawCallee + calledExpression: @@raw_callee arguments: _* @args trailingClosure: _? @trailing additionalTrailingClosures: _* @additional) => (call_expr - callee: {ctx.in_pattern = false; rawCallee} + callee: {ctx.in_pattern = false; raw_callee} argument: {args} argument: {trailing.map(|trailing| tree!((argument value: {trailing})))} argument: {additional}) @@ -1085,10 +1085,7 @@ fn translation_rules() -> Vec> { pattern: (identifier #{name}) value: { // Expand [x] into [x = x] - match val { - Some(val) => val, - None => tree!((identifier #{name})), - } + val.unwrap_or_else(|| tree!((identifier #{name}))) }) ), // A closure parameter clause (`(x: Int, y)`) unwraps to its parameters. @@ -1766,14 +1763,14 @@ fn translation_rules() -> Vec> { (extensionDecl extensionKeyword: @@kind modifiers: _* @mods - extendedType: @extendedType + extendedType: @extended_type inheritanceClause: (inheritanceClause inheritedTypes: (inheritedType type: @bases)*)? memberBlock: (memberBlock members: _* @members)) => (class_like_declaration modifier: (modifier #{kind}) modifier: {mods} - extension_target: {extendedType} + extension_target: {extended_type} base_type: {bases.into_iter().map(|ty| tree!((base_type type: {ty})))} member: {members}) ), @@ -1784,7 +1781,7 @@ fn translation_rules() -> Vec> { // nest under `signature` (as for `functionDecl`). rule!( (initializerDecl - initKeyword: @@initK + initKeyword: @@init_k modifiers: _* @mods signature: (functionSignature parameterClause: (functionParameterClause parameters: _* @params)) @@ -1792,20 +1789,20 @@ fn translation_rules() -> Vec> { => (constructor_declaration modifier: {mods} - name_node: (identifier #{initK}) + name_node: (identifier #{init_k}) parameter: {params} body: {body}) ), rule!( (initializerDecl - initKeyword: @@initK + initKeyword: @@init_k modifiers: _* @mods signature: (functionSignature parameterClause: (functionParameterClause parameters: _* @params))) => (constructor_declaration modifier: {mods} - name_node: (identifier #{initK}) + name_node: (identifier #{init_k}) parameter: {params} body: (block)) ), diff --git a/unified/swift-syntax-rs/README.md b/unified/swift-syntax-rs/README.md index 587802f73bd1..2d2fea6d178d 100644 --- a/unified/swift-syntax-rs/README.md +++ b/unified/swift-syntax-rs/README.md @@ -164,6 +164,11 @@ cargo test The first build compiles `swift-syntax` and can take several minutes. +For Rust-only checks, use `SWIFT_SYNTAX_RS_CHECK_ONLY=1 cargo clippy` (or `cargo +check`) to skip building the native Swift shim. Do not set this variable for +`cargo build`, `cargo test` or `cargo run` as they need the native library at +link time. + ## Regenerating the extractor node types After updating the pinned swift-syntax version, regenerate the unified diff --git a/unified/swift-syntax-rs/build.rs b/unified/swift-syntax-rs/build.rs index 29908d2ac448..b2c6bf6a0239 100644 --- a/unified/swift-syntax-rs/build.rs +++ b/unified/swift-syntax-rs/build.rs @@ -3,6 +3,7 @@ use std::path::PathBuf; use std::process::Command; fn main() { + println!("cargo:rerun-if-env-changed=SWIFT_SYNTAX_RS_CHECK_ONLY"); let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); let swift_dir = manifest_dir.join("swift"); @@ -21,6 +22,14 @@ fn main() { println!("cargo:rerun-if-changed={}", input.display()); } + // Skip linking the native shim (intended for cargo check and cargo clippy). + if env::var("SWIFT_SYNTAX_RS_CHECK_ONLY").as_deref() == Ok("1") { + println!("cargo:warning=skipping the Swift FFI build (SWIFT_SYNTAX_RS_CHECK_ONLY=1)"); + // Keep the link requirement so this cannot produce a shim-free executable. + println!("cargo:rustc-link-lib=dylib=SwiftSyntaxFFI"); + return; + } + // Build the Swift FFI package as a release dynamic library. // // Degrade gracefully when there is no runnable Swift toolchain. This crate