Add support for clang-format

This commit is contained in:
ITAYC0HEN 2021-01-24 16:49:38 +02:00 committed by karliss
parent c82fc5b44f
commit a62f138e2f
8 changed files with 270 additions and 25 deletions

View File

@ -16,7 +16,7 @@
<!-- **Code formatting** <!-- **Code formatting**
Make sure you ran astyle on your code before making the PR. Check our contribution guidelines here: https://cutter.re/docs/code.html --> Make sure you ran clang-format on your code before making the PR. Check our contribution guidelines here: https://cutter.re/docs/code.html -->
**Closing issues** **Closing issues**

6
.gitignore vendored
View File

@ -1,6 +1,3 @@
# Binaries
AStyle*
# OSX files # OSX files
*.DS_Store *.DS_Store
.AppleDouble .AppleDouble
@ -93,9 +90,6 @@ src/out
/breakpad /breakpad
# astyle backup .orig files
*.orig
# Local gdb files # Local gdb files
.gdb_history .gdb_history
.gdbinit .gdbinit

126
_clang-format Normal file
View File

@ -0,0 +1,126 @@
# Do not edit this file! Automatically generated using scripts/udate_clang_format.sh and scripts/_clang_format
# See update_clang_format.sh for more information.
# generated using clang-format version 8.0.0-3~ubuntu16.04.1 (tags/RELEASE_800/final)
---
Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Right
AlignOperands: false
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: true
AfterControlStatement: false
AfterEnum: false
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: true
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: NonAssignment
BreakBeforeBraces: Custom
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 100
CommentPragmas: '^!|^:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 8
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: false
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
- forever
- Q_FOREVER
- QBENCHMARK
- QBENCHMARK_ONCE
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
- Regex: '.*'
Priority: 1
IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: false
IndentPPDirectives: AfterHash
IndentWidth: 4
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 4
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments: true
SortIncludes: false
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: true
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 8
UseTab: Never
...

View File

@ -78,15 +78,20 @@ so your widget refreshes its output when Rizin seek is modified
Coding Style Coding Style
------------ ------------
In general, we follow `the official Qt guidelines <https://wiki.qt.io/Qt_Coding_Style>`__ to In general, we follow a slightly customized version of `the official Qt guidelines <https://wiki.qt.io/Qt_Coding_Style>`__
format the code. If in doubt, you can use `AStyle to format the code. Before sending a pull request, you will need to use `clang-format`<https://clang.llvm.org/docs/ClangFormat.html>`__ (version 8 or newer)
2.06 <https://sourceforge.net/projects/astyle/files/astyle/astyle%202.06/>`__
to format the code. The command line for formatting the code according to format the code. The command line for formatting the code according
to the style is: to the style is:
.. code:: bash .. code:: bash
astyle --project=src/Cutter.astylerc src/filename.cpp clang-format -style=file -i src/filename.cpp
If your changes were done on many files across the codebase, you can use this oneliner to tun ``clang-format`` on the entire 'src' directory:
.. code:: bash
find ./src -regex '.*\.\(cpp\|h\)' -exec clang-format -style=file -i {} \;
In contrast to the official guidelines of Qt, in Cutter we always use curly braces in conditional statements, even if the body of a conditional statement contains only one line. In contrast to the official guidelines of Qt, in Cutter we always use curly braces in conditional statements, even if the body of a conditional statement contains only one line.

View File

