SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
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
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
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
 

Kürzlich hochgeladen (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
+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...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 

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