Skip to content

Port C++ linter framework from Python to Rust, launched via 'soldr cargo run' #2488

Closed

Description

@zackees

Summary

Port the FastLED C++ linter framework from Python+re to a Rust crate using the regex crate. Launch the resulting binary via soldr cargo run --release --bin fastled-lint -- <args> so that the build-and-run path is cached and fast on every invocation.

Motivation

The current linter (ci/lint_cpp/ + dispatcher ci/lint_cpp/run_all_checkers.py) is pure Python with the re module. The framework is good — FileContentChecker ABC + MultiCheckerFileProcessor cache (in ci/util/check_files.py) reads each file once and runs every applicable checker against the cached content — but the runtime cost is bounded by Python regex performance and a single-threaded file walk.

Realistic speedup from porting:

  • Rust regex vs Python re: 5–15× per match, DFA + zero per-char allocation.
  • rayon parallelism over MultiCheckerFileProcessor's file loop: another 3–6× on an 8-core box (the Python dispatcher is single-threaded; NUM_WORKERS defined in ci/util/check_files.py:14 is unused for the current path).
  • Combined: 15–90× on full-scan workloads (bash lint --cpp over ~2,265 C++ files).

Single-file mode is already fast (~43× faster per the linter-architecture docs), so the biggest absolute win is on full CI scans, but tightening even single-file invocation latency matters for the Claude Code PostToolUse hook (ci/hooks/lint-on-save.py) that fires on every editor save.

Scope of the port

In scope:

  • New Cargo crate at ci/lint_cpp_rs/ (workspace layout TBD).
  • Rust trait equivalent of FileContentChecker:
    pub trait FileContentChecker: Sync {
        fn should_process_file(&self, path: &Path) -> bool;
        fn check_file_content(&self, file: &FileContent) -> Vec<String>;
    }
  • Rust equivalent of MultiCheckerFileProcessor with the same read-file-once cache, but iterating via files.par_iter() (rayon) instead of the current sequential loop.
  • Scope-based dispatch identical to ci/lint_cpp/run_all_checkers.py:156-321 (create_checkers()): 13 scopes (global, src, fl, platforms, examples, tests, …).
  • A/B test harness: under FL_LINT_AB=1 run both Python and Rust paths on the same input, diff the outputs, fail loudly on any divergence. This is non-negotiable for parity confidence.

Out of scope for v1:

  • LSP integration / language-server mode.
  • Incremental file-watch mode (orthogonal — covered by separate watch tooling).
  • Replacing the Python framework entirely — keep both as parallel "easy path" (Python) and "fast path" (Rust) until rule parity is 100%.

Regex crate choice

