Skip to content

Commit e2522d2

Browse files
authored
[RNE Rewrite] chore: add clang-tidy static checks (#1286)
## Description Adds clang-tidy static analysis for the core package's C/C++ sources. Second step of #1271 (clangd setup landed in #1285). Rebased onto `rne-rewrite`, so this is clang-tidy-only. - `.clang-tidy` — a high-signal check set enabled group by group (one commit each): `bugprone-*`, `performance-*`, `clang-analyzer-*`, `cppcoreguidelines-*`, `google-*`, `llvm-*`, `misc-*`, `modernize-*`, `readability-*`. Each group's narrow exclusion list (raw-buffer pointer math, `reinterpret_cast`, `#pragma once`, JSI multiple-inheritance, opinionated/noisy checks) is documented inline with rationale. Analyzes only this package's own `cpp/` headers; third-party is `-isystem`. - `scripts/clang-tidy.sh` + the `lint:cpp` package script — run clang-tidy over `cpp/` using `compile_flags.txt` (the same database clangd uses), failing on any finding. - `.github/workflows/clang-tidy.yml` — CI gate, **dormant** behind the `ENABLE_CLANG_TIDY` repo variable. It provisions headers through the on-demand download flow (`download-libs.js`, #1283) rather than a stub, since clang-tidy needs the ExecuTorch headers to parse the sources. The fixes each group surfaced are split across the per-group commits (scoped `DType` enum, member-init lists, `explicit` ctor, `const`-correctness cleanup, `use-auto`/`emplace`/`cmp_*` modernizations, `NOLINT`s for the intentional cases). Depends on #1283 for `download-libs.js`; enable the workflow once that has merged and a release carrying `headers.tar.gz` exists. The provisioning step sets `RNET_HEADERS_ONLY=1` (clang-tidy needs only headers) — see PR thread re: honoring that flag in `download-libs.js`. Verified locally (Homebrew LLVM clang-tidy): `lint:cpp` is green on all sources and exits non-zero on an injected finding. ### Introduces a breaking change? - [ ] Yes - [x] No ### Type of change - [ ] Bug fix (change which fixes an issue) - [ ] New feature (change which adds functionality) - [ ] Documentation update (improves or adds clarity to existing documentation) - [x] Other (chores, tests, code style improvements etc.) ### Tested on - [ ] iOS - [ ] Android ### Testing instructions 1. Provision `packages/react-native-executorch/third-party/include` and run `yarn install`. 2. From the repo root: `CLANG_TIDY=$(brew --prefix llvm)/bin/clang-tidy yarn workspace react-native-executorch lint:cpp` — expect 0 findings. 3. Confirm the gate has teeth: introduce a bug in a `cpp/` file, e.g. `double r = a / b;` (ints) for `bugprone-integer-division`, and re-run — expect a non-zero exit. Revert afterwards. ### Related issues #1271 ### Checklist - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have updated the documentation accordingly - [x] My changes generate no new warnings
1 parent 95acdba commit e2522d2

19 files changed

Lines changed: 346 additions & 154 deletions

File tree

‎.github/workflows/clang-tidy.yml‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
name: clang-tidy
2+
3+
on:
4+
pull_request:
5+
branches:
6+
- main
7+
- rne-rewrite
8+
paths:
9+
- 'packages/react-native-executorch/cpp/**'
10+
- 'packages/react-native-executorch/.clang-tidy'
11+
- 'packages/react-native-executorch/compile_flags.txt'
12+
- 'packages/react-native-executorch/scripts/clang-tidy.sh'
13+
- '.github/workflows/clang-tidy.yml'
14+
workflow_dispatch:
15+
16+
jobs:
17+
clang-tidy:
18+
runs-on: ubuntu-latest
19+
# Dormant until the on-demand header artifact is published (#1283): clang-tidy
20+
# must parse the sources, which needs the ExecuTorch/torch headers that are not
21+
# committed. Enable by setting the repo variable ENABLE_CLANG_TIDY=true once a
22+
# release carrying headers.tar.gz exists for the package version.
23+
if: ${{ vars.ENABLE_CLANG_TIDY == 'true' }}
24+
steps:
25+
- name: Checkout
26+
uses: actions/checkout@v6
27+
28+
- name: Setup
29+
uses: ./.github/actions/setup
30+
31+
- name: Install clang-tidy
32+
run: |
33+
sudo apt-get update
34+
sudo apt-get install -y clang-tidy
35+
clang-tidy --version
36+
37+
- name: Provision ExecuTorch headers
38+
# Reuse the on-demand download flow (#1283). clang-tidy only needs headers
39+
# (it syntax-checks, no linking), so RNET_HEADERS_ONLY fetches just
40+
# headers.tar.gz; RNET_TARGET avoids host platform auto-detection.
41+
working-directory: packages/react-native-executorch
42+
env:
43+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
44+
RNET_HEADERS_ONLY: '1'
45+
RNET_TARGET: android-arm64-v8a
46+
# TODO(#1291, @msluszniak): drop this override once a real versioned
47+
# release exists. download-libs.js resolves the tag from the package
48+
# version (v${PACKAGE_VERSION} == v0.0.0), but the placeholder 0.0.0 has
49+
# no release; headers.tar.gz currently lives only on the test pre-release.
50+
RNET_BASE_URL: https://github.com/software-mansion/react-native-executorch/releases/download/v0.0.0-rewrite-libs-test
51+
run: node scripts/download-libs.js
52+
53+
- name: Run clang-tidy
54+
run: yarn workspace react-native-executorch lint:cpp

‎CONTRIBUTING.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,20 @@ don't conflict. clangd discovers `compile_flags.txt`/`.clangd` automatically fro
7979
open file's directory. If you produce a `compile_commands.json` from a native build,
8080
clangd will prefer it — it's gitignored and takes precedence over `compile_flags.txt`.
8181

82+
## clang-tidy
83+
84+
`packages/react-native-executorch/.clang-tidy` adds a conservative, high-signal set of
85+
static checks (bugprone / performance / clang-analyzer) on top of the same database. The
86+
clangd extension surfaces these inline; you can also run them from the command line:
87+
88+
```
89+
yarn workspace react-native-executorch lint:cpp # all C++ sources
90+
CLANG_TIDY=$(brew --prefix llvm)/bin/clang-tidy yarn workspace react-native-executorch lint:cpp
91+
```
92+
93+
It needs the same provisioned headers as clangd. Suppress an intentional, reviewed finding
94+
with a commented `// NOLINTNEXTLINE(check-name)` rather than loosening the shared config.
95+
8296
# Creating a Pull Request
8397

8498
Before writing any code reach out to us to make sure no one is currently working on it, you can always open an issue first.
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# clang-tidy configuration for the react-native-executorch C/C++ sources.
2+
#
3+
# A high-signal set focused on correctness/performance bugs and modern C++
4+
# guidelines (issue #1271). Check groups are enabled one at a time and the
5+
# findings fixed; it is expected to stay green on our own code.
6+
#
7+
# clang-tidy reads the include flags / standard / defines from compile_flags.txt
8+
# (the same database clangd uses), so it needs the same prerequisites: a provisioned
9+
# third-party/include and `yarn install`. The clangd extension also surfaces these
10+
# checks inline in the editor.
11+
#
12+
# Excluded checks (incompatible with a native tensor/buffer library that interops
13+
# with ExecuTorch over raw pointers, or purely opinionated):
14+
# pro-bounds-pointer-arithmetic / -avoid-unchecked-container-access /
15+
# -constant-array-index — raw buffer pointer math and hot-loop indexing are by design
16+
# pro-type-reinterpret-cast — type-erased byte buffers cast to typed pointers
17+
# avoid-magic-numbers / easily-swappable-parameters / enum-size — opinionated / noisy
18+
# llvm-header-guard — the project uses #pragma once by convention
19+
# llvm-prefer-static-over-anonymous-namespace — anonymous namespaces are a valid
20+
# idiom here and also hold the helpers' shared types/constants
21+
# misc-include-cleaner — ExecuTorch umbrella headers make it misreport includes
22+
# misc-multiple-inheritance — the JSI HostObject + enable_shared_from_this pattern
23+
# misc-non-private-member-variables-in-classes — HostObjects are deliberate public
24+
# data carriers read across extensions
25+
# misc-const-correctness — applied once as a cleanup, but too aggressive to gate on
26+
# (it flags RAII lock guards as const-able); not enforced going forward
27+
# modernize-use-trailing-return-type — the codebase uses traditional return types
28+
# modernize-return-braced-init-list — `return {…}` hides the (JSI) return type
29+
# readability-identifier-length — short names (i, rt, h, w, …) are idiomatic here
30+
# readability-math-missing-parentheses — flags standard array-offset arithmetic
31+
# readability-function-cognitive-complexity — the JSI get() dispatchers and the
32+
# image/tensor kernels are inherently above the threshold
33+
# readability-uppercase-literal-suffix — the codebase uses lowercase (1.0f) consistently
34+
# readability-magic-numbers — opinionated (same as cppcoreguidelines-avoid-magic-numbers)
35+
Checks: >
36+
-*,
37+
bugprone-*,
38+
performance-*,
39+
clang-analyzer-*,
40+
cppcoreguidelines-*,
41+
google-*,
42+
llvm-*,
43+
misc-*,
44+
modernize-*,
45+
readability-*,
46+
-bugprone-easily-swappable-parameters,
47+
-performance-enum-size,
48+
-cppcoreguidelines-pro-bounds-pointer-arithmetic,
49+
-cppcoreguidelines-pro-bounds-avoid-unchecked-container-access,
50+
-cppcoreguidelines-pro-bounds-constant-array-index,
51+
-cppcoreguidelines-pro-type-reinterpret-cast,
52+
-cppcoreguidelines-avoid-magic-numbers,
53+
-llvm-header-guard,
54+
-llvm-prefer-static-over-anonymous-namespace,
55+
-misc-include-cleaner,
56+
-misc-multiple-inheritance,
57+
-misc-non-private-member-variables-in-classes,
58+
-misc-const-correctness,
59+
-modernize-use-trailing-return-type,
60+
-modernize-return-braced-init-list,
61+
-readability-identifier-length,
62+
-readability-math-missing-parentheses,
63+
-readability-function-cognitive-complexity,
64+
-readability-uppercase-literal-suffix,
65+
-readability-magic-numbers
66+
67+
# Restrict analysis to this package's own cpp/ tree. Anchored on the full package
68+
# path so it can never match an unrelated directory that merely contains "cpp"
69+
# (e.g. third-party/.../abseil-cpp/, or another package's cpp/). Third-party headers
70+
# are also -isystem in compile_flags.txt, so clang-tidy does not analyze them anyway.
71+
HeaderFilterRegex: 'packages/react-native-executorch/cpp/.*\.(h|hpp)$'
72+
73+
# Treat findings as warnings (CI decides failure via --warnings-as-errors).
74+
WarningsAsErrors: ''

‎packages/react-native-executorch/.clangd‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ CompileFlags:
2525
- -Wconversion
2626
- -Wsign-conversion
2727
- -Wdouble-promotion
28+
# compile_flags.txt forces -xc++, so clangd opens headers as main-file
29+
# translation units and flags their `#pragma once`. Silence that
30+
# editor-only false positive (the guard is correct when the header is
31+
# #included normally, which is the only context clang-tidy ever sees).
32+
- -Wno-pragma-once-outside-header
2833

2934
Diagnostics:
3035
# ExecuTorch/torch rely heavily on umbrella headers, which clangd's include

‎packages/react-native-executorch/cpp/RnExecutorch.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
#include "extensions/cv/install.h"
99
#endif
1010

11-
using namespace facebook;
11+
namespace jsi = facebook::jsi;
1212

1313
namespace rnexecutorch {
1414
void install(jsi::Runtime &jsiRuntime) {

‎packages/react-native-executorch/cpp/core/dtype.cpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ size_t elementSize(DType dtype) {
5454
switch (dtype) {
5555
case DType::uint8:
5656
return 1;
57+
// NOLINTNEXTLINE(bugprone-branch-clone): int32 and float32 are both 4 bytes; the identical branches are intentional.
5758
case DType::int32:
5859
return 4;
5960
case DType::float32:

‎packages/react-native-executorch/cpp/core/dtype.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
#include <string>
66

77
namespace rnexecutorch::core::types {
8-
enum DType {
8+
enum class DType {
99
uint8,
1010
int32,
1111
float32

‎packages/react-native-executorch/cpp/core/model.cpp‎

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ jsi::Value ModelHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &name) {
4343

4444
auto methodNames = self->etModule_->method_names();
4545
if (!methodNames.ok()) {
46-
std::string errorMsg = executorch::runtime::to_string(methodNames.error());
46+
const std::string errorMsg = executorch::runtime::to_string(methodNames.error());
4747
throw jsi::JSError(rt, "getMethodNames: Failed to get method names: " + errorMsg);
4848
}
4949

@@ -82,15 +82,15 @@ jsi::Value ModelHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &name) {
8282
auto methodName = args[0].asString(rt).utf8(rt);
8383
auto methodMeta = self->etModule_->method_meta(methodName);
8484
if (!methodMeta.ok()) {
85-
std::string errorMsg = executorch::runtime::to_string(methodMeta.error());
85+
const std::string errorMsg = executorch::runtime::to_string(methodMeta.error());
8686
throw jsi::JSError(rt, "getMethodMeta: Failed to get method meta: " + errorMsg);
8787
}
8888

8989
auto inputTagsArray = jsi::Array(rt, methodMeta->num_inputs());
9090
for (size_t i = 0; i < methodMeta->num_inputs(); ++i) {
9191
auto tag = methodMeta->input_tag(i);
9292
if (!tag.ok()) {
93-
std::string errorMsg = executorch::runtime::to_string(tag.error());
93+
const std::string errorMsg = executorch::runtime::to_string(tag.error());
9494
throw jsi::JSError(rt, "getMethodMeta: Failed to get input tag for input " + std::to_string(i) + ": " + errorMsg);
9595
}
9696
inputTagsArray.setValueAtIndex(rt, i, jsi::String::createFromUtf8(rt, executorch::runtime::tag_to_string(tag.get())));
@@ -100,7 +100,7 @@ jsi::Value ModelHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &name) {
100100
for (size_t i = 0; i < methodMeta->num_outputs(); ++i) {
101101
auto tag = methodMeta->output_tag(i);
102102
if (!tag.ok()) {
103-
std::string errorMsg = executorch::runtime::to_string(tag.error());
103+
const std::string errorMsg = executorch::runtime::to_string(tag.error());
104104
throw jsi::JSError(rt, "getMethodMeta: Failed to get output tag for output " + std::to_string(i) + ": " + errorMsg);
105105
}
106106
outputTagsArray.setValueAtIndex(rt, i, jsi::String::createFromUtf8(rt, executorch::runtime::tag_to_string(tag.get())));
@@ -110,7 +110,7 @@ jsi::Value ModelHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &name) {
110110
for (size_t i = 0; i < methodMeta->num_backends(); ++i) {
111111
auto backendName = methodMeta->get_backend_name(i);
112112
if (!backendName.ok()) {
113-
std::string errorMsg = executorch::runtime::to_string(backendName.error());
113+
const std::string errorMsg = executorch::runtime::to_string(backendName.error());
114114
throw jsi::JSError(rt, "getMethodMeta: Failed to get backend name for backend " + std::to_string(i) + ": " + errorMsg);
115115
}
116116
usesBackendMap.setProperty(rt, backendName.get(), methodMeta->uses_backend(backendName.get()));
@@ -123,7 +123,7 @@ jsi::Value ModelHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &name) {
123123
jsTensorMeta.setProperty(rt, "nbytes", static_cast<double>(tensorMeta.nbytes()));
124124

125125
try {
126-
std::string dtypeStr = rnexecutorch::core::types::toString(rnexecutorch::core::types::fromScalarType(tensorMeta.scalar_type()));
126+
const std::string dtypeStr = rnexecutorch::core::types::toString(rnexecutorch::core::types::fromScalarType(tensorMeta.scalar_type()));
127127
jsTensorMeta.setProperty(rt, "dtype", jsi::String::createFromUtf8(rt, dtypeStr));
128128
} catch (const std::exception &) {
129129
jsTensorMeta.setProperty(rt, "dtype", jsi::String::createFromUtf8(rt, "not supported"));
@@ -142,7 +142,7 @@ jsi::Value ModelHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &name) {
142142
for (size_t i = 0; i < methodMeta->num_inputs(); ++i) {
143143
auto tensorMeta = methodMeta->input_tensor_meta(i);
144144
if (!tensorMeta.ok()) {
145-
std::string errorMsg = executorch::runtime::to_string(tensorMeta.error());
145+
const std::string errorMsg = executorch::runtime::to_string(tensorMeta.error());
146146
throw jsi::JSError(rt, "getMethodMeta: Failed to get tensor meta for input " + std::to_string(i) + ": " + errorMsg);
147147
}
148148
inputTensorMetaArray.setValueAtIndex(rt, i, tensorMetaToJS(rt, tensorMeta.get()));
@@ -152,7 +152,7 @@ jsi::Value ModelHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &name) {
152152
for (size_t i = 0; i < methodMeta->num_outputs(); ++i) {
153153
auto tensorMeta = methodMeta->output_tensor_meta(i);
154154
if (!tensorMeta.ok()) {
155-
std::string errorMsg = executorch::runtime::to_string(tensorMeta.error());
155+
const std::string errorMsg = executorch::runtime::to_string(tensorMeta.error());
156156
throw jsi::JSError(rt, "getMethodMeta: Failed to get tensor meta for output " + std::to_string(i) + ": " + errorMsg);
157157
}
158158
outputTensorMetaArray.setValueAtIndex(rt, i, tensorMetaToJS(rt, tensorMeta.get()));
@@ -207,14 +207,14 @@ jsi::Value ModelHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &name) {
207207
auto inputsArray = args[1].asObject(rt).asArray(rt);
208208

209209
if (!methodMeta.ok()) {
210-
std::string errorMsg = executorch::runtime::to_string(methodMeta.error());
210+
const std::string errorMsg = executorch::runtime::to_string(methodMeta.error());
211211
throw jsi::JSError(rt, "execute: Failed to get method meta for '" + methodName + "': " + errorMsg);
212212
}
213213

214214
if (inputsArray.size(rt) != methodMeta->num_inputs()) {
215-
std::string errorMsg = "execute: Incorrect size for inputs: got " +
216-
std::to_string(inputsArray.size(rt)) +
217-
", expected " + std::to_string(methodMeta->num_inputs());
215+
const std::string errorMsg = "execute: Incorrect size for inputs: got " +
216+
std::to_string(inputsArray.size(rt)) +
217+
", expected " + std::to_string(methodMeta->num_inputs());
218218
throw jsi::JSError(rt, errorMsg);
219219
}
220220

@@ -252,7 +252,7 @@ jsi::Value ModelHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &name) {
252252
auto val = inputsArray.getValueAtIndex(rt, i);
253253

254254
if (!tag.ok()) {
255-
std::string errorMsg = executorch::runtime::to_string(tag.error());
255+
const std::string errorMsg = executorch::runtime::to_string(tag.error());
256256
throw jsi::JSError(rt, "execute: Failed to get input tag for inputs[" +
257257
std::to_string(i) + "]: " + errorMsg);
258258
}
@@ -290,7 +290,7 @@ jsi::Value ModelHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &name) {
290290
auto tensorMeta = methodMeta->input_tensor_meta(i);
291291

292292
if (!tensorMeta.ok()) {
293-
std::string errorMsg = executorch::runtime::to_string(tensorMeta.error());
293+
const std::string errorMsg = executorch::runtime::to_string(tensorMeta.error());
294294
throw jsi::JSError(rt, "execute: Failed to get tensor meta for inputs[" +
295295
std::to_string(i) + "]: " + errorMsg);
296296
}
@@ -343,7 +343,7 @@ jsi::Value ModelHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &name) {
343343
#endif
344344

345345
if (!result.ok()) {
346-
std::string errorMsg = executorch::runtime::to_string(result.error());
346+
const std::string errorMsg = executorch::runtime::to_string(result.error());
347347
throw jsi::JSError(rt, "execute: Method '" + methodName + "' execution failed: " + errorMsg +
348348
". This may be due to missing required backends - use getMethodMeta()" +
349349
" to check required backends and getExecuTorchRegisteredBackends()" +
@@ -392,7 +392,7 @@ jsi::Value ModelHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &name) {
392392
auto tensorMeta = methodMeta->output_tensor_meta(index);
393393

394394
if (!tensorMeta.ok()) {
395-
std::string errorMsg = executorch::runtime::to_string(tensorMeta.error());
395+
const std::string errorMsg = executorch::runtime::to_string(tensorMeta.error());
396396
throw jsi::JSError(rt, "execute: Failed to get tensor meta for output at index " +
397397
std::to_string(index) + ": " + errorMsg);
398398
}
@@ -467,7 +467,7 @@ std::vector<facebook::jsi::PropNameID> ModelHostObject::getPropertyNames(jsi::Ru
467467
}
468468

469469
void install_loadModel(jsi::Runtime &rt, jsi::Object &module) {
470-
auto name = "loadModel";
470+
const auto *name = "loadModel";
471471
auto fnBody = [](jsi::Runtime &rt, const jsi::Value & /*thisVal*/, const jsi::Value *args, size_t count) -> jsi::Value {
472472
if (count != 1) {
473473
throw jsi::JSError(rt, "loadModel: Usage: loadModel(arg0)");
@@ -482,7 +482,7 @@ void install_loadModel(jsi::Runtime &rt, jsi::Object &module) {
482482

483483
auto error = modelInstance->etModule_->load();
484484
if (!modelInstance->etModule_->is_loaded()) {
485-
std::string errorMsg = executorch::runtime::to_string(error);
485+
const std::string errorMsg = executorch::runtime::to_string(error);
486486
throw jsi::JSError(rt, "loadModel: Failed to load model: " + errorMsg);
487487
}
488488

‎packages/react-native-executorch/cpp/core/model.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ class ModelHostObject : public facebook::jsi::HostObject, public std::enable_sha
2424
std::unique_ptr<executorch::extension::Module> etModule_;
2525
std::mutex mutex_;
2626

27-
ModelHostObject(const std::string &modelPath);
27+
explicit ModelHostObject(const std::string &modelPath);
2828

2929
facebook::jsi::Value get(facebook::jsi::Runtime &rt, const facebook::jsi::PropNameID &name) override;
3030
std::vector<facebook::jsi::PropNameID> getPropertyNames(facebook::jsi::Runtime &rt) override;

0 commit comments

Comments
 (0)