@ -53,9 +53,10 @@ The following instructions were made based on version 4.12.4 of Qt Creator. The
- Enter ``CUTTER_USE_BUNDLED_RIZIN`` as a key name and change the value to ON. In earlier Qt Creator versions it is necessary to do this during the initial kit selection and configuration step. - Enter ``CUTTER_USE_BUNDLED_RIZIN`` as a key name and change the value to ON. In earlier Qt Creator versions it is necessary to do this during the initial kit selection and configuration step.
- Click :guilabel:`Apply Configuration Changes`: The configuration should succeed now. In case of errors inspect the output log. - Click :guilabel:`Apply Configuration Changes`: The configuration should succeed now. In case of errors inspect the output log.
Either in :menuselection:`Projects --> Code Style --> C++` or :menuselection:`Tools --> Options --> C++ --> Code Style` select :guilabel:`Qt [built-in]`. It should be selected by default unless you have used Qt Creator for other projects. Cutter Coding style is almost identical to Qt one. This will help with using correct indentation type and basic formatting without running code formatter.
To configure AStyle for formatting a file go to :menuselection:`Tools --> Options --> Beautifier --> Artistic Style`. If necessary, specify the path to astyle executable. The :guilabel:`Use file \*.astylerc defined in project files` option doesn't seem to be working reliably so it is necessary to use :guilabel:`Use specific config file` option. Cutter astyle configuration is stored in :file:`cutter/src/Cutter.astylerc`. Formatting using clang-format
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To configure ``clang-format`` for formatting a file you will need to use the built-in Beautifier plugin. `Follow the instructions <https://doc.qt.io/qtcreator/creator-beautifier.html>`_ on Qt Creator's website to enable the plugin and configure it to run ``clang-format`` when saving a file. In the clang-format options page choose "Use predefined style: File".
Changing CMake configuration Changing CMake configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -98,6 +99,10 @@ After the first configuration :kbd:`Ctrl-Shift-P`/:guilabel:`CMake: Edit CMake C
.. _vscode-debug-setup: .. _vscode-debug-setup:
Formatting using clang-format
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The C/C++ extension we recommended earlier supports source code formatting using clang-format which is included with the extension. Use :kbd:`Ctrl-Shift-I` to format the document or :kbd:`Ctrl-K Ctrl-F` to only format the selection. We recommend to configure auto-formatting via the settings. `Follow the instructions <https://code.visualstudio.com/docs/cpp/cpp-ide#_code-formatting>`_ on VS Code's website.
Building, Running, Debugging Building, Running, Debugging
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Build and running commands are available in the status bar at the bottom and in the Command Palette menu (:kbd:`Ctrl-Shift-P`) named ``CMake: Build F7``, ``CMake: Run Without Debugging Shift+F5``, and ``CMake Debug Ctrl + F5``. Build and running commands are available in the status bar at the bottom and in the Command Palette menu (:kbd:`Ctrl-Shift-P`) named ``CMake: Build F7``, ``CMake: Run Without Debugging Shift+F5``, and ``CMake Debug Ctrl + F5``.
@ -145,6 +150,10 @@ Changing CMake configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Go to :menuselection:`File --> Settings --> Build,Execution,Deployment --> CMake`. CMake options are specified the same way as on command-line ``-DOPTION_NAME=VALUE``. Go to :menuselection:`File --> Settings --> Build,Execution,Deployment --> CMake`. CMake options are specified the same way as on command-line ``-DOPTION_NAME=VALUE``.
Formatting using clang-format
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Clion provides you with an easy way to format files with ``clang-format``. Follow the `documentation <https://www.jetbrains.com/help/clion/clangformat-as-alternative-formatter.html>`_ on their website to learn how to enable formatting with ``clang-format``.
Building, Running, Debugging Building, Running, Debugging
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Follow the `Clion documentation <https://www.jetbrains.com/help/clion/qt-tutorial.html#debug-renderers>`_ for how to configure Qt type debugger renderers. If you are using the MSVC toolchain Follow the `Clion documentation <https://www.jetbrains.com/help/clion/qt-tutorial.html#debug-renderers>`_ for how to configure Qt type debugger renderers. If you are using the MSVC toolchain
@ -189,6 +198,10 @@ Changing CMake configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Open :menuselection:`Project --> CMake Settings`. CMake options can be modified either in graphical table editor, as a command-line flag or by switching to the JSON view. Open :menuselection:`Project --> CMake Settings`. CMake options can be modified either in graphical table editor, as a command-line flag or by switching to the JSON view.
Formatting using clang-format
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Visual Studio supports ``clang-format`` by default so you should not do anything special. It will simple use the existing ``_clang-format`` file from Cutter's root directory. If you wish to configure how and when Visual Studio will use ``clang-format``, you can do this from :menuselection:`Tools --> Options --> Text Editor --> C/C++ --> Formatting`.
Editing Qt .ui files and Qt integration Editing Qt .ui files and Qt integration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
By default Visual Studio will open ``.ui`` files as XML text documents. You can configure to open it using Qt Designer by right-clicking and selecting :guilabel:`Open With...`. By default Visual Studio will open ``.ui`` files as XML text documents. You can configure to open it using Qt Designer by right-clicking and selecting :guilabel:`Open With...`.

94
scripts/_clang-format Normal file
View File

@ -0,0 +1,94 @@
# Copyright (C) 2016 Olivier Goffart <ogoffart@woboq.com>
#
# You may use this file under the terms of the 3-clause BSD license.
# See the file LICENSE from this package for details.
# This is the clang-format configuration style to be used by Qt,
# based on the rules from https://wiki.qt.io/Qt_Coding_Style and
# https://wiki.qt.io/Coding_Conventions
# Cutter specific modifications at the bottom. This file is used to generate
# _clang_format at the root of repository using update_clang_format.sh
---
# Webkit style was loosely based on the Qt style
BasedOnStyle: WebKit
Standard: Cpp11
# Column width is limited to 100 in accordance with Qt Coding Style.
# https://wiki.qt.io/Qt_Coding_Style
# Note that this may be changed at some point in the future.
ColumnLimit: 100
# How much weight do extra characters after the line length limit have.
# PenaltyExcessCharacter: 4
# Disable reflow of qdoc comments: indentation rules are different.
# Translation comments are also excluded.
CommentPragmas: "^!|^:"
# We want a space between the type and the star for pointer types.
PointerBindsToType: false
# We use template< without space.
SpaceAfterTemplateKeyword: false
# We want to break before the operators, but not before a '='.
BreakBeforeBinaryOperators: NonAssignment
# Braces are usually attached, but not after functions or class declarations.
BreakBeforeBraces: Custom
BraceWrapping:
AfterClass: true
AfterControlStatement: false
AfterEnum: false
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: true
AfterUnion: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
# When constructor initializers do not fit on one line, put them each on a new line.
ConstructorInitializerAllOnOneLineOrOnePerLine: true
# Indent initializers by 4 spaces
ConstructorInitializerIndentWidth: 4
# Indent width for line continuations.
ContinuationIndentWidth: 8
# No indentation for namespaces.
NamespaceIndentation: None
# Allow indentation for preprocessing directives (if/ifdef/endif). https://reviews.llvm.org/rL312125
IndentPPDirectives: AfterHash
# Horizontally align arguments after an open bracket.
# The coding style does not specify the following, but this is what gives
# results closest to the existing code.
AlignAfterOpenBracket: true
AlwaysBreakTemplateDeclarations: true
# Ideally we should also allow less short function in a single line, but
# clang-format does not handle that.
AllowShortFunctionsOnASingleLine: Inline
# The coding style specifies some include order categories, but also tells to
# separate categories with an empty line. It does not specify the order within
# the categories. Since the SortInclude feature of clang-format does not
# re-order includes separated by empty lines, the feature is not used.
SortIncludes: false
# macros for which the opening brace stays attached.
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH, forever, Q_FOREVER, QBENCHMARK, QBENCHMARK_ONCE ]
# Break constructor initializers before the colon and after the commas.
BreakConstructorInitializers: BeforeColon
# Cutter additions to Qt's Clang file
# ====================================
# Align the assignment operators of consecutive lines
AlignConsecutiveAssignments: false

25
scripts/update_clang_format.sh Executable file
View File

@ -0,0 +1,25 @@
#!/bin/bash
set -euo pipefail
cd $(dirname "${BASH_SOURCE[0]}")
# Do not replace with newer without dicussing! Intentionally using older clang-format-version.
tool=clang-format-8
# Using full config dumped with older clang format should produce more consistent result when some
# people have slightly newer clang-format. 8 chosen because it is newest version available in Ubuntu 16.04 official repository.
output_file=../_clang-format
# Usage:
# modify scripts/_clang_format
# run this script
# compare the generated outptu with previous version
temp_file=_clang_format_new
echo -e "# Do not edit this file! Automatically generated using scripts/udate_clang_format.sh and scripts/_clang_format\n# See update_clang_format.sh for more information." > $temp_file
echo "# generated using `$tool --version`" >> $temp_file
$tool -style=file -dump-config >> $temp_file
mv $temp_file $output_file
echo Done

View File

@ -1,12 +0,0 @@
--style=kr
--indent=spaces=4
--align-pointer=name
--align-reference=name
--convert-tabs
--attach-namespaces
--max-code-length=100
--max-instatement-indent=120
--pad-header
--pad-oper
--keep-one-line-blocks