From 6dc44871f37022ef9f28d79fa54ae4e17488f776 Mon Sep 17 00:00:00 2001 From: Matteo Settenvini Date: Thu, 30 Nov 2023 16:28:00 +0100 Subject: [PATCH] Adjusted version with initial chosen settings --- .clang-format | 260 ++++++++++++++++++++++++++++++++++++++++++++ .clang-tidy | 186 +++++++++++++++++++++++++++---- .vscode/tasks.json | 15 ++- CMakeLists.txt | 23 +++- extras.md | 19 ++++ foo.h | 0 main-unformatted.cc | 78 ++++++++++--- 7 files changed, 534 insertions(+), 47 deletions(-) create mode 100644 extras.md create mode 100644 foo.h diff --git a/.clang-format b/.clang-format index e69de29..44c8b12 100644 --- a/.clang-format +++ b/.clang-format @@ -0,0 +1,260 @@ +--- +IndentWidth: 4 +--- +Language: Cpp + +# Access modifiers go to the same +# level as braces, as for labels. +AccessModifierOffset: -4 + +AlignAfterOpenBracket: Align + +# Use table-style alignment +# for consistency +AlignArrayOfStructures: Right + +AlignConsecutiveAssignments: None + +AlignConsecutiveBitFields: AcrossEmptyLinesAndComments + +AlignConsecutiveDeclarations: AcrossComments + +AlignConsecutiveMacros: AcrossComments + +AlignEscapedNewlines: Left + +AlignOperands: Align + +AlignTrailingComments: false + +AllowAllArgumentsOnNextLine: true + +AllowAllParametersOfDeclarationOnNextLine: false + +AllowShortEnumsOnASingleLine: false + +AllowShortBlocksOnASingleLine: Never + +AllowShortCaseLabelsOnASingleLine: false + +AllowShortFunctionsOnASingleLine: Empty + +AllowShortLambdasOnASingleLine: Inline + +AllowShortIfStatementsOnASingleLine: Never + +AllowShortLoopsOnASingleLine: false + +AlwaysBreakAfterReturnType: None + +AlwaysBreakBeforeMultilineStrings: false + +AlwaysBreakTemplateDeclarations: Yes + +AttributeMacros: + - __attribute__ + - DSO_EXPORT + +BinPackArguments: true + +BinPackParameters: true + +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: true + AfterNamespace: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: true + BeforeElse: true + BeforeLambdaBody: true + BeforeWhile: true + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false + +BreakBeforeBinaryOperators: None + +BreakBeforeConceptDeclarations: true + +BreakBeforeBraces: Attach + +BreakInheritanceList: AfterComma + +BreakBeforeTernaryOperators: true + +BreakConstructorInitializers: BeforeComma + +BreakStringLiterals: true + +# We chose a limit that fits on a +# 1080p laptop monitor when doing +# diffs. +ColumnLimit: 100 + +# Allow `xgettext --add-comments` to +# extract comments for translators +CommentPragmas: '^ TRANSLATORS: ' + +QualifierAlignment: Leave + +CompactNamespaces: false + +ConstructorInitializerIndentWidth: 4 + +ContinuationIndentWidth: 4 + +Cpp11BracedListStyle: false + +DerivePointerAlignment: false + +EmptyLineAfterAccessModifier: Never + +EmptyLineBeforeAccessModifier: Always + +PackConstructorInitializers: Never + +FixNamespaceComments: true + +ForEachMacros: + - TAILQ_FOREACH + - SLIST_FOREACH + +IfMacros: [] + +IncludeBlocks: Regroup + +IncludeCategories: + - Regex: '^"' + Priority: 1 + CaseSensitive: false + + - Regex: '^- + android-cloexec-* + , boost-use-to-string + , bugprone-assert-side-effect + , bugprone-bad-signal-to-kill-thread + , bugprone-copy-constructor-init + , bugprone-dangling-handle + , bugprone-dynamic-static-initializers + , bugprone-easily-swappable-parameters + , bugprone-exception-escape + , bugprone-fold-init-type + , bugprone-forward-declaration-namespace + , bugprone-forwarding-reference-overload + , bugprone-inaccurate-erase + , bugprone-incorrect-roundings + , bugprone-infinite-loop + , bugprone-integer-division + , bugprone-lambda-function-name + , bugprone-macro-parentheses + , bugprone-macro-repeated-side-effects + , bugprone-misplaced-operator-in-strlen-in-alloc + , bugprone-misplaced-pointer-arithmetic-in-alloc + , bugprone-misplaced-widening-cast + , bugprone-move-forwarding-reference + , bugprone-multiple-statement-macro + , bugprone-not-null-terminated-result + , bugprone-parent-virtual-call + , bugprone-posix-return + , bugprone-redundant-branch-condition + , bugprone-reserved-identifier + , bugprone-signal-handler + , bugprone-sizeof-container + , bugprone-sizeof-expression + , bugprone-spuriously-wake-up-functions + , bugprone-string-constructor + , bugprone-string-integer-assignment + , bugprone-string-literal-with-embedded-nul + , bugprone-stringview-nullptr + , bugprone-suspicious-enum-usage + , bugprone-suspicious-memory-comparison + , bugprone-suspicious-memset-usage + , bugprone-suspicious-semicolon + , bugprone-suspicious-string-compare + , bugprone-swapped-arguments + , bugprone-throw-keyword-missing + , bugprone-undefined-memory-manipulation + , bugprone-undelegated-constructor + , bugprone-unhandled-self-assignment + , bugprone-unused-raii + , bugprone-unused-return-value + , bugprone-use-after-move + , cert-dcl58-cpp + , cert-env33-c + , cert-err33-c + , cert-err34-c + , cert-err58-cpp + , cert-err60-cpp + , cert-flp30-c + , cert-msc50-cpp + , cert-msc51-cpp + , cert-oop57-cpp + , cert-oop58-cpp + , concurrency-mt-unsafe + , cppcoreguidelines-avoid-goto + , cppcoreguidelines-avoid-non-const-global-variables + , clang-diagnostic-* + , clang-analyzer-* + , cppcoreguidelines-init-variables + , cppcoreguidelines-interfaces-global-init + , cppcoreguidelines-macro-usage + , cppcoreguidelines-narrowing-conversions + , cppcoreguidelines-pro-bounds-constant-array-index + , cppcoreguidelines-pro-type-const-cast + , cppcoreguidelines-pro-type-cstyle-cast + , cppcoreguidelines-slicing + , cppcoreguidelines-special-member-functions + , cppcoreguidelines-virtual-class-destructor + , google-build-namespaces + , google-build-using-namespace + , google-default-arguments + , google-explicit-constructor + , google-global-names-in-headers + , google-runtime-int + , google-runtime-operator + , hicpp-exception-baseclass + , misc-definitions-in-headers + , misc-misleading-bidirectional + , misc-misleading-identifier + , misc-misplaced-const + , misc-non-private-member-variables-in-classes + , misc-redundant-expression + , misc-static-assert + , misc-throw-by-value-catch-by-reference + , misc-unconventional-assign-operator + , misc-uniqueptr-reset-release + , misc-unused-parameters + , misc-unused-using-decls + , modernize-avoid-c-arrays + , modernize-concat-nested-namespaces + , modernize-deprecated-headers + , modernize-deprecated-ios-base-aliases + , modernize-loop-convert + , modernize-make-shared + , modernize-make-unique + , modernize-pass-by-value + , modernize-raw-string-literal + , modernize-redundant-void-arg + , modernize-return-braced-init-list + , modernize-shrink-to-fit + , modernize-unary-static-assert + , modernize-use-auto + , modernize-use-bool-literals + , modernize-use-default-member-init + , modernize-use-emplace + , modernize-use-equals-default + , modernize-use-equals-delete + , modernize-use-nodiscard + , modernize-use-noexcept + , modernize-use-nullptr + , modernize-use-override + , modernize-use-trailing-return-type + , modernize-use-transparent-functors + , modernize-use-uncaught-exceptions + , modernize-use-using + , readability-braces-around-statements + , readability-function-size + , readability-non-const-parameter + , readability-magic-numbers + , readability-redundant-string-init + , readability-simplify-boolean-expr + , readability-static-accessed-through-instance + , readability-string-compare + , readability-uniqueptr-delete-release + , readability-use-anyofallof + +# - ONE DAY... cppcoreguidelines-avoid-non-const-global-variables +WarningsAsErrors: >- + cppcoreguidelines-init-variables + , cppcoreguidelines-interfaces-global-init + , cppcoreguidelines-pro-type-cstyle-cast + , cppcoreguidelines-slicing + , cppcoreguidelines-virtual-class-destructor + , google-explicit-constructor + , google-runtime-operator + , misc-definitions-in-headers + , misc-misleading-bidirectional + , misc-misleading-identifier + , misc-non-private-member-variables-in-classes + , misc-throw-by-value-catch-by-reference + , misc-unconventional-assign-operator + , readability-braces-around-statements + HeaderFilterRegex: '' -AnalyzeTemporaryDtors: false -FormatStyle: none -User: matteo +FormatStyle: file:.clang-format CheckOptions: - llvm-else-after-return.WarnOnConditionVariables: 'false' - modernize-loop-convert.MinConfidence: reasonable - modernize-replace-auto-ptr.IncludeStyle: llvm - cert-str34-c.DiagnoseSignedUnsignedCharComparisons: 'false' - google-readability-namespace-comments.ShortNamespaceLines: '10' - cert-err33-c.CheckedFunctions: '::aligned_alloc;::asctime_s;::at_quick_exit;::atexit;::bsearch;::bsearch_s;::btowc;::c16rtomb;::c32rtomb;::calloc;::clock;::cnd_broadcast;::cnd_init;::cnd_signal;::cnd_timedwait;::cnd_wait;::ctime_s;::fclose;::fflush;::fgetc;::fgetpos;::fgets;::fgetwc;::fopen;::fopen_s;::fprintf;::fprintf_s;::fputc;::fputs;::fputwc;::fputws;::fread;::freopen;::freopen_s;::fscanf;::fscanf_s;::fseek;::fsetpos;::ftell;::fwprintf;::fwprintf_s;::fwrite;::fwscanf;::fwscanf_s;::getc;::getchar;::getenv;::getenv_s;::gets_s;::getwc;::getwchar;::gmtime;::gmtime_s;::localtime;::localtime_s;::malloc;::mbrtoc16;::mbrtoc32;::mbsrtowcs;::mbsrtowcs_s;::mbstowcs;::mbstowcs_s;::memchr;::mktime;::mtx_init;::mtx_lock;::mtx_timedlock;::mtx_trylock;::mtx_unlock;::printf_s;::putc;::putwc;::raise;::realloc;::remove;::rename;::scanf;::scanf_s;::setlocale;::setvbuf;::signal;::snprintf;::snprintf_s;::sprintf;::sprintf_s;::sscanf;::sscanf_s;::strchr;::strerror_s;::strftime;::strpbrk;::strrchr;::strstr;::strtod;::strtof;::strtoimax;::strtok;::strtok_s;::strtol;::strtold;::strtoll;::strtoul;::strtoull;::strtoumax;::strxfrm;::swprintf;::swprintf_s;::swscanf;::swscanf_s;::thrd_create;::thrd_detach;::thrd_join;::thrd_sleep;::time;::timespec_get;::tmpfile;::tmpfile_s;::tmpnam;::tmpnam_s;::tss_create;::tss_get;::tss_set;::ungetc;::ungetwc;::vfprintf;::vfprintf_s;::vfscanf;::vfscanf_s;::vfwprintf;::vfwprintf_s;::vfwscanf;::vfwscanf_s;::vprintf_s;::vscanf;::vscanf_s;::vsnprintf;::vsnprintf_s;::vsprintf;::vsprintf_s;::vsscanf;::vsscanf_s;::vswprintf;::vswprintf_s;::vswscanf;::vswscanf_s;::vwprintf_s;::vwscanf;::vwscanf_s;::wcrtomb;::wcschr;::wcsftime;::wcspbrk;::wcsrchr;::wcsrtombs;::wcsrtombs_s;::wcsstr;::wcstod;::wcstof;::wcstoimax;::wcstok;::wcstok_s;::wcstol;::wcstold;::wcstoll;::wcstombs;::wcstombs_s;::wcstoul;::wcstoull;::wcstoumax;::wcsxfrm;::wctob;::wctrans;::wctype;::wmemchr;::wprintf_s;::wscanf;::wscanf_s;' - cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField: 'false' - cert-dcl16-c.NewSuffixes: 'L;LL;LU;LLU' - google-readability-braces-around-statements.ShortStatementLines: '1' - cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic: 'true' - google-readability-namespace-comments.SpacesBeforeComments: '2' - modernize-loop-convert.MaxCopySize: '16' - modernize-pass-by-value.IncludeStyle: llvm - modernize-use-nullptr.NullMacros: 'NULL' - llvm-qualified-auto.AddConstToQualified: 'false' - modernize-loop-convert.NamingStyle: CamelCase - llvm-else-after-return.WarnOnUnfixable: 'false' - google-readability-function-size.StatementThreshold: '800' + - key: readability-function-size.StatementThreshold + value: '60' + - key: readability-function-size.BranchThreshold + value: '15' + - key: readability-function-size.VariableThreshold + value: '15' + - key: readability-function-size.ParameterThreshold + value: '7' + ... diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 17a8058..b763903 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -8,9 +8,20 @@ "targets": [ "format" ], - "group": "build", + "group": { + "kind": "build", + "isDefault": true + }, "problemMatcher": [], - "detail": "CMake template build task" + "detail": "CMake template build task", + "presentation": { + "echo": true, + "reveal": "never", + "focus": false, + "panel": "shared", + "showReuseMessage": true, + "clear": true + } } ] } diff --git a/CMakeLists.txt b/CMakeLists.txt index 417bb79..fad83bb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,17 +2,28 @@ cmake_minimum_required(VERSION 3.22) project(format-demo) -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE INTERNAL "") add_custom_command(OUTPUT main-formatted.cc DEPENDS main-unformatted.cc .clang-format .clang-tidy + BYPRODUCTS main-previous.cc main-diff.cc COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/main-unformatted.cc main-formatted.cc - COMMAND clang-format-16 -i main-formatted.cc - COMMAND clang-tidy-16 --fix --fix-notes -fix-errors - -fix-errors -p ${CMAKE_CURRENT_BINARY_DIR} main-formatted.cc + COMMAND sh -c "test -f main-formatted.cc && ${CMAKE_COMMAND} -E copy main-formatted.cc main-previous.cc" + COMMAND clang-format-14 -i --style=file:${CMAKE_CURRENT_SOURCE_DIR}/.clang-format main-formatted.cc + COMMAND clang-tidy-14 --use-color --fix --fix-notes -fix-errors -p ${CMAKE_CURRENT_BINARY_DIR} main-formatted.cc + COMMAND chmod 0444 main-formatted.cc + # COMMAND sh -c "test -f main-previous.cc && diff -u main-previous.cc main-formatted.cc > main-diff.cc" VERBATIM) + +add_executable(output + ${CMAKE_CURRENT_BINARY_DIR}/main-formatted.cc) + + add_custom_target(format DEPENDS main-formatted.cc COMMENT "Formatting and linting sources" - SOURCES main-unformatted.cc ${CMAKE_CURRENT_BINARY_DIR}/main-formatted.cc - .clang-format .clang-tidy + SOURCES main-unformatted.cc + ${CMAKE_CURRENT_BINARY_DIR}/main-formatted.cc + ${CMAKE_CURRENT_BINARY_DIR}/main-diff.cc + .clang-format + .clang-tidy VERBATIM) diff --git a/extras.md b/extras.md new file mode 100644 index 0000000..99489a3 --- /dev/null +++ b/extras.md @@ -0,0 +1,19 @@ +# Extra rules + +These are rules that can't be captured directly +by clang-format / clang-tidy. + +* Use .hpp for C++ headers, .cpp for C++ files +* \#pragma once +* includes: + - double-quotes for ebee-developed applications + - angular brackets for external projects / system headers + - full relative path from src/ folder + - for libraries: public includes in a folder separated from private includes + - includes ordered by most specific to most generic + - for libraries: mark interfaces available externaly with a `DLL_EXPORT` macro for `__attribute__((visibility("default")))` + +## TODO + +- change xgettext parameter to "--add-comments" to TRANSLATORS in CMakeLists.txt +- remove bundled doctest.h or trompeloeil from project \ No newline at end of file diff --git a/foo.h b/foo.h new file mode 100644 index 0000000..e69de29 diff --git a/main-unformatted.cc b/main-unformatted.cc index 4fee5c9..d5666d9 100644 --- a/main-unformatted.cc +++ b/main-unformatted.cc @@ -1,31 +1,59 @@ +// Includes #include +#include #include #include #include -#include - +#include +#include "foo.h" +#include "main-formatted.hh" #include #include #include -#define BIT_MASK 0xDEADBEAF - -#define MULTILINE_DEF(a,b) if ((a)>2) { \ -auto temp = (b)/2; \ -(b)+=10; \ -someFunctionCall((a),(b));\ +// Macros +#define MAGIC_NUMBER 0xdeadbeef +#define MAGIC_FUNCTION(a,b) while ((a) % (b) != 0) { \ + (a)--; \ } -namespace LevelOneNamespace { - -extern auto someFunctionCall(int16_t, float *) -> int; -namespace LevelTwoNamespace { +namespace ns1 { namespace ns2 { template bool is_sorted(T(&array)[size]) { return std::adjacent_find(array, array + size, std::greater()) == array + size; } + +class C { +public: + C() : a_(1), _b(2), m_c("3") {} + virtual ~C() noexcept { + + } + + auto f() const noexcept -> int { + return static_cast(a_); + } + +private: + double a_; + int _b; + std::string m_c; +}; +} +} + +auto someFunctionCall(int8_t a, +float *b) -> int { + return *b; +} + +struct test { + int a,b; + const char* c; +}; + std::vector returnVector( uint32_t* LongNameForParameter1, double* LongNameForParameter2, const float& LongNameForParameter3, @@ -46,10 +74,18 @@ std::vector returnVector( uint32_t* LongNameForParameter1, a++; } while (false); - return {}; -} +test demo[] = +{ + {56, 23, "hello"}, + {-1, 93463, "world"}, + {7, 5, "!!" } +}; -} + auto b = *LongNameForParameter1 > LongNameForParameter3 + ? 1 + : 2; + + return {}; } int main() { @@ -58,11 +94,21 @@ int main() { int list[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; -using LevelOneNamespace::LevelTwoNamespace::is_sorted; +using ns1::ns2::is_sorted; do { std::random_shuffle(list, list + 9); } while (is_sorted(list)); + switch(43) { + case 42: + { + // indented? + } + break; + case 43: + return 0; + } + int score = 0; do {