Default to plain regex (Rust's DFA-backed implementation, linear-time guarantee, fastest option). Three checkers need handling for negative lookbehind/lookahead, which regex does not support:

  • ci/lint_cpp/bare_allocation_checker.py:51 — (?<!::)(?<!\.)\b(malloc|calloc|realloc)\s*\(
  • ci/lint_cpp/bare_allocation_checker.py:54 — (?<!::)(?<!\.)\bfree\s*\(
  • ci/lint_cpp/static_in_headers_checker.py:47-58 — multi-regex state machine (lookaround-free on inspection, but verify)

Solution: do not pull in fancy-regex. The lookbehind is a 2-byte pre-match check (rejection if the character immediately before the match is : or .). Match with plain regex, then in Rust code inspect the byte at match.start() - 1 and reject if it's one of those characters. This is faster than fancy-regex and preserves the linear-time guarantee.

Everything else (banned_macros, include_paths, serial_printf, using_namespace_fl_in_examples, etc.) ports 1:1.

Launch path — soldr cargo run

The linter binary must be launched via soldr cargo run --release --bin fastled-lint -- <args>, not via direct cargo run and not via a hand-rolled shell wrapper.

Rationale:

  • soldr cargo ... is the FastLED-blessed front door for Rust tooling. It manages the toolchain fetch, sets RUSTC_WRAPPER=zccache for cached rebuilds, and handles cross-platform binary fetching for cargo-watch and friends (per soldr's crates/soldr-fetch/src/known_tools.rs).
  • Once the lazy-rebuild trampoline lands (soldr#342), soldr cargo run will skip cargo's ~80–250ms startup on no-op invocations by reading cargo's .d dep files and a soldr-managed content-hash sidecar. This is the difference between sub-second feedback and a multi-second pause on every editor save through ci/hooks/lint-on-save.py.
  • Until NodeMCU with FastLED #342 lands, soldr cargo run still routes the build through zccache, so the rebuild path stays fast even when the no-op fast-path isn't yet free.

Invocation contract from bash lint:

soldr cargo run --release --bin fastled-lint --manifest-path ci/lint_cpp_rs/Cargo.toml -- <files-or-globs>

The bash lint wrapper in ci/lint.py should construct this invocation; contributors should not invoke cargo run or the binary directly.

Auto-recompile during linter development

For developers actively editing linter rules:

soldr cargo watch -w ci/lint_cpp_rs -s 'soldr cargo build --release --manifest-path ci/lint_cpp_rs/Cargo.toml'

(See soldr#341 for the underlying watcher integration.) When soldr#341 lands, the -x form will also work.

Migration plan

  1. Land ci/lint_cpp_rs/ skeleton with FileContentChecker trait, FileContent, MultiCheckerFileProcessor, and a single trivial checker (serial_printf — pure substring match, no regex). Wire bash lint --cpp --rust to invoke it.
  2. Port 3 more simple checkers: using_namespace_fl_in_examples, banned_macros, include_paths. All lookaround-free, all single-regex.
  3. Add A/B harness: FL_LINT_AB=1 runs Python and Rust on the same input set, diffs results, fails on divergence. Run in CI on every PR.
  4. Port bare_allocation using the manual prev-byte check trick. Verify against ci/lint_cpp/test_bare_allocation_checker.py.
  5. Port static_in_headers (multi-regex state machine).
  6. Batch-port remaining checkers by scope: src → fl → platforms → examples → tests. ~1 hour per simple checker.
  7. Flip default to Rust when A/B parity is 100% over one release cycle. Keep --legacy flag for one release after that, then remove.
  8. Update ci/hooks/lint-on-save.py to invoke soldr cargo run so editor-save linting benefits from the trampoline cache once soldr#342 lands.

Risks and mitigations

  • Build dependency: Rust toolchain becomes required for contributors editing linter rules. Mitigation: soldr handles toolchain fetch transparently; contributors run soldr cargo build and it Just Works. CI ships a pre-built binary so users who don't edit rules don't need Rust installed.
  • Plugin authorship friction: contributors must learn Rust to add new rules. The Python framework is currently very low-barrier (drop a *_checker.py file, write a regex). Mitigation: keep both frameworks coexistent indefinitely. The dispatcher unions both. Easy rules can stay in Python; hot rules move to Rust.
  • Parity drift: silent linter divergence is worse than slow Python. Mitigation: the A/B harness in step 3 is non-negotiable. Add as a required CI check.
  • fancy-regex temptation: do not pull it in. The manual prev-byte check in bare_allocation is trivial and preserves linear-time matching guarantees.
  • Save-time perf without soldr#342: until the trampoline lands, soldr cargo run still pays cargo's ~150ms startup per invocation. On editor saves this is noticeable. Mitigation: either (a) wait for soldr#342, (b) interim wrapper that calls the binary directly when target/release/fastled-lint exists and is newer than ci/lint_cpp_rs/src/**, falling back to soldr cargo run otherwise. Option (b) is a poor-man's trampoline; remove it after NodeMCU with FastLED #342.

Related issues

  • soldr#341 — cargo watch integration with zccache fast path.
  • soldr#342 — Lazy-rebuild trampoline for soldr cargo run (the no-op fast-path needed for editor-save invocations).

Activity

  1. zackees commented on Jun 2, 2026

    @zackees
    MemberAuthor

    Testing and process-management strategy

    For the Rust C++ linter port, use a two-stage parity plan:

    1. Port the implementation first, keep Python tests as the oracle.

      • Keep the current Python unit tests in ci/lint_cpp/test_* during the port; they already encode the edge cases and expected checker semantics.
      • Avoid starting with a PyO3 .pyd that imitates the Python checker classes. The current tests often inspect implementation-specific state such as checker.violations[path]; forcing Rust to expose that shape would couple the Rust design to the old Python object model instead of the production linter contract.
      • Add a Python parity harness that runs the same fixture through the original Python checker and the Rust fastled-lint binary, then compares normalized violations.
      • Give the Rust binary a testable JSON contract, for example:
        soldr cargo run --release --bin fastled-lint --manifest-path ci/lint_cpp_rs/Cargo.toml -- \
          --checker banned_macros --format json path/to/file.h
      • Normalize both implementations to records like:
        [
          {
            "checker": "BannedMacrosChecker",
            "path": "src/fl/example.h",
            "line": 12,
            "message": "..."
          }
        ]
      • Parity should cover should_process_file() filtering, line numbers, suppression comments, checker names, paths, and messages.
      • FL_LINT_AB=1 should run Python and Rust over the same real repo file set and diff canonical JSON results. CI should fail loudly on any divergence.
    2. Port the tests after implementation parity is stable.

      • Extract existing Python cases into shared fixture data: JSON/TOML/YAML, or fixture files plus expected violation records.
      • Rust native tests consume the same fixtures directly.
      • Python tests either remain as compatibility tests or retire per checker once the Rust path is default and parity has held for a release cycle.
      • A PyO3 .pyd bridge can remain an optional later optimization if subprocess overhead becomes a measured test-suite cost, but it should not be the initial correctness bridge.

    For subprocess supervision, use running_process / running-process-core rather than ad-hoc subprocess / std::process wrappers:

    • Python parity harnesses should use the PyPI package running_process when invoking soldr cargo run / fastled-lint.
    • Rust-side orchestration should use running-process-core when Rust needs to spawn or supervise child processes.
    • This matters because the parity and A/B harnesses intentionally run cross-language tools. They need bounded timeouts, captured stdout/stderr, cleanup of process trees, and protection against stuck children, especially on Windows.
    • Timeout or killed-process cases should be structured test failures that include command, cwd, duration, stdout, stderr, and exit status.
  2. moved this from Triage to Done in FastLED Trackeron Jun 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions