SlideShare a Scribd company logo
1 of 25
Download to read offline
Hands on clang-format
Adding (n)one feature at a time
Kai Wolf
kai-wolf.me
March 31, 2016
A quick reality check - please raise hand
• We have a (living) coding style guide
• We use code generators
• We do (semi-)automatized refactoring (clang-tidy, Clang
MapReduce, awk | grep | sed, ...)
• We use automatic code formatting tools
• We utilize pre/post-commit hooks for these kind of stuff
2 / 25
Why is it important?
• Inconsistent formatting distracts the reader
• Formatting code by hand is tedious
• Nobody reads the style guide anyways
• Automatic/large scale refactoring not feasible without automatic
code formatting
3 / 25
Lots of auto formatting tools available
Artistic Style (AStyle)
Works. Focuses only on indentation and brace/bracket placement
Uncrustify
Many, many, many rules (around ~200). Might take a whole day to
adjust to own style guide.
GNU indent
Works most of the time (see OpenSSL Blog - CodeReformat Finished).
Basically has three presets available (Ansi, GNU, K&R). Indent needs
to know about all types used within the code.
GC GreatCode
Intrusive formatting rules. May break your code.
4 / 25
How to use clang-format
$ cat bbox.cpp
cv::Rect BoundingBox::getBoundingRect(const cv::Mat& Binary) const {
assert(Binary.channels() == 1);
using Contour = std::vector<cv::Point>;
std::vector<Contour> contours;
auto hierarchy = std::vector<cv::Vec4i>();
cv::findContours(Binary.clone(),contours,hierarchy,CV_RETR_TREE,
CV_CHAIN_APPROX_SIMPLE);
auto result = *std::max_element(contours.begin(), contours.end(),
[](Contour a, Contour b) {
return cv::contourArea(a) < cv::contourArea(b);});
return cv::boundingRect(cv::Mat(result));}
5 / 25
How to use clang-format
$ cat bbox.cpp | clang-format -style=’{BasedOnStyle: Google, IndentWidth: 4’
cv::Rect BoundingBox::getBoundingRect(const cv::Mat& Binary) const {
assert(Binary.channels() == 1);
using Contour = std::vector<cv::Point>;
std::vector<Contour> contours;
auto hierarchy = std::vector<cv::Vec4i>();
cv::findContours(Binary.clone(), contours, hierarchy, CV_RETR_TREE,
CV_CHAIN_APPROX_SIMPLE);
auto result = *std::max_element(
contours.begin(), contours.end(), [](Contour a, Contour b) {
return cv::contourArea(a) < cv::contourArea(b);
});
return cv::boundingRect(cv::Mat(result));
}
6 / 25
How to use clang-format
Plugins available for Vi, Emacs, Visual Studio etc. Custom integration
almost always possible. For example: CLion
7 / 25
How to use clang-format
There are many deliberate options available:
Release Number of options
clang-format v3.5 53
clang-format v3.6 62
clang-format v3.7 65
clang-format v3.8 70
clang-format v3.9 75
8 / 25
Motivating example
Say for example, our style guide suggests that this:
void foo(int a, int b, double c, const char* str);
should be formatted like this:
void foo(int a,int b,double c,const char* str);
9 / 25
What does clang-format offer here?
10 / 25
Let’s try to fix that
In order to start hacking we need the llvm repository with the
following subprojects:
$ export LLVM_SVN=http://llvm.org/svn/llvm-project
$ svn co ${LLVM_SVN}/llvm/trunk llvm
$ cd llvm/tools
$ svn co ${LLVM_SVN}/cfe/trunk clang
$ cd ../projects
$ svn co ${LLVM_SVN}/test-suite/trunk test-suite
$ cd ../tools/clang/tools
$ svn co ${LLVM_SVN}/clang-tools-extra/trunk extra
11 / 25
Navigate around the code base
Formatting rules for clang-format are located in
llvm/tools/clang/lib/Format/
Unittests are located in
llvm/tools/clang/unittests/Format/
Frontend for clang-format
$ cd llvm/tools/clang # clang subproject
$ cat tools/clang-format/ClangFormat.cpp
int main(int argc, const char **argv) {
...
for (unsigned i = 0; i < FileNames.size(); ++i)
Error |= clang::format::format(FileNames[i]);
12 / 25
clang::format::format
static bool format(StringRef FileName) {
...
if (fillRanges(Code.get(), Ranges))
return true;
...
FormatStyle FormatStyle =
getStyle(Style, AssumedFileName, FallbackStyle)
...
Replacements Replaces =
sortIncludes(FormatStyle, Code, Ranges)
...
Replacements FormatChanges =
reformat(FormatStyle, ChangedCode, Ranges)
}
13 / 25
clang::format::reformat
...
for (const tooling::Range &Range : Ranges) {
SourceLocation Start =
StartOfFile.getLocWithOffset(
Range.getOffset());
SourceLocation End =
Start.getLocWithOffset(Range.getLength());
CharRanges.push_back(
CharSourceRange::getCharRange(Start, End));
}
return reformat(Style, SourceMgr, ID, CharRanges,
IncompleteFormat);
14 / 25
clang::format::reformat
FormatStyle Expanded = expandPresets(Style);
if (Expanded.DisableFormat)
return tooling::Replacements();
Formatter formatter(Expanded, SourceMgr, ID,
Ranges);
return formatter.format(IncompleteFormat);
15 / 25
clang::tok::TokenKind
void foo(int a, int b);
UnwrappedLineParser Parser();
-> readTokens();
-> parseFile();
-> parseLevel();
-> parseStructuralElement();
<- AnnotatedLines
0 kw_void
1 identifier
2 l_param
3 kw_int
4 identifier
5 comma
6 kw_int
7 identifier
8 r_param
9 semi
16 / 25
clang::format
For each annotated line (TokenAnnotator.cpp):
void TokenAnnotator::
calculateFormattingInformation(
AnnotatedLine &Line);
Fortunately not much to do here for us:
bool TokenAnnotator::spaceRequiredBetween(
const AnnotatedLine &Line,
const FormatToken &Left,
const FormatToken &Right);
17 / 25
Our patch (excerpt)
Format.h
/// b If c true, spaces will be inserted between
/// function parameters.
bool SpacesBetweenFunctionParameters;
TokenAnnotator.cpp
...
if (Right.is(TT_OverloadedOperatorLParen))
return Style.SpaceBeforeParens ==
FormatStyle::SBPO_Always;
if (Left.is(tok::comma))
// return true;
return Style.SpacesBetweenFunctionParameters;
if (Right.is(tok::comma))
return false;
18 / 25
Preparing the patch
Tests are looking good.
TEST_F(FormatTest, SpacesBetweenFunctionParameters) {
FormatStyle Spaces = getLLVMStyle();
Spaces.SpacesBetweenFunctionParameters = false;
verifyFormat("void foo(int a);", Spaces);
verifyFormat("void foo(int a,double b);", Spaces);
verifyFormat("void foo(int a,double b,char c);", Spaces);
Spaces.SpacesBetweenFunctionParameters = true;
verifyFormat("void foo(int a, double b);", Spaces);
verifyFormat("void foo(int a, double b, char c);", Spaces);
}
By the way: If you manage an open source project, make sure to
explain how to contribute!
• How to get going? How to submit your patch?
• Who decides what patches are accepted?
• Who should review your patch?
• What should be included in the patch? (doc, unittests, full file
context diff etc.)
19 / 25
Oops..
http://reviews.llvm.org/D16765
20 / 25
That paragraph must be new...
21 / 25
Yes, indeed
By the time I’ve created the patch, clang-format 3.7 was the current
release
22 / 25
Yet there’s hope..
https://github.com/hankhank/clang
23 / 25
I don’t always accidentally...
24 / 25
25 / 25

More Related Content

What's hot

LAS16-501: Introduction to LLVM - Projects, Components, Integration, Internals
LAS16-501: Introduction to LLVM - Projects, Components, Integration, InternalsLAS16-501: Introduction to LLVM - Projects, Components, Integration, Internals
LAS16-501: Introduction to LLVM - Projects, Components, Integration, InternalsLinaro
 
GCC Compiler as a Performance Testing tool for C programs
GCC Compiler as a Performance Testing tool for C programsGCC Compiler as a Performance Testing tool for C programs
GCC Compiler as a Performance Testing tool for C programsDaniel Ilunga
 
Whirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerWhirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerGonçalo Gomes
 
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...AboutYouGmbH
 
Virtual platform
Virtual platformVirtual platform
Virtual platformsean chen
 
Semi-Automatic Code Cleanup with Clang-Tidy
Semi-Automatic Code Cleanup with Clang-TidySemi-Automatic Code Cleanup with Clang-Tidy
Semi-Automatic Code Cleanup with Clang-TidyMarkus Werle
 
LLVM Compiler - Link Time Optimization
LLVM Compiler - Link Time OptimizationLLVM Compiler - Link Time Optimization
LLVM Compiler - Link Time OptimizationVivek Pansara
 
Claire protorpc
Claire protorpcClaire protorpc
Claire protorpcFan Robbin
 
Code quality par Simone Civetta
Code quality par Simone CivettaCode quality par Simone Civetta
Code quality par Simone CivettaCocoaHeads France
 
Debugging of (C)Python applications
Debugging of (C)Python applicationsDebugging of (C)Python applications
Debugging of (C)Python applicationsRoman Podoliaka
 
Fast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCFast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCTim Burks
 
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...CanSecWest
 
Review: Apitrace and Vogl
Review: Apitrace and VoglReview: Apitrace and Vogl
Review: Apitrace and VoglGao Yunzhong
 
Debugging Python with gdb
Debugging Python with gdbDebugging Python with gdb
Debugging Python with gdbRoman Podoliaka
 

What's hot (20)

LAS16-501: Introduction to LLVM - Projects, Components, Integration, Internals
LAS16-501: Introduction to LLVM - Projects, Components, Integration, InternalsLAS16-501: Introduction to LLVM - Projects, Components, Integration, Internals
LAS16-501: Introduction to LLVM - Projects, Components, Integration, Internals
 
Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!
 
LLVM
LLVMLLVM
LLVM
 
Where is LLVM Being Used Today?
Where is LLVM Being Used Today? Where is LLVM Being Used Today?
Where is LLVM Being Used Today?
 
GCC, GNU compiler collection
GCC, GNU compiler collectionGCC, GNU compiler collection
GCC, GNU compiler collection
 
A Close Look at ARM Code Size
A Close Look at ARM Code SizeA Close Look at ARM Code Size
A Close Look at ARM Code Size
 
GCC Compiler as a Performance Testing tool for C programs
GCC Compiler as a Performance Testing tool for C programsGCC Compiler as a Performance Testing tool for C programs
GCC Compiler as a Performance Testing tool for C programs
 
Whirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerWhirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic Linker
 
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
 
Virtual platform
Virtual platformVirtual platform
Virtual platform
 
Semi-Automatic Code Cleanup with Clang-Tidy
Semi-Automatic Code Cleanup with Clang-TidySemi-Automatic Code Cleanup with Clang-Tidy
Semi-Automatic Code Cleanup with Clang-Tidy
 
MinGw Compiler
MinGw CompilerMinGw Compiler
MinGw Compiler
 
LLVM Compiler - Link Time Optimization
LLVM Compiler - Link Time OptimizationLLVM Compiler - Link Time Optimization
LLVM Compiler - Link Time Optimization
 
Claire protorpc
Claire protorpcClaire protorpc
Claire protorpc
 
Code quality par Simone Civetta
Code quality par Simone CivettaCode quality par Simone Civetta
Code quality par Simone Civetta
 
Debugging of (C)Python applications
Debugging of (C)Python applicationsDebugging of (C)Python applications
Debugging of (C)Python applications
 
Fast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCFast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPC
 
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...
 
Review: Apitrace and Vogl
Review: Apitrace and VoglReview: Apitrace and Vogl
Review: Apitrace and Vogl
 
Debugging Python with gdb
Debugging Python with gdbDebugging Python with gdb
Debugging Python with gdb
 

Similar to Hands on clang-format

07 140430-ipp-languages used in llvm during compilation
07 140430-ipp-languages used in llvm during compilation07 140430-ipp-languages used in llvm during compilation
07 140430-ipp-languages used in llvm during compilationAdam Husár
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기경주 전
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerApache Traffic Server
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerAndrey Karpov
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Sylvain Wallez
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoRodolfo Carvalho
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGlobalLogic Ukraine
 
Inside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGInside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGSylvain Wallez
 
Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Miłosz Sobczak
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedPascal-Louis Perez
 
BarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformationsBarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformationswalkmod
 

Similar to Hands on clang-format (20)

Bluespec @waseda
Bluespec @wasedaBluespec @waseda
Bluespec @waseda
 
07 140430-ipp-languages used in llvm during compilation
07 140430-ipp-languages used in llvm during compilation07 140430-ipp-languages used in llvm during compilation
07 140430-ipp-languages used in llvm during compilation
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
 
Into The Box 2018 - CBT
Into The Box 2018 - CBTInto The Box 2018 - CBT
Into The Box 2018 - CBT
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
Go. why it goes v2
Go. why it goes v2Go. why it goes v2
Go. why it goes v2
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii Shapoval
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
CP Handout#2
CP Handout#2CP Handout#2
CP Handout#2
 
Inside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGInside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUG
 
Cs30 New
Cs30 NewCs30 New
Cs30 New
 
Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 
BarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformationsBarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformations
 

Recently uploaded

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 

Recently uploaded (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Hands on clang-format

  • 1. Hands on clang-format Adding (n)one feature at a time Kai Wolf kai-wolf.me March 31, 2016
  • 2. A quick reality check - please raise hand • We have a (living) coding style guide • We use code generators • We do (semi-)automatized refactoring (clang-tidy, Clang MapReduce, awk | grep | sed, ...) • We use automatic code formatting tools • We utilize pre/post-commit hooks for these kind of stuff 2 / 25
  • 3. Why is it important? • Inconsistent formatting distracts the reader • Formatting code by hand is tedious • Nobody reads the style guide anyways • Automatic/large scale refactoring not feasible without automatic code formatting 3 / 25
  • 4. Lots of auto formatting tools available Artistic Style (AStyle) Works. Focuses only on indentation and brace/bracket placement Uncrustify Many, many, many rules (around ~200). Might take a whole day to adjust to own style guide. GNU indent Works most of the time (see OpenSSL Blog - CodeReformat Finished). Basically has three presets available (Ansi, GNU, K&R). Indent needs to know about all types used within the code. GC GreatCode Intrusive formatting rules. May break your code. 4 / 25
  • 5. How to use clang-format $ cat bbox.cpp cv::Rect BoundingBox::getBoundingRect(const cv::Mat& Binary) const { assert(Binary.channels() == 1); using Contour = std::vector<cv::Point>; std::vector<Contour> contours; auto hierarchy = std::vector<cv::Vec4i>(); cv::findContours(Binary.clone(),contours,hierarchy,CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); auto result = *std::max_element(contours.begin(), contours.end(), [](Contour a, Contour b) { return cv::contourArea(a) < cv::contourArea(b);}); return cv::boundingRect(cv::Mat(result));} 5 / 25
  • 6. How to use clang-format $ cat bbox.cpp | clang-format -style=’{BasedOnStyle: Google, IndentWidth: 4’ cv::Rect BoundingBox::getBoundingRect(const cv::Mat& Binary) const { assert(Binary.channels() == 1); using Contour = std::vector<cv::Point>; std::vector<Contour> contours; auto hierarchy = std::vector<cv::Vec4i>(); cv::findContours(Binary.clone(), contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); auto result = *std::max_element( contours.begin(), contours.end(), [](Contour a, Contour b) { return cv::contourArea(a) < cv::contourArea(b); }); return cv::boundingRect(cv::Mat(result)); } 6 / 25
  • 7. How to use clang-format Plugins available for Vi, Emacs, Visual Studio etc. Custom integration almost always possible. For example: CLion 7 / 25
  • 8. How to use clang-format There are many deliberate options available: Release Number of options clang-format v3.5 53 clang-format v3.6 62 clang-format v3.7 65 clang-format v3.8 70 clang-format v3.9 75 8 / 25
  • 9. Motivating example Say for example, our style guide suggests that this: void foo(int a, int b, double c, const char* str); should be formatted like this: void foo(int a,int b,double c,const char* str); 9 / 25
  • 10. What does clang-format offer here? 10 / 25
  • 11. Let’s try to fix that In order to start hacking we need the llvm repository with the following subprojects: $ export LLVM_SVN=http://llvm.org/svn/llvm-project $ svn co ${LLVM_SVN}/llvm/trunk llvm $ cd llvm/tools $ svn co ${LLVM_SVN}/cfe/trunk clang $ cd ../projects $ svn co ${LLVM_SVN}/test-suite/trunk test-suite $ cd ../tools/clang/tools $ svn co ${LLVM_SVN}/clang-tools-extra/trunk extra 11 / 25
  • 12. Navigate around the code base Formatting rules for clang-format are located in llvm/tools/clang/lib/Format/ Unittests are located in llvm/tools/clang/unittests/Format/ Frontend for clang-format $ cd llvm/tools/clang # clang subproject $ cat tools/clang-format/ClangFormat.cpp int main(int argc, const char **argv) { ... for (unsigned i = 0; i < FileNames.size(); ++i) Error |= clang::format::format(FileNames[i]); 12 / 25
  • 13. clang::format::format static bool format(StringRef FileName) { ... if (fillRanges(Code.get(), Ranges)) return true; ... FormatStyle FormatStyle = getStyle(Style, AssumedFileName, FallbackStyle) ... Replacements Replaces = sortIncludes(FormatStyle, Code, Ranges) ... Replacements FormatChanges = reformat(FormatStyle, ChangedCode, Ranges) } 13 / 25
  • 14. clang::format::reformat ... for (const tooling::Range &Range : Ranges) { SourceLocation Start = StartOfFile.getLocWithOffset( Range.getOffset()); SourceLocation End = Start.getLocWithOffset(Range.getLength()); CharRanges.push_back( CharSourceRange::getCharRange(Start, End)); } return reformat(Style, SourceMgr, ID, CharRanges, IncompleteFormat); 14 / 25
  • 15. clang::format::reformat FormatStyle Expanded = expandPresets(Style); if (Expanded.DisableFormat) return tooling::Replacements(); Formatter formatter(Expanded, SourceMgr, ID, Ranges); return formatter.format(IncompleteFormat); 15 / 25
  • 16. clang::tok::TokenKind void foo(int a, int b); UnwrappedLineParser Parser(); -> readTokens(); -> parseFile(); -> parseLevel(); -> parseStructuralElement(); <- AnnotatedLines 0 kw_void 1 identifier 2 l_param 3 kw_int 4 identifier 5 comma 6 kw_int 7 identifier 8 r_param 9 semi 16 / 25
  • 17. clang::format For each annotated line (TokenAnnotator.cpp): void TokenAnnotator:: calculateFormattingInformation( AnnotatedLine &Line); Fortunately not much to do here for us: bool TokenAnnotator::spaceRequiredBetween( const AnnotatedLine &Line, const FormatToken &Left, const FormatToken &Right); 17 / 25
  • 18. Our patch (excerpt) Format.h /// b If c true, spaces will be inserted between /// function parameters. bool SpacesBetweenFunctionParameters; TokenAnnotator.cpp ... if (Right.is(TT_OverloadedOperatorLParen)) return Style.SpaceBeforeParens == FormatStyle::SBPO_Always; if (Left.is(tok::comma)) // return true; return Style.SpacesBetweenFunctionParameters; if (Right.is(tok::comma)) return false; 18 / 25
  • 19. Preparing the patch Tests are looking good. TEST_F(FormatTest, SpacesBetweenFunctionParameters) { FormatStyle Spaces = getLLVMStyle(); Spaces.SpacesBetweenFunctionParameters = false; verifyFormat("void foo(int a);", Spaces); verifyFormat("void foo(int a,double b);", Spaces); verifyFormat("void foo(int a,double b,char c);", Spaces); Spaces.SpacesBetweenFunctionParameters = true; verifyFormat("void foo(int a, double b);", Spaces); verifyFormat("void foo(int a, double b, char c);", Spaces); } By the way: If you manage an open source project, make sure to explain how to contribute! • How to get going? How to submit your patch? • Who decides what patches are accepted? • Who should review your patch? • What should be included in the patch? (doc, unittests, full file context diff etc.) 19 / 25
  • 21. That paragraph must be new... 21 / 25
  • 22. Yes, indeed By the time I’ve created the patch, clang-format 3.7 was the current release 22 / 25
  • 24. I don’t always accidentally... 24 / 25