Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions .github/workflows/cargo-clippy.yml
Original file line number Diff line number Diff line change
@@ -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"
2 changes: 0 additions & 2 deletions .github/workflows/cpp-bmn.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 0 additions & 8 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand Down
6 changes: 0 additions & 6 deletions .github/workflows/tree-sitter-extractor-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
135 changes: 135 additions & 0 deletions misc/scripts/cargo-clippy/cargo_clippy.py
Original file line number Diff line number Diff line change
@@ -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()
52 changes: 52 additions & 0 deletions misc/scripts/cargo-clippy/test_cargo_clippy.py
Original file line number Diff line number Diff line change
@@ -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()
21 changes: 9 additions & 12 deletions unified/extractor/src/languages/swift/swift.rs
Original file line number Diff line number Diff line change
Expand Up @@ -969,13 +969,13 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
// 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})
Expand Down Expand Up @@ -1085,10 +1085,7 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
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.
Expand Down Expand Up @@ -1766,14 +1763,14 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
(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})
),
Expand All @@ -1784,28 +1781,28 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
// nest under `signature` (as for `functionDecl`).
rule!(
(initializerDecl
initKeyword: @@initK
initKeyword: @@init_k
modifiers: _* @mods
signature: (functionSignature
parameterClause: (functionParameterClause parameters: _* @params))
body: (codeBlock) @body)
=>
(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))
),
Expand Down
5 changes: 5 additions & 0 deletions unified/swift-syntax-rs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading