Skip to content

Instantly share code, notes, and snippets.

@jimhester
Last active May 25, 2021 15:51
Show Gist options
  • Save jimhester/815770df32463818e9bc2c9eee96f3d1 to your computer and use it in GitHub Desktop.
Save jimhester/815770df32463818e9bc2c9eee96f3d1 to your computer and use it in GitHub Desktop.
Static analysis for R packages

Static analysis tools for C and C++ code

The compiler has built in static analysis! Use warnings!

usethis::edit_r_makevars()

CFLAGS += -Wall -Wpedantic -Wextra -fdiagnostics-color=always

  • for C++

CXXFLAGS += -Wall -Wpedantic -Wextra -fdiagnostics-color=always

  • for C++11

CXX11FLAGS += -Wall -Wpedantic -Wextra -fdiagnostics-color=always

-Weverything (clang only), just to see if there are any useful ones (don't leave on, some incompatible with each other)

Facebook infer

infer -- make
infer explore

Compiles the code, so you need to clean before re-running

Optional checkers

  • purity
  • detect pure functions
  • loop hoisting
  • runtime complexity analysis
  • quandary - potentially detects unsafe data access, SQL injections, untrusted files, untrusted URI, cross site scripting
  • thread safety - thread data races (though C / C++ support seems limited)

bear

ʕ·ᴥ·ʔ Build EAR - listens to your build commands to generate a compilation database for clang based tools.

# You may have to remove ccache executables from your PATH prior to running bear

bear -- make # newer versions
bear make # older versions
bear -- R CMD INSTALL .
bear -- Rscript -e 'pkgload::load_all()'

Run infer with database

infer --compilation-database compile_commands.json

clang tidy

run-clang-tidy -q
run-clang-tidy -q -checks ,-*DeprecatedOrUnsafeBufferHandling
run-clang-tidy -q -checks modernize*,-modernize-use-trailing-return-type
run-clang-tidy -q -checks performance*

# https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
run-clang-tidy -q -checks cppcoreguidelines-* 

run-clang-tidy -q -checks readability-*

scan-build

scan-build-10 --use-cc=/usr/bin/clang make
/usr/local/Cellar/llvm/11.0.0_1/bin/scan-view ~/p/scan-build-2021-05-20-195654-1024-1

clang-format

Project specific configuration in .clang-format files.

Many editors support automatically running on save (not RStudio unfortuantely)

git integration at https://github.com/llvm/llvm-project/blob/main/clang/tools/clang-format/git-clang-format

Run with git clang-format and it will format your current files

Could also put in a git precommit hook

clangd

Examples

  • brio - eba6052 - file handle leak (infer), memory leak (clang-tidy)
  • readr - 081ee75f662606ff3145bf - clang-tidy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment