Format.cpp 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491
  1. //===--- Format.cpp - Format C++ code -------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// \file
  10. /// This file implements functions declared in Format.h. This will be
  11. /// split into separate files as we go.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Format/Format.h"
  15. #include "AffectedRangeManager.h"
  16. #include "BreakableToken.h"
  17. #include "ContinuationIndenter.h"
  18. #include "DefinitionBlockSeparator.h"
  19. #include "FormatInternal.h"
  20. #include "FormatTokenLexer.h"
  21. #include "NamespaceEndCommentsFixer.h"
  22. #include "QualifierAlignmentFixer.h"
  23. #include "SortJavaScriptImports.h"
  24. #include "TokenAnalyzer.h"
  25. #include "TokenAnnotator.h"
  26. #include "UnwrappedLineFormatter.h"
  27. #include "UnwrappedLineParser.h"
  28. #include "UsingDeclarationsSorter.h"
  29. #include "WhitespaceManager.h"
  30. #include "clang/Basic/Diagnostic.h"
  31. #include "clang/Basic/DiagnosticOptions.h"
  32. #include "clang/Basic/SourceManager.h"
  33. #include "clang/Lex/Lexer.h"
  34. #include "clang/Tooling/Inclusions/HeaderIncludes.h"
  35. #include "llvm/ADT/STLExtras.h"
  36. #include "llvm/ADT/StringRef.h"
  37. #include "llvm/Support/Allocator.h"
  38. #include "llvm/Support/Debug.h"
  39. #include "llvm/Support/Path.h"
  40. #include "llvm/Support/Regex.h"
  41. #include "llvm/Support/VirtualFileSystem.h"
  42. #include "llvm/Support/YAMLTraits.h"
  43. #include <algorithm>
  44. #include <memory>
  45. #include <mutex>
  46. #include <numeric>
  47. #include <string>
  48. #include <unordered_map>
  49. #define DEBUG_TYPE "format-formatter"
  50. using clang::format::FormatStyle;
  51. LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::RawStringFormat)
  52. namespace llvm {
  53. namespace yaml {
  54. template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
  55. static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
  56. IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
  57. IO.enumCase(Value, "Java", FormatStyle::LK_Java);
  58. IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
  59. IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
  60. IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
  61. IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
  62. IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
  63. IO.enumCase(Value, "CSharp", FormatStyle::LK_CSharp);
  64. IO.enumCase(Value, "Json", FormatStyle::LK_Json);
  65. }
  66. };
  67. template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
  68. static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
  69. IO.enumCase(Value, "c++03", FormatStyle::LS_Cpp03);
  70. IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03); // Legacy alias
  71. IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03); // Legacy alias
  72. IO.enumCase(Value, "c++11", FormatStyle::LS_Cpp11);
  73. IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11); // Legacy alias
  74. IO.enumCase(Value, "c++14", FormatStyle::LS_Cpp14);
  75. IO.enumCase(Value, "c++17", FormatStyle::LS_Cpp17);
  76. IO.enumCase(Value, "c++20", FormatStyle::LS_Cpp20);
  77. IO.enumCase(Value, "Latest", FormatStyle::LS_Latest);
  78. IO.enumCase(Value, "Cpp11", FormatStyle::LS_Latest); // Legacy alias
  79. IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
  80. }
  81. };
  82. template <>
  83. struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {
  84. static void enumeration(IO &IO,
  85. FormatStyle::LambdaBodyIndentationKind &Value) {
  86. IO.enumCase(Value, "Signature", FormatStyle::LBI_Signature);
  87. IO.enumCase(Value, "OuterScope", FormatStyle::LBI_OuterScope);
  88. }
  89. };
  90. template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
  91. static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
  92. IO.enumCase(Value, "Never", FormatStyle::UT_Never);
  93. IO.enumCase(Value, "false", FormatStyle::UT_Never);
  94. IO.enumCase(Value, "Always", FormatStyle::UT_Always);
  95. IO.enumCase(Value, "true", FormatStyle::UT_Always);
  96. IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
  97. IO.enumCase(Value, "ForContinuationAndIndentation",
  98. FormatStyle::UT_ForContinuationAndIndentation);
  99. IO.enumCase(Value, "AlignWithSpaces", FormatStyle::UT_AlignWithSpaces);
  100. }
  101. };
  102. template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
  103. static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
  104. IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
  105. IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
  106. IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
  107. }
  108. };
  109. template <> struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {
  110. static void enumeration(IO &IO, FormatStyle::ShortBlockStyle &Value) {
  111. IO.enumCase(Value, "Never", FormatStyle::SBS_Never);
  112. IO.enumCase(Value, "false", FormatStyle::SBS_Never);
  113. IO.enumCase(Value, "Always", FormatStyle::SBS_Always);
  114. IO.enumCase(Value, "true", FormatStyle::SBS_Always);
  115. IO.enumCase(Value, "Empty", FormatStyle::SBS_Empty);
  116. }
  117. };
  118. template <>
  119. struct ScalarEnumerationTraits<FormatStyle::QualifierAlignmentStyle> {
  120. static void enumeration(IO &IO, FormatStyle::QualifierAlignmentStyle &Value) {
  121. IO.enumCase(Value, "Leave", FormatStyle::QAS_Leave);
  122. IO.enumCase(Value, "Left", FormatStyle::QAS_Left);
  123. IO.enumCase(Value, "Right", FormatStyle::QAS_Right);
  124. IO.enumCase(Value, "Custom", FormatStyle::QAS_Custom);
  125. }
  126. };
  127. template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
  128. static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
  129. IO.enumCase(Value, "None", FormatStyle::SFS_None);
  130. IO.enumCase(Value, "false", FormatStyle::SFS_None);
  131. IO.enumCase(Value, "All", FormatStyle::SFS_All);
  132. IO.enumCase(Value, "true", FormatStyle::SFS_All);
  133. IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
  134. IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly);
  135. IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
  136. }
  137. };
  138. template <> struct ScalarEnumerationTraits<FormatStyle::AlignConsecutiveStyle> {
  139. static void enumeration(IO &IO, FormatStyle::AlignConsecutiveStyle &Value) {
  140. IO.enumCase(Value, "None", FormatStyle::ACS_None);
  141. IO.enumCase(Value, "Consecutive", FormatStyle::ACS_Consecutive);
  142. IO.enumCase(Value, "AcrossEmptyLines", FormatStyle::ACS_AcrossEmptyLines);
  143. IO.enumCase(Value, "AcrossComments", FormatStyle::ACS_AcrossComments);
  144. IO.enumCase(Value, "AcrossEmptyLinesAndComments",
  145. FormatStyle::ACS_AcrossEmptyLinesAndComments);
  146. // For backward compatibility.
  147. IO.enumCase(Value, "true", FormatStyle::ACS_Consecutive);
  148. IO.enumCase(Value, "false", FormatStyle::ACS_None);
  149. }
  150. };
  151. template <>
  152. struct ScalarEnumerationTraits<FormatStyle::ArrayInitializerAlignmentStyle> {
  153. static void enumeration(IO &IO,
  154. FormatStyle::ArrayInitializerAlignmentStyle &Value) {
  155. IO.enumCase(Value, "None", FormatStyle::AIAS_None);
  156. IO.enumCase(Value, "Left", FormatStyle::AIAS_Left);
  157. IO.enumCase(Value, "Right", FormatStyle::AIAS_Right);
  158. }
  159. };
  160. template <> struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
  161. static void enumeration(IO &IO, FormatStyle::ShortIfStyle &Value) {
  162. IO.enumCase(Value, "Never", FormatStyle::SIS_Never);
  163. IO.enumCase(Value, "WithoutElse", FormatStyle::SIS_WithoutElse);
  164. IO.enumCase(Value, "OnlyFirstIf", FormatStyle::SIS_OnlyFirstIf);
  165. IO.enumCase(Value, "AllIfsAndElse", FormatStyle::SIS_AllIfsAndElse);
  166. // For backward compatibility.
  167. IO.enumCase(Value, "Always", FormatStyle::SIS_OnlyFirstIf);
  168. IO.enumCase(Value, "false", FormatStyle::SIS_Never);
  169. IO.enumCase(Value, "true", FormatStyle::SIS_WithoutElse);
  170. }
  171. };
  172. template <> struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
  173. static void enumeration(IO &IO, FormatStyle::ShortLambdaStyle &Value) {
  174. IO.enumCase(Value, "None", FormatStyle::SLS_None);
  175. IO.enumCase(Value, "false", FormatStyle::SLS_None);
  176. IO.enumCase(Value, "Empty", FormatStyle::SLS_Empty);
  177. IO.enumCase(Value, "Inline", FormatStyle::SLS_Inline);
  178. IO.enumCase(Value, "All", FormatStyle::SLS_All);
  179. IO.enumCase(Value, "true", FormatStyle::SLS_All);
  180. }
  181. };
  182. template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
  183. static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value) {
  184. IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
  185. IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
  186. IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
  187. }
  188. };
  189. template <> struct ScalarEnumerationTraits<FormatStyle::TrailingCommaStyle> {
  190. static void enumeration(IO &IO, FormatStyle::TrailingCommaStyle &Value) {
  191. IO.enumCase(Value, "None", FormatStyle::TCS_None);
  192. IO.enumCase(Value, "Wrapped", FormatStyle::TCS_Wrapped);
  193. }
  194. };
  195. template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
  196. static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
  197. IO.enumCase(Value, "All", FormatStyle::BOS_All);
  198. IO.enumCase(Value, "true", FormatStyle::BOS_All);
  199. IO.enumCase(Value, "None", FormatStyle::BOS_None);
  200. IO.enumCase(Value, "false", FormatStyle::BOS_None);
  201. IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
  202. }
  203. };
  204. template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
  205. static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
  206. IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
  207. IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
  208. IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
  209. IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
  210. IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
  211. IO.enumCase(Value, "Whitesmiths", FormatStyle::BS_Whitesmiths);
  212. IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
  213. IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
  214. IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
  215. }
  216. };
  217. template <>
  218. struct ScalarEnumerationTraits<
  219. FormatStyle::BraceWrappingAfterControlStatementStyle> {
  220. static void
  221. enumeration(IO &IO,
  222. FormatStyle::BraceWrappingAfterControlStatementStyle &Value) {
  223. IO.enumCase(Value, "Never", FormatStyle::BWACS_Never);
  224. IO.enumCase(Value, "MultiLine", FormatStyle::BWACS_MultiLine);
  225. IO.enumCase(Value, "Always", FormatStyle::BWACS_Always);
  226. // For backward compatibility.
  227. IO.enumCase(Value, "false", FormatStyle::BWACS_Never);
  228. IO.enumCase(Value, "true", FormatStyle::BWACS_Always);
  229. }
  230. };
  231. template <>
  232. struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
  233. static void
  234. enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) {
  235. IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
  236. IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
  237. IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
  238. }
  239. };
  240. template <>
  241. struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
  242. static void enumeration(IO &IO,
  243. FormatStyle::BreakInheritanceListStyle &Value) {
  244. IO.enumCase(Value, "BeforeColon", FormatStyle::BILS_BeforeColon);
  245. IO.enumCase(Value, "BeforeComma", FormatStyle::BILS_BeforeComma);
  246. IO.enumCase(Value, "AfterColon", FormatStyle::BILS_AfterColon);
  247. IO.enumCase(Value, "AfterComma", FormatStyle::BILS_AfterComma);
  248. }
  249. };
  250. template <>
  251. struct ScalarEnumerationTraits<FormatStyle::PackConstructorInitializersStyle> {
  252. static void
  253. enumeration(IO &IO, FormatStyle::PackConstructorInitializersStyle &Value) {
  254. IO.enumCase(Value, "Never", FormatStyle::PCIS_Never);
  255. IO.enumCase(Value, "BinPack", FormatStyle::PCIS_BinPack);
  256. IO.enumCase(Value, "CurrentLine", FormatStyle::PCIS_CurrentLine);
  257. IO.enumCase(Value, "NextLine", FormatStyle::PCIS_NextLine);
  258. }
  259. };
  260. template <>
  261. struct ScalarEnumerationTraits<FormatStyle::EmptyLineAfterAccessModifierStyle> {
  262. static void
  263. enumeration(IO &IO, FormatStyle::EmptyLineAfterAccessModifierStyle &Value) {
  264. IO.enumCase(Value, "Never", FormatStyle::ELAAMS_Never);
  265. IO.enumCase(Value, "Leave", FormatStyle::ELAAMS_Leave);
  266. IO.enumCase(Value, "Always", FormatStyle::ELAAMS_Always);
  267. }
  268. };
  269. template <>
  270. struct ScalarEnumerationTraits<
  271. FormatStyle::EmptyLineBeforeAccessModifierStyle> {
  272. static void
  273. enumeration(IO &IO, FormatStyle::EmptyLineBeforeAccessModifierStyle &Value) {
  274. IO.enumCase(Value, "Never", FormatStyle::ELBAMS_Never);
  275. IO.enumCase(Value, "Leave", FormatStyle::ELBAMS_Leave);
  276. IO.enumCase(Value, "LogicalBlock", FormatStyle::ELBAMS_LogicalBlock);
  277. IO.enumCase(Value, "Always", FormatStyle::ELBAMS_Always);
  278. }
  279. };
  280. template <>
  281. struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
  282. static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) {
  283. IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
  284. IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
  285. IO.enumCase(Value, "BeforeHash", FormatStyle::PPDIS_BeforeHash);
  286. }
  287. };
  288. template <>
  289. struct ScalarEnumerationTraits<FormatStyle::IndentExternBlockStyle> {
  290. static void enumeration(IO &IO, FormatStyle::IndentExternBlockStyle &Value) {
  291. IO.enumCase(Value, "AfterExternBlock", FormatStyle::IEBS_AfterExternBlock);
  292. IO.enumCase(Value, "Indent", FormatStyle::IEBS_Indent);
  293. IO.enumCase(Value, "NoIndent", FormatStyle::IEBS_NoIndent);
  294. IO.enumCase(Value, "true", FormatStyle::IEBS_Indent);
  295. IO.enumCase(Value, "false", FormatStyle::IEBS_NoIndent);
  296. }
  297. };
  298. template <>
  299. struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
  300. static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
  301. IO.enumCase(Value, "None", FormatStyle::RTBS_None);
  302. IO.enumCase(Value, "All", FormatStyle::RTBS_All);
  303. IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
  304. IO.enumCase(Value, "TopLevelDefinitions",
  305. FormatStyle::RTBS_TopLevelDefinitions);
  306. IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
  307. }
  308. };
  309. template <>
  310. struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
  311. static void enumeration(IO &IO,
  312. FormatStyle::BreakTemplateDeclarationsStyle &Value) {
  313. IO.enumCase(Value, "No", FormatStyle::BTDS_No);
  314. IO.enumCase(Value, "MultiLine", FormatStyle::BTDS_MultiLine);
  315. IO.enumCase(Value, "Yes", FormatStyle::BTDS_Yes);
  316. // For backward compatibility.
  317. IO.enumCase(Value, "false", FormatStyle::BTDS_MultiLine);
  318. IO.enumCase(Value, "true", FormatStyle::BTDS_Yes);
  319. }
  320. };
  321. template <>
  322. struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
  323. static void
  324. enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
  325. IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
  326. IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
  327. IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
  328. // For backward compatibility.
  329. IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
  330. IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
  331. }
  332. };
  333. template <>
  334. struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
  335. static void enumeration(IO &IO,
  336. FormatStyle::NamespaceIndentationKind &Value) {
  337. IO.enumCase(Value, "None", FormatStyle::NI_None);
  338. IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
  339. IO.enumCase(Value, "All", FormatStyle::NI_All);
  340. }
  341. };
  342. template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
  343. static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
  344. IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
  345. IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
  346. IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
  347. IO.enumCase(Value, "BlockIndent", FormatStyle::BAS_BlockIndent);
  348. // For backward compatibility.
  349. IO.enumCase(Value, "true", FormatStyle::BAS_Align);
  350. IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
  351. }
  352. };
  353. template <>
  354. struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
  355. static void enumeration(IO &IO,
  356. FormatStyle::EscapedNewlineAlignmentStyle &Value) {
  357. IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
  358. IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
  359. IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
  360. // For backward compatibility.
  361. IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
  362. IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
  363. }
  364. };
  365. template <> struct ScalarEnumerationTraits<FormatStyle::OperandAlignmentStyle> {
  366. static void enumeration(IO &IO, FormatStyle::OperandAlignmentStyle &Value) {
  367. IO.enumCase(Value, "DontAlign", FormatStyle::OAS_DontAlign);
  368. IO.enumCase(Value, "Align", FormatStyle::OAS_Align);
  369. IO.enumCase(Value, "AlignAfterOperator",
  370. FormatStyle::OAS_AlignAfterOperator);
  371. // For backward compatibility.
  372. IO.enumCase(Value, "true", FormatStyle::OAS_Align);
  373. IO.enumCase(Value, "false", FormatStyle::OAS_DontAlign);
  374. }
  375. };
  376. template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
  377. static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
  378. IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
  379. IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
  380. IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
  381. // For backward compatibility.
  382. IO.enumCase(Value, "true", FormatStyle::PAS_Left);
  383. IO.enumCase(Value, "false", FormatStyle::PAS_Right);
  384. }
  385. };
  386. template <>
  387. struct ScalarEnumerationTraits<FormatStyle::SeparateDefinitionStyle> {
  388. static void enumeration(IO &IO, FormatStyle::SeparateDefinitionStyle &Value) {
  389. IO.enumCase(Value, "Leave", FormatStyle::SDS_Leave);
  390. IO.enumCase(Value, "Always", FormatStyle::SDS_Always);
  391. IO.enumCase(Value, "Never", FormatStyle::SDS_Never);
  392. }
  393. };
  394. template <>
  395. struct ScalarEnumerationTraits<FormatStyle::SpaceAroundPointerQualifiersStyle> {
  396. static void
  397. enumeration(IO &IO, FormatStyle::SpaceAroundPointerQualifiersStyle &Value) {
  398. IO.enumCase(Value, "Default", FormatStyle::SAPQ_Default);
  399. IO.enumCase(Value, "Before", FormatStyle::SAPQ_Before);
  400. IO.enumCase(Value, "After", FormatStyle::SAPQ_After);
  401. IO.enumCase(Value, "Both", FormatStyle::SAPQ_Both);
  402. }
  403. };
  404. template <>
  405. struct ScalarEnumerationTraits<FormatStyle::ReferenceAlignmentStyle> {
  406. static void enumeration(IO &IO, FormatStyle::ReferenceAlignmentStyle &Value) {
  407. IO.enumCase(Value, "Pointer", FormatStyle::RAS_Pointer);
  408. IO.enumCase(Value, "Middle", FormatStyle::RAS_Middle);
  409. IO.enumCase(Value, "Left", FormatStyle::RAS_Left);
  410. IO.enumCase(Value, "Right", FormatStyle::RAS_Right);
  411. }
  412. };
  413. template <>
  414. struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensStyle> {
  415. static void enumeration(IO &IO, FormatStyle::SpaceBeforeParensStyle &Value) {
  416. IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
  417. IO.enumCase(Value, "ControlStatements",
  418. FormatStyle::SBPO_ControlStatements);
  419. IO.enumCase(Value, "ControlStatementsExceptControlMacros",
  420. FormatStyle::SBPO_ControlStatementsExceptControlMacros);
  421. IO.enumCase(Value, "NonEmptyParentheses",
  422. FormatStyle::SBPO_NonEmptyParentheses);
  423. IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
  424. IO.enumCase(Value, "Custom", FormatStyle::SBPO_Custom);
  425. // For backward compatibility.
  426. IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
  427. IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
  428. IO.enumCase(Value, "ControlStatementsExceptForEachMacros",
  429. FormatStyle::SBPO_ControlStatementsExceptControlMacros);
  430. }
  431. };
  432. template <>
  433. struct ScalarEnumerationTraits<FormatStyle::BitFieldColonSpacingStyle> {
  434. static void enumeration(IO &IO,
  435. FormatStyle::BitFieldColonSpacingStyle &Value) {
  436. IO.enumCase(Value, "Both", FormatStyle::BFCS_Both);
  437. IO.enumCase(Value, "None", FormatStyle::BFCS_None);
  438. IO.enumCase(Value, "Before", FormatStyle::BFCS_Before);
  439. IO.enumCase(Value, "After", FormatStyle::BFCS_After);
  440. }
  441. };
  442. template <> struct ScalarEnumerationTraits<FormatStyle::SortIncludesOptions> {
  443. static void enumeration(IO &IO, FormatStyle::SortIncludesOptions &Value) {
  444. IO.enumCase(Value, "Never", FormatStyle::SI_Never);
  445. IO.enumCase(Value, "CaseInsensitive", FormatStyle::SI_CaseInsensitive);
  446. IO.enumCase(Value, "CaseSensitive", FormatStyle::SI_CaseSensitive);
  447. // For backward compatibility.
  448. IO.enumCase(Value, "false", FormatStyle::SI_Never);
  449. IO.enumCase(Value, "true", FormatStyle::SI_CaseSensitive);
  450. }
  451. };
  452. template <>
  453. struct ScalarEnumerationTraits<FormatStyle::SortJavaStaticImportOptions> {
  454. static void enumeration(IO &IO,
  455. FormatStyle::SortJavaStaticImportOptions &Value) {
  456. IO.enumCase(Value, "Before", FormatStyle::SJSIO_Before);
  457. IO.enumCase(Value, "After", FormatStyle::SJSIO_After);
  458. }
  459. };
  460. template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInAnglesStyle> {
  461. static void enumeration(IO &IO, FormatStyle::SpacesInAnglesStyle &Value) {
  462. IO.enumCase(Value, "Never", FormatStyle::SIAS_Never);
  463. IO.enumCase(Value, "Always", FormatStyle::SIAS_Always);
  464. IO.enumCase(Value, "Leave", FormatStyle::SIAS_Leave);
  465. // For backward compatibility.
  466. IO.enumCase(Value, "false", FormatStyle::SIAS_Never);
  467. IO.enumCase(Value, "true", FormatStyle::SIAS_Always);
  468. }
  469. };
  470. template <> struct MappingTraits<FormatStyle> {
  471. static void mapping(IO &IO, FormatStyle &Style) {
  472. // When reading, read the language first, we need it for getPredefinedStyle.
  473. IO.mapOptional("Language", Style.Language);
  474. if (IO.outputting()) {
  475. StringRef Styles[] = {"LLVM", "Google", "Chromium", "Mozilla",
  476. "WebKit", "GNU", "Microsoft"};
  477. for (StringRef StyleName : Styles) {
  478. FormatStyle PredefinedStyle;
  479. if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
  480. Style == PredefinedStyle) {
  481. IO.mapOptional("# BasedOnStyle", StyleName);
  482. break;
  483. }
  484. }
  485. } else {
  486. StringRef BasedOnStyle;
  487. IO.mapOptional("BasedOnStyle", BasedOnStyle);
  488. if (!BasedOnStyle.empty()) {
  489. FormatStyle::LanguageKind OldLanguage = Style.Language;
  490. FormatStyle::LanguageKind Language =
  491. ((FormatStyle *)IO.getContext())->Language;
  492. if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
  493. IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
  494. return;
  495. }
  496. Style.Language = OldLanguage;
  497. }
  498. }
  499. // For backward compatibility.
  500. if (!IO.outputting()) {
  501. IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
  502. IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
  503. IO.mapOptional("IndentFunctionDeclarationAfterType",
  504. Style.IndentWrappedFunctionNames);
  505. IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
  506. IO.mapOptional("SpaceAfterControlStatementKeyword",
  507. Style.SpaceBeforeParens);
  508. }
  509. IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
  510. IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
  511. IO.mapOptional("AlignArrayOfStructures", Style.AlignArrayOfStructures);
  512. IO.mapOptional("AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
  513. IO.mapOptional("AlignConsecutiveAssignments",
  514. Style.AlignConsecutiveAssignments);
  515. IO.mapOptional("AlignConsecutiveBitFields",
  516. Style.AlignConsecutiveBitFields);
  517. IO.mapOptional("AlignConsecutiveDeclarations",
  518. Style.AlignConsecutiveDeclarations);
  519. IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
  520. IO.mapOptional("AlignOperands", Style.AlignOperands);
  521. IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
  522. IO.mapOptional("AllowAllArgumentsOnNextLine",
  523. Style.AllowAllArgumentsOnNextLine);
  524. IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
  525. Style.AllowAllParametersOfDeclarationOnNextLine);
  526. IO.mapOptional("AllowShortEnumsOnASingleLine",
  527. Style.AllowShortEnumsOnASingleLine);
  528. IO.mapOptional("AllowShortBlocksOnASingleLine",
  529. Style.AllowShortBlocksOnASingleLine);
  530. IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
  531. Style.AllowShortCaseLabelsOnASingleLine);
  532. IO.mapOptional("AllowShortFunctionsOnASingleLine",
  533. Style.AllowShortFunctionsOnASingleLine);
  534. IO.mapOptional("AllowShortLambdasOnASingleLine",
  535. Style.AllowShortLambdasOnASingleLine);
  536. IO.mapOptional("AllowShortIfStatementsOnASingleLine",
  537. Style.AllowShortIfStatementsOnASingleLine);
  538. IO.mapOptional("AllowShortLoopsOnASingleLine",
  539. Style.AllowShortLoopsOnASingleLine);
  540. IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
  541. Style.AlwaysBreakAfterDefinitionReturnType);
  542. IO.mapOptional("AlwaysBreakAfterReturnType",
  543. Style.AlwaysBreakAfterReturnType);
  544. // If AlwaysBreakAfterDefinitionReturnType was specified but
  545. // AlwaysBreakAfterReturnType was not, initialize the latter from the
  546. // former for backwards compatibility.
  547. if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
  548. Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
  549. if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
  550. Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
  551. else if (Style.AlwaysBreakAfterDefinitionReturnType ==
  552. FormatStyle::DRTBS_TopLevel)
  553. Style.AlwaysBreakAfterReturnType =
  554. FormatStyle::RTBS_TopLevelDefinitions;
  555. }
  556. IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
  557. Style.AlwaysBreakBeforeMultilineStrings);
  558. IO.mapOptional("AlwaysBreakTemplateDeclarations",
  559. Style.AlwaysBreakTemplateDeclarations);
  560. IO.mapOptional("AttributeMacros", Style.AttributeMacros);
  561. IO.mapOptional("BinPackArguments", Style.BinPackArguments);
  562. IO.mapOptional("BinPackParameters", Style.BinPackParameters);
  563. IO.mapOptional("BraceWrapping", Style.BraceWrapping);
  564. IO.mapOptional("BreakBeforeBinaryOperators",
  565. Style.BreakBeforeBinaryOperators);
  566. IO.mapOptional("BreakBeforeConceptDeclarations",
  567. Style.BreakBeforeConceptDeclarations);
  568. IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
  569. bool BreakBeforeInheritanceComma = false;
  570. IO.mapOptional("BreakBeforeInheritanceComma", BreakBeforeInheritanceComma);
  571. IO.mapOptional("BreakInheritanceList", Style.BreakInheritanceList);
  572. // If BreakBeforeInheritanceComma was specified but
  573. // BreakInheritance was not, initialize the latter from the
  574. // former for backwards compatibility.
  575. if (BreakBeforeInheritanceComma &&
  576. Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon)
  577. Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
  578. IO.mapOptional("BreakBeforeTernaryOperators",
  579. Style.BreakBeforeTernaryOperators);
  580. bool BreakConstructorInitializersBeforeComma = false;
  581. IO.mapOptional("BreakConstructorInitializersBeforeComma",
  582. BreakConstructorInitializersBeforeComma);
  583. IO.mapOptional("BreakConstructorInitializers",
  584. Style.BreakConstructorInitializers);
  585. // If BreakConstructorInitializersBeforeComma was specified but
  586. // BreakConstructorInitializers was not, initialize the latter from the
  587. // former for backwards compatibility.
  588. if (BreakConstructorInitializersBeforeComma &&
  589. Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon)
  590. Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
  591. IO.mapOptional("BreakAfterJavaFieldAnnotations",
  592. Style.BreakAfterJavaFieldAnnotations);
  593. IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
  594. IO.mapOptional("ColumnLimit", Style.ColumnLimit);
  595. IO.mapOptional("CommentPragmas", Style.CommentPragmas);
  596. IO.mapOptional("QualifierAlignment", Style.QualifierAlignment);
  597. // Default Order for Left/Right based Qualifier alignment.
  598. if (Style.QualifierAlignment == FormatStyle::QAS_Right) {
  599. Style.QualifierOrder = {"type", "const", "volatile"};
  600. } else if (Style.QualifierAlignment == FormatStyle::QAS_Left) {
  601. Style.QualifierOrder = {"const", "volatile", "type"};
  602. } else if (Style.QualifierAlignment == FormatStyle::QAS_Custom) {
  603. IO.mapOptional("QualifierOrder", Style.QualifierOrder);
  604. }
  605. IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
  606. IO.mapOptional("ConstructorInitializerIndentWidth",
  607. Style.ConstructorInitializerIndentWidth);
  608. IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
  609. IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
  610. IO.mapOptional("DeriveLineEnding", Style.DeriveLineEnding);
  611. IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
  612. IO.mapOptional("DisableFormat", Style.DisableFormat);
  613. IO.mapOptional("EmptyLineAfterAccessModifier",
  614. Style.EmptyLineAfterAccessModifier);
  615. IO.mapOptional("EmptyLineBeforeAccessModifier",
  616. Style.EmptyLineBeforeAccessModifier);
  617. IO.mapOptional("ExperimentalAutoDetectBinPacking",
  618. Style.ExperimentalAutoDetectBinPacking);
  619. IO.mapOptional("PackConstructorInitializers",
  620. Style.PackConstructorInitializers);
  621. // For backward compatibility:
  622. // The default value of ConstructorInitializerAllOnOneLineOrOnePerLine was
  623. // false unless BasedOnStyle was Google or Chromium whereas that of
  624. // AllowAllConstructorInitializersOnNextLine was always true, so the
  625. // equivalent default value of PackConstructorInitializers is PCIS_NextLine
  626. // for Google/Chromium or PCIS_BinPack otherwise. If the deprecated options
  627. // had a non-default value while PackConstructorInitializers has a default
  628. // value, set the latter to an equivalent non-default value if needed.
  629. StringRef BasedOn;
  630. IO.mapOptional("BasedOnStyle", BasedOn);
  631. const bool IsGoogleOrChromium = BasedOn.equals_insensitive("google") ||
  632. BasedOn.equals_insensitive("chromium");
  633. bool OnCurrentLine = IsGoogleOrChromium;
  634. bool OnNextLine = true;
  635. IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
  636. OnCurrentLine);
  637. IO.mapOptional("AllowAllConstructorInitializersOnNextLine", OnNextLine);
  638. if (!IsGoogleOrChromium) {
  639. if (Style.PackConstructorInitializers == FormatStyle::PCIS_BinPack &&
  640. OnCurrentLine) {
  641. Style.PackConstructorInitializers = OnNextLine
  642. ? FormatStyle::PCIS_NextLine
  643. : FormatStyle::PCIS_CurrentLine;
  644. }
  645. } else if (Style.PackConstructorInitializers ==
  646. FormatStyle::PCIS_NextLine) {
  647. if (!OnCurrentLine)
  648. Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
  649. else if (!OnNextLine)
  650. Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
  651. }
  652. IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
  653. IO.mapOptional("ForEachMacros", Style.ForEachMacros);
  654. IO.mapOptional("IfMacros", Style.IfMacros);
  655. IO.mapOptional("IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
  656. IO.mapOptional("IncludeCategories", Style.IncludeStyle.IncludeCategories);
  657. IO.mapOptional("IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
  658. IO.mapOptional("IncludeIsMainSourceRegex",
  659. Style.IncludeStyle.IncludeIsMainSourceRegex);
  660. IO.mapOptional("IndentAccessModifiers", Style.IndentAccessModifiers);
  661. IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
  662. IO.mapOptional("IndentCaseBlocks", Style.IndentCaseBlocks);
  663. IO.mapOptional("IndentGotoLabels", Style.IndentGotoLabels);
  664. IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
  665. IO.mapOptional("IndentExternBlock", Style.IndentExternBlock);
  666. IO.mapOptional("IndentRequires", Style.IndentRequires);
  667. IO.mapOptional("IndentWidth", Style.IndentWidth);
  668. IO.mapOptional("IndentWrappedFunctionNames",
  669. Style.IndentWrappedFunctionNames);
  670. IO.mapOptional("InsertTrailingCommas", Style.InsertTrailingCommas);
  671. IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
  672. IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
  673. IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
  674. IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
  675. Style.KeepEmptyLinesAtTheStartOfBlocks);
  676. IO.mapOptional("LambdaBodyIndentation", Style.LambdaBodyIndentation);
  677. IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
  678. IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
  679. IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
  680. IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
  681. IO.mapOptional("NamespaceMacros", Style.NamespaceMacros);
  682. IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
  683. IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
  684. IO.mapOptional("ObjCBreakBeforeNestedBlockParam",
  685. Style.ObjCBreakBeforeNestedBlockParam);
  686. IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
  687. IO.mapOptional("ObjCSpaceBeforeProtocolList",
  688. Style.ObjCSpaceBeforeProtocolList);
  689. IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
  690. IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
  691. Style.PenaltyBreakBeforeFirstCallParameter);
  692. IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
  693. IO.mapOptional("PenaltyBreakFirstLessLess",
  694. Style.PenaltyBreakFirstLessLess);
  695. IO.mapOptional("PenaltyBreakOpenParenthesis",
  696. Style.PenaltyBreakOpenParenthesis);
  697. IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
  698. IO.mapOptional("PenaltyBreakTemplateDeclaration",
  699. Style.PenaltyBreakTemplateDeclaration);
  700. IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
  701. IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
  702. Style.PenaltyReturnTypeOnItsOwnLine);
  703. IO.mapOptional("PenaltyIndentedWhitespace",
  704. Style.PenaltyIndentedWhitespace);
  705. IO.mapOptional("PointerAlignment", Style.PointerAlignment);
  706. IO.mapOptional("PPIndentWidth", Style.PPIndentWidth);
  707. IO.mapOptional("RawStringFormats", Style.RawStringFormats);
  708. IO.mapOptional("ReferenceAlignment", Style.ReferenceAlignment);
  709. IO.mapOptional("ReflowComments", Style.ReflowComments);
  710. IO.mapOptional("RemoveBracesLLVM", Style.RemoveBracesLLVM);
  711. IO.mapOptional("SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
  712. IO.mapOptional("ShortNamespaceLines", Style.ShortNamespaceLines);
  713. IO.mapOptional("SortIncludes", Style.SortIncludes);
  714. IO.mapOptional("SortJavaStaticImport", Style.SortJavaStaticImport);
  715. IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
  716. IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
  717. IO.mapOptional("SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
  718. IO.mapOptional("SpaceAfterTemplateKeyword",
  719. Style.SpaceAfterTemplateKeyword);
  720. IO.mapOptional("SpaceBeforeAssignmentOperators",
  721. Style.SpaceBeforeAssignmentOperators);
  722. IO.mapOptional("SpaceBeforeCaseColon", Style.SpaceBeforeCaseColon);
  723. IO.mapOptional("SpaceBeforeCpp11BracedList",
  724. Style.SpaceBeforeCpp11BracedList);
  725. IO.mapOptional("SpaceBeforeCtorInitializerColon",
  726. Style.SpaceBeforeCtorInitializerColon);
  727. IO.mapOptional("SpaceBeforeInheritanceColon",
  728. Style.SpaceBeforeInheritanceColon);
  729. IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
  730. IO.mapOptional("SpaceBeforeParensOptions", Style.SpaceBeforeParensOptions);
  731. IO.mapOptional("SpaceAroundPointerQualifiers",
  732. Style.SpaceAroundPointerQualifiers);
  733. IO.mapOptional("SpaceBeforeRangeBasedForLoopColon",
  734. Style.SpaceBeforeRangeBasedForLoopColon);
  735. IO.mapOptional("SpaceInEmptyBlock", Style.SpaceInEmptyBlock);
  736. IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
  737. IO.mapOptional("SpacesBeforeTrailingComments",
  738. Style.SpacesBeforeTrailingComments);
  739. IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
  740. IO.mapOptional("SpacesInConditionalStatement",
  741. Style.SpacesInConditionalStatement);
  742. IO.mapOptional("SpacesInContainerLiterals",
  743. Style.SpacesInContainerLiterals);
  744. IO.mapOptional("SpacesInCStyleCastParentheses",
  745. Style.SpacesInCStyleCastParentheses);
  746. IO.mapOptional("SpacesInLineCommentPrefix",
  747. Style.SpacesInLineCommentPrefix);
  748. IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
  749. IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
  750. IO.mapOptional("SpaceBeforeSquareBrackets",
  751. Style.SpaceBeforeSquareBrackets);
  752. IO.mapOptional("BitFieldColonSpacing", Style.BitFieldColonSpacing);
  753. IO.mapOptional("Standard", Style.Standard);
  754. IO.mapOptional("StatementAttributeLikeMacros",
  755. Style.StatementAttributeLikeMacros);
  756. IO.mapOptional("StatementMacros", Style.StatementMacros);
  757. IO.mapOptional("TabWidth", Style.TabWidth);
  758. IO.mapOptional("TypenameMacros", Style.TypenameMacros);
  759. IO.mapOptional("UseCRLF", Style.UseCRLF);
  760. IO.mapOptional("UseTab", Style.UseTab);
  761. IO.mapOptional("WhitespaceSensitiveMacros",
  762. Style.WhitespaceSensitiveMacros);
  763. }
  764. };
  765. template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
  766. static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
  767. IO.mapOptional("AfterCaseLabel", Wrapping.AfterCaseLabel);
  768. IO.mapOptional("AfterClass", Wrapping.AfterClass);
  769. IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
  770. IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
  771. IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
  772. IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
  773. IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
  774. IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
  775. IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
  776. IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
  777. IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
  778. IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
  779. IO.mapOptional("BeforeLambdaBody", Wrapping.BeforeLambdaBody);
  780. IO.mapOptional("BeforeWhile", Wrapping.BeforeWhile);
  781. IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
  782. IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
  783. IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
  784. IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
  785. }
  786. };
  787. template <> struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {
  788. static void mapping(IO &IO, FormatStyle::SpaceBeforeParensCustom &Spacing) {
  789. IO.mapOptional("AfterControlStatements", Spacing.AfterControlStatements);
  790. IO.mapOptional("AfterForeachMacros", Spacing.AfterForeachMacros);
  791. IO.mapOptional("AfterFunctionDefinitionName",
  792. Spacing.AfterFunctionDefinitionName);
  793. IO.mapOptional("AfterFunctionDeclarationName",
  794. Spacing.AfterFunctionDeclarationName);
  795. IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacros);
  796. IO.mapOptional("AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
  797. IO.mapOptional("BeforeNonEmptyParentheses",
  798. Spacing.BeforeNonEmptyParentheses);
  799. }
  800. };
  801. template <> struct MappingTraits<FormatStyle::RawStringFormat> {
  802. static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
  803. IO.mapOptional("Language", Format.Language);
  804. IO.mapOptional("Delimiters", Format.Delimiters);
  805. IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
  806. IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
  807. IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
  808. }
  809. };
  810. template <> struct MappingTraits<FormatStyle::SpacesInLineComment> {
  811. static void mapping(IO &IO, FormatStyle::SpacesInLineComment &Space) {
  812. // Transform the maximum to signed, to parse "-1" correctly
  813. int signedMaximum = static_cast<int>(Space.Maximum);
  814. IO.mapOptional("Minimum", Space.Minimum);
  815. IO.mapOptional("Maximum", signedMaximum);
  816. Space.Maximum = static_cast<unsigned>(signedMaximum);
  817. if (Space.Maximum != -1u) {
  818. Space.Minimum = std::min(Space.Minimum, Space.Maximum);
  819. }
  820. }
  821. };
  822. // Allows to read vector<FormatStyle> while keeping default values.
  823. // IO.getContext() should contain a pointer to the FormatStyle structure, that
  824. // will be used to get default values for missing keys.
  825. // If the first element has no Language specified, it will be treated as the
  826. // default one for the following elements.
  827. template <> struct DocumentListTraits<std::vector<FormatStyle>> {
  828. static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
  829. return Seq.size();
  830. }
  831. static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
  832. size_t Index) {
  833. if (Index >= Seq.size()) {
  834. assert(Index == Seq.size());
  835. FormatStyle Template;
  836. if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
  837. Template = Seq[0];
  838. } else {
  839. Template = *((const FormatStyle *)IO.getContext());
  840. Template.Language = FormatStyle::LK_None;
  841. }
  842. Seq.resize(Index + 1, Template);
  843. }
  844. return Seq[Index];
  845. }
  846. };
  847. } // namespace yaml
  848. } // namespace llvm
  849. namespace clang {
  850. namespace format {
  851. const std::error_category &getParseCategory() {
  852. static const ParseErrorCategory C{};
  853. return C;
  854. }
  855. std::error_code make_error_code(ParseError e) {
  856. return std::error_code(static_cast<int>(e), getParseCategory());
  857. }
  858. inline llvm::Error make_string_error(const llvm::Twine &Message) {
  859. return llvm::make_error<llvm::StringError>(Message,
  860. llvm::inconvertibleErrorCode());
  861. }
  862. const char *ParseErrorCategory::name() const noexcept {
  863. return "clang-format.parse_error";
  864. }
  865. std::string ParseErrorCategory::message(int EV) const {
  866. switch (static_cast<ParseError>(EV)) {
  867. case ParseError::Success:
  868. return "Success";
  869. case ParseError::Error:
  870. return "Invalid argument";
  871. case ParseError::Unsuitable:
  872. return "Unsuitable";
  873. case ParseError::BinPackTrailingCommaConflict:
  874. return "trailing comma insertion cannot be used with bin packing";
  875. case ParseError::InvalidQualifierSpecified:
  876. return "Invalid qualifier specified in QualifierOrder";
  877. case ParseError::DuplicateQualifierSpecified:
  878. return "Duplicate qualifier specified in QualfierOrder";
  879. case ParseError::MissingQualifierType:
  880. return "Missing type in QualfierOrder";
  881. case ParseError::MissingQualifierOrder:
  882. return "Missing QualfierOrder";
  883. }
  884. llvm_unreachable("unexpected parse error");
  885. }
  886. static void expandPresetsBraceWrapping(FormatStyle &Expanded) {
  887. if (Expanded.BreakBeforeBraces == FormatStyle::BS_Custom)
  888. return;
  889. Expanded.BraceWrapping = {/*AfterCaseLabel=*/false,
  890. /*AfterClass=*/false,
  891. /*AfterControlStatement=*/FormatStyle::BWACS_Never,
  892. /*AfterEnum=*/false,
  893. /*AfterFunction=*/false,
  894. /*AfterNamespace=*/false,
  895. /*AfterObjCDeclaration=*/false,
  896. /*AfterStruct=*/false,
  897. /*AfterUnion=*/false,
  898. /*AfterExternBlock=*/false,
  899. /*BeforeCatch=*/false,
  900. /*BeforeElse=*/false,
  901. /*BeforeLambdaBody=*/false,
  902. /*BeforeWhile=*/false,
  903. /*IndentBraces=*/false,
  904. /*SplitEmptyFunction=*/true,
  905. /*SplitEmptyRecord=*/true,
  906. /*SplitEmptyNamespace=*/true};
  907. switch (Expanded.BreakBeforeBraces) {
  908. case FormatStyle::BS_Linux:
  909. Expanded.BraceWrapping.AfterClass = true;
  910. Expanded.BraceWrapping.AfterFunction = true;
  911. Expanded.BraceWrapping.AfterNamespace = true;
  912. break;
  913. case FormatStyle::BS_Mozilla:
  914. Expanded.BraceWrapping.AfterClass = true;
  915. Expanded.BraceWrapping.AfterEnum = true;
  916. Expanded.BraceWrapping.AfterFunction = true;
  917. Expanded.BraceWrapping.AfterStruct = true;
  918. Expanded.BraceWrapping.AfterUnion = true;
  919. Expanded.BraceWrapping.AfterExternBlock = true;
  920. Expanded.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
  921. Expanded.BraceWrapping.SplitEmptyFunction = true;
  922. Expanded.BraceWrapping.SplitEmptyRecord = false;
  923. break;
  924. case FormatStyle::BS_Stroustrup:
  925. Expanded.BraceWrapping.AfterFunction = true;
  926. Expanded.BraceWrapping.BeforeCatch = true;
  927. Expanded.BraceWrapping.BeforeElse = true;
  928. break;
  929. case FormatStyle::BS_Allman:
  930. Expanded.BraceWrapping.AfterCaseLabel = true;
  931. Expanded.BraceWrapping.AfterClass = true;
  932. Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
  933. Expanded.BraceWrapping.AfterEnum = true;
  934. Expanded.BraceWrapping.AfterFunction = true;
  935. Expanded.BraceWrapping.AfterNamespace = true;
  936. Expanded.BraceWrapping.AfterObjCDeclaration = true;
  937. Expanded.BraceWrapping.AfterStruct = true;
  938. Expanded.BraceWrapping.AfterUnion = true;
  939. Expanded.BraceWrapping.AfterExternBlock = true;
  940. Expanded.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
  941. Expanded.BraceWrapping.BeforeCatch = true;
  942. Expanded.BraceWrapping.BeforeElse = true;
  943. Expanded.BraceWrapping.BeforeLambdaBody = true;
  944. break;
  945. case FormatStyle::BS_Whitesmiths:
  946. Expanded.BraceWrapping.AfterCaseLabel = true;
  947. Expanded.BraceWrapping.AfterClass = true;
  948. Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
  949. Expanded.BraceWrapping.AfterEnum = true;
  950. Expanded.BraceWrapping.AfterFunction = true;
  951. Expanded.BraceWrapping.AfterNamespace = true;
  952. Expanded.BraceWrapping.AfterObjCDeclaration = true;
  953. Expanded.BraceWrapping.AfterStruct = true;
  954. Expanded.BraceWrapping.AfterExternBlock = true;
  955. Expanded.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
  956. Expanded.BraceWrapping.BeforeCatch = true;
  957. Expanded.BraceWrapping.BeforeElse = true;
  958. Expanded.BraceWrapping.BeforeLambdaBody = true;
  959. break;
  960. case FormatStyle::BS_GNU:
  961. Expanded.BraceWrapping = {
  962. /*AfterCaseLabel=*/true,
  963. /*AfterClass=*/true,
  964. /*AfterControlStatement=*/FormatStyle::BWACS_Always,
  965. /*AfterEnum=*/true,
  966. /*AfterFunction=*/true,
  967. /*AfterNamespace=*/true,
  968. /*AfterObjCDeclaration=*/true,
  969. /*AfterStruct=*/true,
  970. /*AfterUnion=*/true,
  971. /*AfterExternBlock=*/true,
  972. /*BeforeCatch=*/true,
  973. /*BeforeElse=*/true,
  974. /*BeforeLambdaBody=*/false,
  975. /*BeforeWhile=*/true,
  976. /*IndentBraces=*/true,
  977. /*SplitEmptyFunction=*/true,
  978. /*SplitEmptyRecord=*/true,
  979. /*SplitEmptyNamespace=*/true};
  980. Expanded.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
  981. break;
  982. case FormatStyle::BS_WebKit:
  983. Expanded.BraceWrapping.AfterFunction = true;
  984. break;
  985. default:
  986. break;
  987. }
  988. }
  989. static void expandPresetsSpaceBeforeParens(FormatStyle &Expanded) {
  990. if (Expanded.SpaceBeforeParens == FormatStyle::SBPO_Custom)
  991. return;
  992. // Reset all flags
  993. Expanded.SpaceBeforeParensOptions = {};
  994. switch (Expanded.SpaceBeforeParens) {
  995. case FormatStyle::SBPO_Never:
  996. break;
  997. case FormatStyle::SBPO_ControlStatements:
  998. Expanded.SpaceBeforeParensOptions.AfterControlStatements = true;
  999. Expanded.SpaceBeforeParensOptions.AfterForeachMacros = true;
  1000. Expanded.SpaceBeforeParensOptions.AfterIfMacros = true;
  1001. break;
  1002. case FormatStyle::SBPO_ControlStatementsExceptControlMacros:
  1003. Expanded.SpaceBeforeParensOptions.AfterControlStatements = true;
  1004. break;
  1005. case FormatStyle::SBPO_NonEmptyParentheses:
  1006. Expanded.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
  1007. break;
  1008. case FormatStyle::SBPO_Always:
  1009. break;
  1010. default:
  1011. break;
  1012. }
  1013. }
  1014. FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) {
  1015. FormatStyle LLVMStyle;
  1016. LLVMStyle.InheritsParentConfig = false;
  1017. LLVMStyle.Language = Language;
  1018. LLVMStyle.AccessModifierOffset = -2;
  1019. LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
  1020. LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
  1021. LLVMStyle.AlignArrayOfStructures = FormatStyle::AIAS_None;
  1022. LLVMStyle.AlignOperands = FormatStyle::OAS_Align;
  1023. LLVMStyle.AlignTrailingComments = true;
  1024. LLVMStyle.AlignConsecutiveAssignments = FormatStyle::ACS_None;
  1025. LLVMStyle.AlignConsecutiveBitFields = FormatStyle::ACS_None;
  1026. LLVMStyle.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
  1027. LLVMStyle.AlignConsecutiveMacros = FormatStyle::ACS_None;
  1028. LLVMStyle.AllowAllArgumentsOnNextLine = true;
  1029. LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
  1030. LLVMStyle.AllowShortEnumsOnASingleLine = true;
  1031. LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
  1032. LLVMStyle.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
  1033. LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
  1034. LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
  1035. LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
  1036. LLVMStyle.AllowShortLoopsOnASingleLine = false;
  1037. LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
  1038. LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
  1039. LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
  1040. LLVMStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
  1041. LLVMStyle.AttributeMacros.push_back("__capability");
  1042. LLVMStyle.BinPackArguments = true;
  1043. LLVMStyle.BinPackParameters = true;
  1044. LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
  1045. LLVMStyle.BreakBeforeConceptDeclarations = true;
  1046. LLVMStyle.BreakBeforeTernaryOperators = true;
  1047. LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
  1048. LLVMStyle.BraceWrapping = {/*AfterCaseLabel=*/false,
  1049. /*AfterClass=*/false,
  1050. /*AfterControlStatement=*/FormatStyle::BWACS_Never,
  1051. /*AfterEnum=*/false,
  1052. /*AfterFunction=*/false,
  1053. /*AfterNamespace=*/false,
  1054. /*AfterObjCDeclaration=*/false,
  1055. /*AfterStruct=*/false,
  1056. /*AfterUnion=*/false,
  1057. /*AfterExternBlock=*/false,
  1058. /*BeforeCatch=*/false,
  1059. /*BeforeElse=*/false,
  1060. /*BeforeLambdaBody=*/false,
  1061. /*BeforeWhile=*/false,
  1062. /*IndentBraces=*/false,
  1063. /*SplitEmptyFunction=*/true,
  1064. /*SplitEmptyRecord=*/true,
  1065. /*SplitEmptyNamespace=*/true};
  1066. LLVMStyle.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
  1067. LLVMStyle.BreakAfterJavaFieldAnnotations = false;
  1068. LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
  1069. LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
  1070. LLVMStyle.BreakStringLiterals = true;
  1071. LLVMStyle.ColumnLimit = 80;
  1072. LLVMStyle.CommentPragmas = "^ IWYU pragma:";
  1073. LLVMStyle.CompactNamespaces = false;
  1074. LLVMStyle.ConstructorInitializerIndentWidth = 4;
  1075. LLVMStyle.ContinuationIndentWidth = 4;
  1076. LLVMStyle.Cpp11BracedListStyle = true;
  1077. // Off by default Qualifier ordering
  1078. LLVMStyle.QualifierAlignment = FormatStyle::QAS_Leave;
  1079. LLVMStyle.DeriveLineEnding = true;
  1080. LLVMStyle.DerivePointerAlignment = false;
  1081. LLVMStyle.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
  1082. LLVMStyle.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
  1083. LLVMStyle.ExperimentalAutoDetectBinPacking = false;
  1084. LLVMStyle.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
  1085. LLVMStyle.FixNamespaceComments = true;
  1086. LLVMStyle.ForEachMacros.push_back("foreach");
  1087. LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
  1088. LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
  1089. LLVMStyle.IfMacros.push_back("KJ_IF_MAYBE");
  1090. LLVMStyle.IncludeStyle.IncludeCategories = {
  1091. {"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0, false},
  1092. {"^(<|\"(gtest|gmock|isl|json)/)", 3, 0, false},
  1093. {".*", 1, 0, false}};
  1094. LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
  1095. LLVMStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve;
  1096. LLVMStyle.IndentAccessModifiers = false;
  1097. LLVMStyle.IndentCaseLabels = false;
  1098. LLVMStyle.IndentCaseBlocks = false;
  1099. LLVMStyle.IndentGotoLabels = true;
  1100. LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
  1101. LLVMStyle.IndentRequires = false;
  1102. LLVMStyle.IndentWrappedFunctionNames = false;
  1103. LLVMStyle.IndentWidth = 2;
  1104. LLVMStyle.PPIndentWidth = -1;
  1105. LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
  1106. LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
  1107. LLVMStyle.JavaScriptWrapImports = true;
  1108. LLVMStyle.TabWidth = 8;
  1109. LLVMStyle.LambdaBodyIndentation = FormatStyle::LBI_Signature;
  1110. LLVMStyle.MaxEmptyLinesToKeep = 1;
  1111. LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
  1112. LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
  1113. LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
  1114. LLVMStyle.ObjCBlockIndentWidth = 2;
  1115. LLVMStyle.ObjCBreakBeforeNestedBlockParam = true;
  1116. LLVMStyle.ObjCSpaceAfterProperty = false;
  1117. LLVMStyle.ObjCSpaceBeforeProtocolList = true;
  1118. LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
  1119. LLVMStyle.ReferenceAlignment = FormatStyle::RAS_Pointer;
  1120. LLVMStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
  1121. LLVMStyle.ShortNamespaceLines = 1;
  1122. LLVMStyle.SpacesBeforeTrailingComments = 1;
  1123. LLVMStyle.Standard = FormatStyle::LS_Latest;
  1124. LLVMStyle.UseCRLF = false;
  1125. LLVMStyle.UseTab = FormatStyle::UT_Never;
  1126. LLVMStyle.ReflowComments = true;
  1127. LLVMStyle.RemoveBracesLLVM = false;
  1128. LLVMStyle.SpacesInParentheses = false;
  1129. LLVMStyle.SpacesInSquareBrackets = false;
  1130. LLVMStyle.SpaceInEmptyBlock = false;
  1131. LLVMStyle.SpaceInEmptyParentheses = false;
  1132. LLVMStyle.SpacesInContainerLiterals = true;
  1133. LLVMStyle.SpacesInCStyleCastParentheses = false;
  1134. LLVMStyle.SpacesInLineCommentPrefix = {/*Minimum=*/1, /*Maximum=*/-1u};
  1135. LLVMStyle.SpaceAfterCStyleCast = false;
  1136. LLVMStyle.SpaceAfterLogicalNot = false;
  1137. LLVMStyle.SpaceAfterTemplateKeyword = true;
  1138. LLVMStyle.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
  1139. LLVMStyle.SpaceBeforeCaseColon = false;
  1140. LLVMStyle.SpaceBeforeCtorInitializerColon = true;
  1141. LLVMStyle.SpaceBeforeInheritanceColon = true;
  1142. LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
  1143. LLVMStyle.SpaceBeforeParensOptions.AfterControlStatements = true;
  1144. LLVMStyle.SpaceBeforeParensOptions.AfterForeachMacros = true;
  1145. LLVMStyle.SpaceBeforeParensOptions.AfterIfMacros = true;
  1146. LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
  1147. LLVMStyle.SpaceBeforeAssignmentOperators = true;
  1148. LLVMStyle.SpaceBeforeCpp11BracedList = false;
  1149. LLVMStyle.SpaceBeforeSquareBrackets = false;
  1150. LLVMStyle.BitFieldColonSpacing = FormatStyle::BFCS_Both;
  1151. LLVMStyle.SpacesInAngles = FormatStyle::SIAS_Never;
  1152. LLVMStyle.SpacesInConditionalStatement = false;
  1153. LLVMStyle.PenaltyBreakAssignment = prec::Assignment;
  1154. LLVMStyle.PenaltyBreakComment = 300;
  1155. LLVMStyle.PenaltyBreakFirstLessLess = 120;
  1156. LLVMStyle.PenaltyBreakString = 1000;
  1157. LLVMStyle.PenaltyExcessCharacter = 1000000;
  1158. LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
  1159. LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
  1160. LLVMStyle.PenaltyBreakOpenParenthesis = 0;
  1161. LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational;
  1162. LLVMStyle.PenaltyIndentedWhitespace = 0;
  1163. LLVMStyle.DisableFormat = false;
  1164. LLVMStyle.SortIncludes = FormatStyle::SI_CaseSensitive;
  1165. LLVMStyle.SortJavaStaticImport = FormatStyle::SJSIO_Before;
  1166. LLVMStyle.SortUsingDeclarations = true;
  1167. LLVMStyle.StatementAttributeLikeMacros.push_back("Q_EMIT");
  1168. LLVMStyle.StatementMacros.push_back("Q_UNUSED");
  1169. LLVMStyle.StatementMacros.push_back("QT_REQUIRE_VERSION");
  1170. LLVMStyle.WhitespaceSensitiveMacros.push_back("STRINGIZE");
  1171. LLVMStyle.WhitespaceSensitiveMacros.push_back("PP_STRINGIZE");
  1172. LLVMStyle.WhitespaceSensitiveMacros.push_back("BOOST_PP_STRINGIZE");
  1173. LLVMStyle.WhitespaceSensitiveMacros.push_back("NS_SWIFT_NAME");
  1174. LLVMStyle.WhitespaceSensitiveMacros.push_back("CF_SWIFT_NAME");
  1175. // Defaults that differ when not C++.
  1176. if (Language == FormatStyle::LK_TableGen) {
  1177. LLVMStyle.SpacesInContainerLiterals = false;
  1178. }
  1179. if (LLVMStyle.isJson()) {
  1180. LLVMStyle.ColumnLimit = 0;
  1181. }
  1182. return LLVMStyle;
  1183. }
  1184. FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
  1185. if (Language == FormatStyle::LK_TextProto) {
  1186. FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
  1187. GoogleStyle.Language = FormatStyle::LK_TextProto;
  1188. return GoogleStyle;
  1189. }
  1190. FormatStyle GoogleStyle = getLLVMStyle(Language);
  1191. GoogleStyle.AccessModifierOffset = -1;
  1192. GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
  1193. GoogleStyle.AllowShortIfStatementsOnASingleLine =
  1194. FormatStyle::SIS_WithoutElse;
  1195. GoogleStyle.AllowShortLoopsOnASingleLine = true;
  1196. GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
  1197. GoogleStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
  1198. GoogleStyle.DerivePointerAlignment = true;
  1199. GoogleStyle.IncludeStyle.IncludeCategories = {{"^<ext/.*\\.h>", 2, 0, false},
  1200. {"^<.*\\.h>", 1, 0, false},
  1201. {"^<.*", 2, 0, false},
  1202. {".*", 3, 0, false}};
  1203. GoogleStyle.IncludeStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
  1204. GoogleStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup;
  1205. GoogleStyle.IndentCaseLabels = true;
  1206. GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
  1207. GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
  1208. GoogleStyle.ObjCSpaceAfterProperty = false;
  1209. GoogleStyle.ObjCSpaceBeforeProtocolList = true;
  1210. GoogleStyle.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
  1211. GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
  1212. GoogleStyle.RawStringFormats = {
  1213. {
  1214. FormatStyle::LK_Cpp,
  1215. /*Delimiters=*/
  1216. {
  1217. "cc",
  1218. "CC",
  1219. "cpp",
  1220. "Cpp",
  1221. "CPP",
  1222. "c++",
  1223. "C++",
  1224. },
  1225. /*EnclosingFunctionNames=*/
  1226. {},
  1227. /*CanonicalDelimiter=*/"",
  1228. /*BasedOnStyle=*/"google",
  1229. },
  1230. {
  1231. FormatStyle::LK_TextProto,
  1232. /*Delimiters=*/
  1233. {
  1234. "pb",
  1235. "PB",
  1236. "proto",
  1237. "PROTO",
  1238. },
  1239. /*EnclosingFunctionNames=*/
  1240. {
  1241. "EqualsProto",
  1242. "EquivToProto",
  1243. "PARSE_PARTIAL_TEXT_PROTO",
  1244. "PARSE_TEST_PROTO",
  1245. "PARSE_TEXT_PROTO",
  1246. "ParseTextOrDie",
  1247. "ParseTextProtoOrDie",
  1248. "ParseTestProto",
  1249. "ParsePartialTestProto",
  1250. },
  1251. /*CanonicalDelimiter=*/"pb",
  1252. /*BasedOnStyle=*/"google",
  1253. },
  1254. };
  1255. GoogleStyle.SpacesBeforeTrailingComments = 2;
  1256. GoogleStyle.Standard = FormatStyle::LS_Auto;
  1257. GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  1258. GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
  1259. if (Language == FormatStyle::LK_Java) {
  1260. GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
  1261. GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
  1262. GoogleStyle.AlignTrailingComments = false;
  1263. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
  1264. GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
  1265. GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
  1266. GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
  1267. GoogleStyle.ColumnLimit = 100;
  1268. GoogleStyle.SpaceAfterCStyleCast = true;
  1269. GoogleStyle.SpacesBeforeTrailingComments = 1;
  1270. } else if (Language == FormatStyle::LK_JavaScript) {
  1271. GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
  1272. GoogleStyle.AlignOperands = FormatStyle::OAS_DontAlign;
  1273. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
  1274. // TODO: still under discussion whether to switch to SLS_All.
  1275. GoogleStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
  1276. GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
  1277. GoogleStyle.BreakBeforeTernaryOperators = false;
  1278. // taze:, triple slash directives (`/// <...`), tslint:, and @see, which is
  1279. // commonly followed by overlong URLs.
  1280. GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|tslint:|@see)";
  1281. // TODO: enable once decided, in particular re disabling bin packing.
  1282. // https://google.github.io/styleguide/jsguide.html#features-arrays-trailing-comma
  1283. // GoogleStyle.InsertTrailingCommas = FormatStyle::TCS_Wrapped;
  1284. GoogleStyle.MaxEmptyLinesToKeep = 3;
  1285. GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
  1286. GoogleStyle.SpacesInContainerLiterals = false;
  1287. GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
  1288. GoogleStyle.JavaScriptWrapImports = false;
  1289. } else if (Language == FormatStyle::LK_Proto) {
  1290. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
  1291. GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
  1292. GoogleStyle.SpacesInContainerLiterals = false;
  1293. GoogleStyle.Cpp11BracedListStyle = false;
  1294. // This affects protocol buffer options specifications and text protos.
  1295. // Text protos are currently mostly formatted inside C++ raw string literals
  1296. // and often the current breaking behavior of string literals is not
  1297. // beneficial there. Investigate turning this on once proper string reflow
  1298. // has been implemented.
  1299. GoogleStyle.BreakStringLiterals = false;
  1300. } else if (Language == FormatStyle::LK_ObjC) {
  1301. GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
  1302. GoogleStyle.ColumnLimit = 100;
  1303. // "Regroup" doesn't work well for ObjC yet (main header heuristic,
  1304. // relationship between ObjC standard library headers and other heades,
  1305. // #imports, etc.)
  1306. GoogleStyle.IncludeStyle.IncludeBlocks =
  1307. tooling::IncludeStyle::IBS_Preserve;
  1308. } else if (Language == FormatStyle::LK_CSharp) {
  1309. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
  1310. GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
  1311. GoogleStyle.BreakStringLiterals = false;
  1312. GoogleStyle.ColumnLimit = 100;
  1313. GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
  1314. }
  1315. return GoogleStyle;
  1316. }
  1317. FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
  1318. FormatStyle ChromiumStyle = getGoogleStyle(Language);
  1319. // Disable include reordering across blocks in Chromium code.
  1320. // - clang-format tries to detect that foo.h is the "main" header for
  1321. // foo.cc and foo_unittest.cc via IncludeIsMainRegex. However, Chromium
  1322. // uses many other suffices (_win.cc, _mac.mm, _posix.cc, _browsertest.cc,
  1323. // _private.cc, _impl.cc etc) in different permutations
  1324. // (_win_browsertest.cc) so disable this until IncludeIsMainRegex has a
  1325. // better default for Chromium code.
  1326. // - The default for .cc and .mm files is different (r357695) for Google style
  1327. // for the same reason. The plan is to unify this again once the main
  1328. // header detection works for Google's ObjC code, but this hasn't happened
  1329. // yet. Since Chromium has some ObjC code, switching Chromium is blocked
  1330. // on that.
  1331. // - Finally, "If include reordering is harmful, put things in different
  1332. // blocks to prevent it" has been a recommendation for a long time that
  1333. // people are used to. We'll need a dev education push to change this to
  1334. // "If include reordering is harmful, put things in a different block and
  1335. // _prepend that with a comment_ to prevent it" before changing behavior.
  1336. ChromiumStyle.IncludeStyle.IncludeBlocks =
  1337. tooling::IncludeStyle::IBS_Preserve;
  1338. if (Language == FormatStyle::LK_Java) {
  1339. ChromiumStyle.AllowShortIfStatementsOnASingleLine =
  1340. FormatStyle::SIS_WithoutElse;
  1341. ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
  1342. ChromiumStyle.ContinuationIndentWidth = 8;
  1343. ChromiumStyle.IndentWidth = 4;
  1344. // See styleguide for import groups:
  1345. // https://chromium.googlesource.com/chromium/src/+/refs/heads/main/styleguide/java/java.md#Import-Order
  1346. ChromiumStyle.JavaImportGroups = {
  1347. "android",
  1348. "androidx",
  1349. "com",
  1350. "dalvik",
  1351. "junit",
  1352. "org",
  1353. "com.google.android.apps.chrome",
  1354. "org.chromium",
  1355. "java",
  1356. "javax",
  1357. };
  1358. ChromiumStyle.SortIncludes = FormatStyle::SI_CaseSensitive;
  1359. } else if (Language == FormatStyle::LK_JavaScript) {
  1360. ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
  1361. ChromiumStyle.AllowShortLoopsOnASingleLine = false;
  1362. } else {
  1363. ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  1364. ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
  1365. ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
  1366. ChromiumStyle.AllowShortLoopsOnASingleLine = false;
  1367. ChromiumStyle.BinPackParameters = false;
  1368. ChromiumStyle.DerivePointerAlignment = false;
  1369. if (Language == FormatStyle::LK_ObjC)
  1370. ChromiumStyle.ColumnLimit = 80;
  1371. }
  1372. return ChromiumStyle;
  1373. }
  1374. FormatStyle getMozillaStyle() {
  1375. FormatStyle MozillaStyle = getLLVMStyle();
  1376. MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  1377. MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
  1378. MozillaStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
  1379. MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
  1380. FormatStyle::DRTBS_TopLevel;
  1381. MozillaStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
  1382. MozillaStyle.BinPackParameters = false;
  1383. MozillaStyle.BinPackArguments = false;
  1384. MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
  1385. MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
  1386. MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
  1387. MozillaStyle.ConstructorInitializerIndentWidth = 2;
  1388. MozillaStyle.ContinuationIndentWidth = 2;
  1389. MozillaStyle.Cpp11BracedListStyle = false;
  1390. MozillaStyle.FixNamespaceComments = false;
  1391. MozillaStyle.IndentCaseLabels = true;
  1392. MozillaStyle.ObjCSpaceAfterProperty = true;
  1393. MozillaStyle.ObjCSpaceBeforeProtocolList = false;
  1394. MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  1395. MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
  1396. MozillaStyle.SpaceAfterTemplateKeyword = false;
  1397. return MozillaStyle;
  1398. }
  1399. FormatStyle getWebKitStyle() {
  1400. FormatStyle Style = getLLVMStyle();
  1401. Style.AccessModifierOffset = -4;
  1402. Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
  1403. Style.AlignOperands = FormatStyle::OAS_DontAlign;
  1404. Style.AlignTrailingComments = false;
  1405. Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
  1406. Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
  1407. Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
  1408. Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
  1409. Style.Cpp11BracedListStyle = false;
  1410. Style.ColumnLimit = 0;
  1411. Style.FixNamespaceComments = false;
  1412. Style.IndentWidth = 4;
  1413. Style.NamespaceIndentation = FormatStyle::NI_Inner;
  1414. Style.ObjCBlockIndentWidth = 4;
  1415. Style.ObjCSpaceAfterProperty = true;
  1416. Style.PointerAlignment = FormatStyle::PAS_Left;
  1417. Style.SpaceBeforeCpp11BracedList = true;
  1418. Style.SpaceInEmptyBlock = true;
  1419. return Style;
  1420. }
  1421. FormatStyle getGNUStyle() {
  1422. FormatStyle Style = getLLVMStyle();
  1423. Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
  1424. Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
  1425. Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
  1426. Style.BreakBeforeBraces = FormatStyle::BS_GNU;
  1427. Style.BreakBeforeTernaryOperators = true;
  1428. Style.Cpp11BracedListStyle = false;
  1429. Style.ColumnLimit = 79;
  1430. Style.FixNamespaceComments = false;
  1431. Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
  1432. Style.Standard = FormatStyle::LS_Cpp03;
  1433. return Style;
  1434. }
  1435. FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language) {
  1436. FormatStyle Style = getLLVMStyle(Language);
  1437. Style.ColumnLimit = 120;
  1438. Style.TabWidth = 4;
  1439. Style.IndentWidth = 4;
  1440. Style.UseTab = FormatStyle::UT_Never;
  1441. Style.BreakBeforeBraces = FormatStyle::BS_Custom;
  1442. Style.BraceWrapping.AfterClass = true;
  1443. Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
  1444. Style.BraceWrapping.AfterEnum = true;
  1445. Style.BraceWrapping.AfterFunction = true;
  1446. Style.BraceWrapping.AfterNamespace = true;
  1447. Style.BraceWrapping.AfterObjCDeclaration = true;
  1448. Style.BraceWrapping.AfterStruct = true;
  1449. Style.BraceWrapping.AfterExternBlock = true;
  1450. Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
  1451. Style.BraceWrapping.BeforeCatch = true;
  1452. Style.BraceWrapping.BeforeElse = true;
  1453. Style.BraceWrapping.BeforeWhile = false;
  1454. Style.PenaltyReturnTypeOnItsOwnLine = 1000;
  1455. Style.AllowShortEnumsOnASingleLine = false;
  1456. Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
  1457. Style.AllowShortCaseLabelsOnASingleLine = false;
  1458. Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
  1459. Style.AllowShortLoopsOnASingleLine = false;
  1460. Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
  1461. Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
  1462. return Style;
  1463. }
  1464. FormatStyle getNoStyle() {
  1465. FormatStyle NoStyle = getLLVMStyle();
  1466. NoStyle.DisableFormat = true;
  1467. NoStyle.SortIncludes = FormatStyle::SI_Never;
  1468. NoStyle.SortUsingDeclarations = false;
  1469. return NoStyle;
  1470. }
  1471. bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
  1472. FormatStyle *Style) {
  1473. if (Name.equals_insensitive("llvm")) {
  1474. *Style = getLLVMStyle(Language);
  1475. } else if (Name.equals_insensitive("chromium")) {
  1476. *Style = getChromiumStyle(Language);
  1477. } else if (Name.equals_insensitive("mozilla")) {
  1478. *Style = getMozillaStyle();
  1479. } else if (Name.equals_insensitive("google")) {
  1480. *Style = getGoogleStyle(Language);
  1481. } else if (Name.equals_insensitive("webkit")) {
  1482. *Style = getWebKitStyle();
  1483. } else if (Name.equals_insensitive("gnu")) {
  1484. *Style = getGNUStyle();
  1485. } else if (Name.equals_insensitive("microsoft")) {
  1486. *Style = getMicrosoftStyle(Language);
  1487. } else if (Name.equals_insensitive("none")) {
  1488. *Style = getNoStyle();
  1489. } else if (Name.equals_insensitive("inheritparentconfig")) {
  1490. Style->InheritsParentConfig = true;
  1491. } else {
  1492. return false;
  1493. }
  1494. Style->Language = Language;
  1495. return true;
  1496. }
  1497. ParseError validateQualifierOrder(FormatStyle *Style) {
  1498. // If its empty then it means don't do anything.
  1499. if (Style->QualifierOrder.empty())
  1500. return ParseError::MissingQualifierOrder;
  1501. // Ensure the list contains only currently valid qualifiers.
  1502. for (const auto &Qualifier : Style->QualifierOrder) {
  1503. if (Qualifier == "type")
  1504. continue;
  1505. auto token =
  1506. LeftRightQualifierAlignmentFixer::getTokenFromQualifier(Qualifier);
  1507. if (token == tok::identifier)
  1508. return ParseError::InvalidQualifierSpecified;
  1509. }
  1510. // Ensure the list is unqiue (no duplicates).
  1511. std::set<std::string> UniqueQualifiers(Style->QualifierOrder.begin(),
  1512. Style->QualifierOrder.end());
  1513. if (Style->QualifierOrder.size() != UniqueQualifiers.size()) {
  1514. LLVM_DEBUG(llvm::dbgs()
  1515. << "Duplicate Qualifiers " << Style->QualifierOrder.size()
  1516. << " vs " << UniqueQualifiers.size() << "\n");
  1517. return ParseError::DuplicateQualifierSpecified;
  1518. }
  1519. auto type = std::find(Style->QualifierOrder.begin(),
  1520. Style->QualifierOrder.end(), "type");
  1521. if (type == Style->QualifierOrder.end())
  1522. return ParseError::MissingQualifierType;
  1523. return ParseError::Success;
  1524. }
  1525. std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
  1526. FormatStyle *Style, bool AllowUnknownOptions,
  1527. llvm::SourceMgr::DiagHandlerTy DiagHandler,
  1528. void *DiagHandlerCtxt) {
  1529. assert(Style);
  1530. FormatStyle::LanguageKind Language = Style->Language;
  1531. assert(Language != FormatStyle::LK_None);
  1532. if (Config.getBuffer().trim().empty())
  1533. return make_error_code(ParseError::Error);
  1534. Style->StyleSet.Clear();
  1535. std::vector<FormatStyle> Styles;
  1536. llvm::yaml::Input Input(Config, /*Ctxt=*/nullptr, DiagHandler,
  1537. DiagHandlerCtxt);
  1538. // DocumentListTraits<vector<FormatStyle>> uses the context to get default
  1539. // values for the fields, keys for which are missing from the configuration.
  1540. // Mapping also uses the context to get the language to find the correct
  1541. // base style.
  1542. Input.setContext(Style);
  1543. Input.setAllowUnknownKeys(AllowUnknownOptions);
  1544. Input >> Styles;
  1545. if (Input.error())
  1546. return Input.error();
  1547. for (unsigned i = 0; i < Styles.size(); ++i) {
  1548. // Ensures that only the first configuration can skip the Language option.
  1549. if (Styles[i].Language == FormatStyle::LK_None && i != 0)
  1550. return make_error_code(ParseError::Error);
  1551. // Ensure that each language is configured at most once.
  1552. for (unsigned j = 0; j < i; ++j) {
  1553. if (Styles[i].Language == Styles[j].Language) {
  1554. LLVM_DEBUG(llvm::dbgs()
  1555. << "Duplicate languages in the config file on positions "
  1556. << j << " and " << i << "\n");
  1557. return make_error_code(ParseError::Error);
  1558. }
  1559. }
  1560. }
  1561. // Look for a suitable configuration starting from the end, so we can
  1562. // find the configuration for the specific language first, and the default
  1563. // configuration (which can only be at slot 0) after it.
  1564. FormatStyle::FormatStyleSet StyleSet;
  1565. bool LanguageFound = false;
  1566. for (const FormatStyle &Style : llvm::reverse(Styles)) {
  1567. if (Style.Language != FormatStyle::LK_None)
  1568. StyleSet.Add(Style);
  1569. if (Style.Language == Language)
  1570. LanguageFound = true;
  1571. }
  1572. if (!LanguageFound) {
  1573. if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None)
  1574. return make_error_code(ParseError::Unsuitable);
  1575. FormatStyle DefaultStyle = Styles[0];
  1576. DefaultStyle.Language = Language;
  1577. StyleSet.Add(std::move(DefaultStyle));
  1578. }
  1579. *Style = *StyleSet.Get(Language);
  1580. if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
  1581. Style->BinPackArguments) {
  1582. // See comment on FormatStyle::TSC_Wrapped.
  1583. return make_error_code(ParseError::BinPackTrailingCommaConflict);
  1584. }
  1585. if (Style->QualifierAlignment != FormatStyle::QAS_Leave)
  1586. return make_error_code(validateQualifierOrder(Style));
  1587. return make_error_code(ParseError::Success);
  1588. }
  1589. std::string configurationAsText(const FormatStyle &Style) {
  1590. std::string Text;
  1591. llvm::raw_string_ostream Stream(Text);
  1592. llvm::yaml::Output Output(Stream);
  1593. // We use the same mapping method for input and output, so we need a non-const
  1594. // reference here.
  1595. FormatStyle NonConstStyle = Style;
  1596. expandPresetsBraceWrapping(NonConstStyle);
  1597. expandPresetsSpaceBeforeParens(NonConstStyle);
  1598. Output << NonConstStyle;
  1599. return Stream.str();
  1600. }
  1601. llvm::Optional<FormatStyle>
  1602. FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const {
  1603. if (!Styles)
  1604. return None;
  1605. auto It = Styles->find(Language);
  1606. if (It == Styles->end())
  1607. return None;
  1608. FormatStyle Style = It->second;
  1609. Style.StyleSet = *this;
  1610. return Style;
  1611. }
  1612. void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
  1613. assert(Style.Language != LK_None &&
  1614. "Cannot add a style for LK_None to a StyleSet");
  1615. assert(
  1616. !Style.StyleSet.Styles &&
  1617. "Cannot add a style associated with an existing StyleSet to a StyleSet");
  1618. if (!Styles)
  1619. Styles = std::make_shared<MapType>();
  1620. (*Styles)[Style.Language] = std::move(Style);
  1621. }
  1622. void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
  1623. llvm::Optional<FormatStyle>
  1624. FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const {
  1625. return StyleSet.Get(Language);
  1626. }
  1627. namespace {
  1628. class BracesRemover : public TokenAnalyzer {
  1629. public:
  1630. BracesRemover(const Environment &Env, const FormatStyle &Style)
  1631. : TokenAnalyzer(Env, Style) {}
  1632. std::pair<tooling::Replacements, unsigned>
  1633. analyze(TokenAnnotator &Annotator,
  1634. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1635. FormatTokenLexer &Tokens) override {
  1636. AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
  1637. tooling::Replacements Result;
  1638. removeBraces(AnnotatedLines, Result);
  1639. return {Result, 0};
  1640. }
  1641. private:
  1642. // Remove optional braces.
  1643. void removeBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
  1644. tooling::Replacements &Result) {
  1645. const auto &SourceMgr = Env.getSourceManager();
  1646. for (AnnotatedLine *Line : Lines) {
  1647. removeBraces(Line->Children, Result);
  1648. if (!Line->Affected)
  1649. continue;
  1650. for (FormatToken *Token = Line->First; Token; Token = Token->Next) {
  1651. if (!Token->Optional)
  1652. continue;
  1653. assert(Token->isOneOf(tok::l_brace, tok::r_brace));
  1654. const auto Start = Token == Line->Last
  1655. ? Token->WhitespaceRange.getBegin()
  1656. : Token->Tok.getLocation();
  1657. const auto Range =
  1658. CharSourceRange::getCharRange(Start, Token->Tok.getEndLoc());
  1659. cantFail(Result.add(tooling::Replacement(SourceMgr, Range, "")));
  1660. }
  1661. }
  1662. }
  1663. };
  1664. class JavaScriptRequoter : public TokenAnalyzer {
  1665. public:
  1666. JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
  1667. : TokenAnalyzer(Env, Style) {}
  1668. std::pair<tooling::Replacements, unsigned>
  1669. analyze(TokenAnnotator &Annotator,
  1670. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1671. FormatTokenLexer &Tokens) override {
  1672. AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
  1673. tooling::Replacements Result;
  1674. requoteJSStringLiteral(AnnotatedLines, Result);
  1675. return {Result, 0};
  1676. }
  1677. private:
  1678. // Replaces double/single-quoted string literal as appropriate, re-escaping
  1679. // the contents in the process.
  1680. void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
  1681. tooling::Replacements &Result) {
  1682. for (AnnotatedLine *Line : Lines) {
  1683. requoteJSStringLiteral(Line->Children, Result);
  1684. if (!Line->Affected)
  1685. continue;
  1686. for (FormatToken *FormatTok = Line->First; FormatTok;
  1687. FormatTok = FormatTok->Next) {
  1688. StringRef Input = FormatTok->TokenText;
  1689. if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
  1690. // NB: testing for not starting with a double quote to avoid
  1691. // breaking `template strings`.
  1692. (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
  1693. !Input.startswith("\"")) ||
  1694. (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
  1695. !Input.startswith("\'")))
  1696. continue;
  1697. // Change start and end quote.
  1698. bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
  1699. SourceLocation Start = FormatTok->Tok.getLocation();
  1700. auto Replace = [&](SourceLocation Start, unsigned Length,
  1701. StringRef ReplacementText) {
  1702. auto Err = Result.add(tooling::Replacement(
  1703. Env.getSourceManager(), Start, Length, ReplacementText));
  1704. // FIXME: handle error. For now, print error message and skip the
  1705. // replacement for release version.
  1706. if (Err) {
  1707. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  1708. assert(false);
  1709. }
  1710. };
  1711. Replace(Start, 1, IsSingle ? "'" : "\"");
  1712. Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
  1713. IsSingle ? "'" : "\"");
  1714. // Escape internal quotes.
  1715. bool Escaped = false;
  1716. for (size_t i = 1; i < Input.size() - 1; i++) {
  1717. switch (Input[i]) {
  1718. case '\\':
  1719. if (!Escaped && i + 1 < Input.size() &&
  1720. ((IsSingle && Input[i + 1] == '"') ||
  1721. (!IsSingle && Input[i + 1] == '\''))) {
  1722. // Remove this \, it's escaping a " or ' that no longer needs
  1723. // escaping
  1724. Replace(Start.getLocWithOffset(i), 1, "");
  1725. continue;
  1726. }
  1727. Escaped = !Escaped;
  1728. break;
  1729. case '\"':
  1730. case '\'':
  1731. if (!Escaped && IsSingle == (Input[i] == '\'')) {
  1732. // Escape the quote.
  1733. Replace(Start.getLocWithOffset(i), 0, "\\");
  1734. }
  1735. Escaped = false;
  1736. break;
  1737. default:
  1738. Escaped = false;
  1739. break;
  1740. }
  1741. }
  1742. }
  1743. }
  1744. }
  1745. };
  1746. class Formatter : public TokenAnalyzer {
  1747. public:
  1748. Formatter(const Environment &Env, const FormatStyle &Style,
  1749. FormattingAttemptStatus *Status)
  1750. : TokenAnalyzer(Env, Style), Status(Status) {}
  1751. std::pair<tooling::Replacements, unsigned>
  1752. analyze(TokenAnnotator &Annotator,
  1753. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1754. FormatTokenLexer &Tokens) override {
  1755. tooling::Replacements Result;
  1756. deriveLocalStyle(AnnotatedLines);
  1757. AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
  1758. for (AnnotatedLine *Line : AnnotatedLines)
  1759. Annotator.calculateFormattingInformation(*Line);
  1760. Annotator.setCommentLineLevels(AnnotatedLines);
  1761. WhitespaceManager Whitespaces(
  1762. Env.getSourceManager(), Style,
  1763. Style.DeriveLineEnding
  1764. ? WhitespaceManager::inputUsesCRLF(
  1765. Env.getSourceManager().getBufferData(Env.getFileID()),
  1766. Style.UseCRLF)
  1767. : Style.UseCRLF);
  1768. ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
  1769. Env.getSourceManager(), Whitespaces, Encoding,
  1770. BinPackInconclusiveFunctions);
  1771. unsigned Penalty =
  1772. UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
  1773. Tokens.getKeywords(), Env.getSourceManager(),
  1774. Status)
  1775. .format(AnnotatedLines, /*DryRun=*/false,
  1776. /*AdditionalIndent=*/0,
  1777. /*FixBadIndentation=*/false,
  1778. /*FirstStartColumn=*/Env.getFirstStartColumn(),
  1779. /*NextStartColumn=*/Env.getNextStartColumn(),
  1780. /*LastStartColumn=*/Env.getLastStartColumn());
  1781. for (const auto &R : Whitespaces.generateReplacements())
  1782. if (Result.add(R))
  1783. return std::make_pair(Result, 0);
  1784. return std::make_pair(Result, Penalty);
  1785. }
  1786. private:
  1787. bool
  1788. hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
  1789. for (const AnnotatedLine *Line : Lines) {
  1790. if (hasCpp03IncompatibleFormat(Line->Children))
  1791. return true;
  1792. for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
  1793. if (!Tok->hasWhitespaceBefore()) {
  1794. if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
  1795. return true;
  1796. if (Tok->is(TT_TemplateCloser) &&
  1797. Tok->Previous->is(TT_TemplateCloser))
  1798. return true;
  1799. }
  1800. }
  1801. }
  1802. return false;
  1803. }
  1804. int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
  1805. int AlignmentDiff = 0;
  1806. for (const AnnotatedLine *Line : Lines) {
  1807. AlignmentDiff += countVariableAlignments(Line->Children);
  1808. for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
  1809. if (!Tok->is(TT_PointerOrReference))
  1810. continue;
  1811. bool SpaceBefore = Tok->hasWhitespaceBefore();
  1812. bool SpaceAfter = Tok->Next->hasWhitespaceBefore();
  1813. if (SpaceBefore && !SpaceAfter)
  1814. ++AlignmentDiff;
  1815. if (!SpaceBefore && SpaceAfter)
  1816. --AlignmentDiff;
  1817. }
  1818. }
  1819. return AlignmentDiff;
  1820. }
  1821. void
  1822. deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  1823. bool HasBinPackedFunction = false;
  1824. bool HasOnePerLineFunction = false;
  1825. for (AnnotatedLine *Line : AnnotatedLines) {
  1826. if (!Line->First->Next)
  1827. continue;
  1828. FormatToken *Tok = Line->First->Next;
  1829. while (Tok->Next) {
  1830. if (Tok->is(PPK_BinPacked))
  1831. HasBinPackedFunction = true;
  1832. if (Tok->is(PPK_OnePerLine))
  1833. HasOnePerLineFunction = true;
  1834. Tok = Tok->Next;
  1835. }
  1836. }
  1837. if (Style.DerivePointerAlignment) {
  1838. Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
  1839. ? FormatStyle::PAS_Left
  1840. : FormatStyle::PAS_Right;
  1841. Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
  1842. }
  1843. if (Style.Standard == FormatStyle::LS_Auto)
  1844. Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
  1845. ? FormatStyle::LS_Latest
  1846. : FormatStyle::LS_Cpp03;
  1847. BinPackInconclusiveFunctions =
  1848. HasBinPackedFunction || !HasOnePerLineFunction;
  1849. }
  1850. bool BinPackInconclusiveFunctions;
  1851. FormattingAttemptStatus *Status;
  1852. };
  1853. /// TrailingCommaInserter inserts trailing commas into container literals.
  1854. /// E.g.:
  1855. /// const x = [
  1856. /// 1,
  1857. /// ];
  1858. /// TrailingCommaInserter runs after formatting. To avoid causing a required
  1859. /// reformatting (and thus reflow), it never inserts a comma that'd exceed the
  1860. /// ColumnLimit.
  1861. ///
  1862. /// Because trailing commas disable binpacking of arrays, TrailingCommaInserter
  1863. /// is conceptually incompatible with bin packing.
  1864. class TrailingCommaInserter : public TokenAnalyzer {
  1865. public:
  1866. TrailingCommaInserter(const Environment &Env, const FormatStyle &Style)
  1867. : TokenAnalyzer(Env, Style) {}
  1868. std::pair<tooling::Replacements, unsigned>
  1869. analyze(TokenAnnotator &Annotator,
  1870. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1871. FormatTokenLexer &Tokens) override {
  1872. AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
  1873. tooling::Replacements Result;
  1874. insertTrailingCommas(AnnotatedLines, Result);
  1875. return {Result, 0};
  1876. }
  1877. private:
  1878. /// Inserts trailing commas in [] and {} initializers if they wrap over
  1879. /// multiple lines.
  1880. void insertTrailingCommas(SmallVectorImpl<AnnotatedLine *> &Lines,
  1881. tooling::Replacements &Result) {
  1882. for (AnnotatedLine *Line : Lines) {
  1883. insertTrailingCommas(Line->Children, Result);
  1884. if (!Line->Affected)
  1885. continue;
  1886. for (FormatToken *FormatTok = Line->First; FormatTok;
  1887. FormatTok = FormatTok->Next) {
  1888. if (FormatTok->NewlinesBefore == 0)
  1889. continue;
  1890. FormatToken *Matching = FormatTok->MatchingParen;
  1891. if (!Matching || !FormatTok->getPreviousNonComment())
  1892. continue;
  1893. if (!(FormatTok->is(tok::r_square) &&
  1894. Matching->is(TT_ArrayInitializerLSquare)) &&
  1895. !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral)))
  1896. continue;
  1897. FormatToken *Prev = FormatTok->getPreviousNonComment();
  1898. if (Prev->is(tok::comma) || Prev->is(tok::semi))
  1899. continue;
  1900. // getEndLoc is not reliably set during re-lexing, use text length
  1901. // instead.
  1902. SourceLocation Start =
  1903. Prev->Tok.getLocation().getLocWithOffset(Prev->TokenText.size());
  1904. // If inserting a comma would push the code over the column limit, skip
  1905. // this location - it'd introduce an unstable formatting due to the
  1906. // required reflow.
  1907. unsigned ColumnNumber =
  1908. Env.getSourceManager().getSpellingColumnNumber(Start);
  1909. if (ColumnNumber > Style.ColumnLimit)
  1910. continue;
  1911. // Comma insertions cannot conflict with each other, and this pass has a
  1912. // clean set of Replacements, so the operation below cannot fail.
  1913. cantFail(Result.add(
  1914. tooling::Replacement(Env.getSourceManager(), Start, 0, ",")));
  1915. }
  1916. }
  1917. }
  1918. };
  1919. // This class clean up the erroneous/redundant code around the given ranges in
  1920. // file.
  1921. class Cleaner : public TokenAnalyzer {
  1922. public:
  1923. Cleaner(const Environment &Env, const FormatStyle &Style)
  1924. : TokenAnalyzer(Env, Style),
  1925. DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
  1926. // FIXME: eliminate unused parameters.
  1927. std::pair<tooling::Replacements, unsigned>
  1928. analyze(TokenAnnotator &Annotator,
  1929. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1930. FormatTokenLexer &Tokens) override {
  1931. // FIXME: in the current implementation the granularity of affected range
  1932. // is an annotated line. However, this is not sufficient. Furthermore,
  1933. // redundant code introduced by replacements does not necessarily
  1934. // intercept with ranges of replacements that result in the redundancy.
  1935. // To determine if some redundant code is actually introduced by
  1936. // replacements(e.g. deletions), we need to come up with a more
  1937. // sophisticated way of computing affected ranges.
  1938. AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
  1939. checkEmptyNamespace(AnnotatedLines);
  1940. for (auto *Line : AnnotatedLines)
  1941. cleanupLine(Line);
  1942. return {generateFixes(), 0};
  1943. }
  1944. private:
  1945. void cleanupLine(AnnotatedLine *Line) {
  1946. for (auto *Child : Line->Children) {
  1947. cleanupLine(Child);
  1948. }
  1949. if (Line->Affected) {
  1950. cleanupRight(Line->First, tok::comma, tok::comma);
  1951. cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
  1952. cleanupRight(Line->First, tok::l_paren, tok::comma);
  1953. cleanupLeft(Line->First, tok::comma, tok::r_paren);
  1954. cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
  1955. cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
  1956. cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
  1957. }
  1958. }
  1959. bool containsOnlyComments(const AnnotatedLine &Line) {
  1960. for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
  1961. if (Tok->isNot(tok::comment))
  1962. return false;
  1963. }
  1964. return true;
  1965. }
  1966. // Iterate through all lines and remove any empty (nested) namespaces.
  1967. void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  1968. std::set<unsigned> DeletedLines;
  1969. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  1970. auto &Line = *AnnotatedLines[i];
  1971. if (Line.startsWithNamespace()) {
  1972. checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
  1973. }
  1974. }
  1975. for (auto Line : DeletedLines) {
  1976. FormatToken *Tok = AnnotatedLines[Line]->First;
  1977. while (Tok) {
  1978. deleteToken(Tok);
  1979. Tok = Tok->Next;
  1980. }
  1981. }
  1982. }
  1983. // The function checks if the namespace, which starts from \p CurrentLine, and
  1984. // its nested namespaces are empty and delete them if they are empty. It also
  1985. // sets \p NewLine to the last line checked.
  1986. // Returns true if the current namespace is empty.
  1987. bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1988. unsigned CurrentLine, unsigned &NewLine,
  1989. std::set<unsigned> &DeletedLines) {
  1990. unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
  1991. if (Style.BraceWrapping.AfterNamespace) {
  1992. // If the left brace is in a new line, we should consume it first so that
  1993. // it does not make the namespace non-empty.
  1994. // FIXME: error handling if there is no left brace.
  1995. if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
  1996. NewLine = CurrentLine;
  1997. return false;
  1998. }
  1999. } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
  2000. return false;
  2001. }
  2002. while (++CurrentLine < End) {
  2003. if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
  2004. break;
  2005. if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
  2006. if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
  2007. DeletedLines))
  2008. return false;
  2009. CurrentLine = NewLine;
  2010. continue;
  2011. }
  2012. if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
  2013. continue;
  2014. // If there is anything other than comments or nested namespaces in the
  2015. // current namespace, the namespace cannot be empty.
  2016. NewLine = CurrentLine;
  2017. return false;
  2018. }
  2019. NewLine = CurrentLine;
  2020. if (CurrentLine >= End)
  2021. return false;
  2022. // Check if the empty namespace is actually affected by changed ranges.
  2023. if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
  2024. AnnotatedLines[InitLine]->First->Tok.getLocation(),
  2025. AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
  2026. return false;
  2027. for (unsigned i = InitLine; i <= CurrentLine; ++i) {
  2028. DeletedLines.insert(i);
  2029. }
  2030. return true;
  2031. }
  2032. // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
  2033. // of the token in the pair if the left token has \p LK token kind and the
  2034. // right token has \p RK token kind. If \p DeleteLeft is true, the left token
  2035. // is deleted on match; otherwise, the right token is deleted.
  2036. template <typename LeftKind, typename RightKind>
  2037. void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
  2038. bool DeleteLeft) {
  2039. auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
  2040. for (auto *Res = Tok.Next; Res; Res = Res->Next)
  2041. if (!Res->is(tok::comment) &&
  2042. DeletedTokens.find(Res) == DeletedTokens.end())
  2043. return Res;
  2044. return nullptr;
  2045. };
  2046. for (auto *Left = Start; Left;) {
  2047. auto *Right = NextNotDeleted(*Left);
  2048. if (!Right)
  2049. break;
  2050. if (Left->is(LK) && Right->is(RK)) {
  2051. deleteToken(DeleteLeft ? Left : Right);
  2052. for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
  2053. deleteToken(Tok);
  2054. // If the right token is deleted, we should keep the left token
  2055. // unchanged and pair it with the new right token.
  2056. if (!DeleteLeft)
  2057. continue;
  2058. }
  2059. Left = Right;
  2060. }
  2061. }
  2062. template <typename LeftKind, typename RightKind>
  2063. void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
  2064. cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
  2065. }
  2066. template <typename LeftKind, typename RightKind>
  2067. void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
  2068. cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
  2069. }
  2070. // Delete the given token.
  2071. inline void deleteToken(FormatToken *Tok) {
  2072. if (Tok)
  2073. DeletedTokens.insert(Tok);
  2074. }
  2075. tooling::Replacements generateFixes() {
  2076. tooling::Replacements Fixes;
  2077. std::vector<FormatToken *> Tokens;
  2078. std::copy(DeletedTokens.begin(), DeletedTokens.end(),
  2079. std::back_inserter(Tokens));
  2080. // Merge multiple continuous token deletions into one big deletion so that
  2081. // the number of replacements can be reduced. This makes computing affected
  2082. // ranges more efficient when we run reformat on the changed code.
  2083. unsigned Idx = 0;
  2084. while (Idx < Tokens.size()) {
  2085. unsigned St = Idx, End = Idx;
  2086. while ((End + 1) < Tokens.size() &&
  2087. Tokens[End]->Next == Tokens[End + 1]) {
  2088. ++End;
  2089. }
  2090. auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
  2091. Tokens[End]->Tok.getEndLoc());
  2092. auto Err =
  2093. Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
  2094. // FIXME: better error handling. for now just print error message and skip
  2095. // for the release version.
  2096. if (Err) {
  2097. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  2098. assert(false && "Fixes must not conflict!");
  2099. }
  2100. Idx = End + 1;
  2101. }
  2102. return Fixes;
  2103. }
  2104. // Class for less-than inequality comparason for the set `RedundantTokens`.
  2105. // We store tokens in the order they appear in the translation unit so that
  2106. // we do not need to sort them in `generateFixes()`.
  2107. struct FormatTokenLess {
  2108. FormatTokenLess(const SourceManager &SM) : SM(SM) {}
  2109. bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
  2110. return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
  2111. RHS->Tok.getLocation());
  2112. }
  2113. const SourceManager &SM;
  2114. };
  2115. // Tokens to be deleted.
  2116. std::set<FormatToken *, FormatTokenLess> DeletedTokens;
  2117. };
  2118. class ObjCHeaderStyleGuesser : public TokenAnalyzer {
  2119. public:
  2120. ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
  2121. : TokenAnalyzer(Env, Style), IsObjC(false) {}
  2122. std::pair<tooling::Replacements, unsigned>
  2123. analyze(TokenAnnotator &Annotator,
  2124. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  2125. FormatTokenLexer &Tokens) override {
  2126. assert(Style.Language == FormatStyle::LK_Cpp);
  2127. IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
  2128. Tokens.getKeywords());
  2129. tooling::Replacements Result;
  2130. return {Result, 0};
  2131. }
  2132. bool isObjC() { return IsObjC; }
  2133. private:
  2134. static bool
  2135. guessIsObjC(const SourceManager &SourceManager,
  2136. const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  2137. const AdditionalKeywords &Keywords) {
  2138. // Keep this array sorted, since we are binary searching over it.
  2139. static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
  2140. "CGFloat",
  2141. "CGPoint",
  2142. "CGPointMake",
  2143. "CGPointZero",
  2144. "CGRect",
  2145. "CGRectEdge",
  2146. "CGRectInfinite",
  2147. "CGRectMake",
  2148. "CGRectNull",
  2149. "CGRectZero",
  2150. "CGSize",
  2151. "CGSizeMake",
  2152. "CGVector",
  2153. "CGVectorMake",
  2154. "NSAffineTransform",
  2155. "NSArray",
  2156. "NSAttributedString",
  2157. "NSBlockOperation",
  2158. "NSBundle",
  2159. "NSCache",
  2160. "NSCalendar",
  2161. "NSCharacterSet",
  2162. "NSCountedSet",
  2163. "NSData",
  2164. "NSDataDetector",
  2165. "NSDecimal",
  2166. "NSDecimalNumber",
  2167. "NSDictionary",
  2168. "NSEdgeInsets",
  2169. "NSHashTable",
  2170. "NSIndexPath",
  2171. "NSIndexSet",
  2172. "NSInteger",
  2173. "NSInvocationOperation",
  2174. "NSLocale",
  2175. "NSMapTable",
  2176. "NSMutableArray",
  2177. "NSMutableAttributedString",
  2178. "NSMutableCharacterSet",
  2179. "NSMutableData",
  2180. "NSMutableDictionary",
  2181. "NSMutableIndexSet",
  2182. "NSMutableOrderedSet",
  2183. "NSMutableSet",
  2184. "NSMutableString",
  2185. "NSNumber",
  2186. "NSNumberFormatter",
  2187. "NSObject",
  2188. "NSOperation",
  2189. "NSOperationQueue",
  2190. "NSOperationQueuePriority",
  2191. "NSOrderedSet",
  2192. "NSPoint",
  2193. "NSPointerArray",
  2194. "NSQualityOfService",
  2195. "NSRange",
  2196. "NSRect",
  2197. "NSRegularExpression",
  2198. "NSSet",
  2199. "NSSize",
  2200. "NSString",
  2201. "NSTimeZone",
  2202. "NSUInteger",
  2203. "NSURL",
  2204. "NSURLComponents",
  2205. "NSURLQueryItem",
  2206. "NSUUID",
  2207. "NSValue",
  2208. "UIImage",
  2209. "UIView",
  2210. };
  2211. for (auto Line : AnnotatedLines) {
  2212. if (Line->First && (Line->First->TokenText.startswith("#") ||
  2213. Line->First->TokenText == "__pragma" ||
  2214. Line->First->TokenText == "_Pragma"))
  2215. continue;
  2216. for (const FormatToken *FormatTok = Line->First; FormatTok;
  2217. FormatTok = FormatTok->Next) {
  2218. if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
  2219. (FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword ||
  2220. FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
  2221. tok::l_brace))) ||
  2222. (FormatTok->Tok.isAnyIdentifier() &&
  2223. std::binary_search(std::begin(FoundationIdentifiers),
  2224. std::end(FoundationIdentifiers),
  2225. FormatTok->TokenText)) ||
  2226. FormatTok->is(TT_ObjCStringLiteral) ||
  2227. FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
  2228. Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
  2229. TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
  2230. TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
  2231. TT_ObjCProperty)) {
  2232. LLVM_DEBUG(llvm::dbgs()
  2233. << "Detected ObjC at location "
  2234. << FormatTok->Tok.getLocation().printToString(
  2235. SourceManager)
  2236. << " token: " << FormatTok->TokenText << " token type: "
  2237. << getTokenTypeName(FormatTok->getType()) << "\n");
  2238. return true;
  2239. }
  2240. if (guessIsObjC(SourceManager, Line->Children, Keywords))
  2241. return true;
  2242. }
  2243. }
  2244. return false;
  2245. }
  2246. bool IsObjC;
  2247. };
  2248. struct IncludeDirective {
  2249. StringRef Filename;
  2250. StringRef Text;
  2251. unsigned Offset;
  2252. int Category;
  2253. int Priority;
  2254. };
  2255. struct JavaImportDirective {
  2256. StringRef Identifier;
  2257. StringRef Text;
  2258. unsigned Offset;
  2259. std::vector<StringRef> AssociatedCommentLines;
  2260. bool IsStatic;
  2261. };
  2262. } // end anonymous namespace
  2263. // Determines whether 'Ranges' intersects with ('Start', 'End').
  2264. static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
  2265. unsigned End) {
  2266. for (auto Range : Ranges) {
  2267. if (Range.getOffset() < End &&
  2268. Range.getOffset() + Range.getLength() > Start)
  2269. return true;
  2270. }
  2271. return false;
  2272. }
  2273. // Returns a pair (Index, OffsetToEOL) describing the position of the cursor
  2274. // before sorting/deduplicating. Index is the index of the include under the
  2275. // cursor in the original set of includes. If this include has duplicates, it is
  2276. // the index of the first of the duplicates as the others are going to be
  2277. // removed. OffsetToEOL describes the cursor's position relative to the end of
  2278. // its current line.
  2279. // If `Cursor` is not on any #include, `Index` will be UINT_MAX.
  2280. static std::pair<unsigned, unsigned>
  2281. FindCursorIndex(const SmallVectorImpl<IncludeDirective> &Includes,
  2282. const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) {
  2283. unsigned CursorIndex = UINT_MAX;
  2284. unsigned OffsetToEOL = 0;
  2285. for (int i = 0, e = Includes.size(); i != e; ++i) {
  2286. unsigned Start = Includes[Indices[i]].Offset;
  2287. unsigned End = Start + Includes[Indices[i]].Text.size();
  2288. if (!(Cursor >= Start && Cursor < End))
  2289. continue;
  2290. CursorIndex = Indices[i];
  2291. OffsetToEOL = End - Cursor;
  2292. // Put the cursor on the only remaining #include among the duplicate
  2293. // #includes.
  2294. while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
  2295. CursorIndex = i;
  2296. break;
  2297. }
  2298. return std::make_pair(CursorIndex, OffsetToEOL);
  2299. }
  2300. // Replace all "\r\n" with "\n".
  2301. std::string replaceCRLF(const std::string &Code) {
  2302. std::string NewCode;
  2303. size_t Pos = 0, LastPos = 0;
  2304. do {
  2305. Pos = Code.find("\r\n", LastPos);
  2306. if (Pos == LastPos) {
  2307. ++LastPos;
  2308. continue;
  2309. }
  2310. if (Pos == std::string::npos) {
  2311. NewCode += Code.substr(LastPos);
  2312. break;
  2313. }
  2314. NewCode += Code.substr(LastPos, Pos - LastPos) + "\n";
  2315. LastPos = Pos + 2;
  2316. } while (Pos != std::string::npos);
  2317. return NewCode;
  2318. }
  2319. // Sorts and deduplicate a block of includes given by 'Includes' alphabetically
  2320. // adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
  2321. // source order.
  2322. // #include directives with the same text will be deduplicated, and only the
  2323. // first #include in the duplicate #includes remains. If the `Cursor` is
  2324. // provided and put on a deleted #include, it will be moved to the remaining
  2325. // #include in the duplicate #includes.
  2326. static void sortCppIncludes(const FormatStyle &Style,
  2327. const SmallVectorImpl<IncludeDirective> &Includes,
  2328. ArrayRef<tooling::Range> Ranges, StringRef FileName,
  2329. StringRef Code, tooling::Replacements &Replaces,
  2330. unsigned *Cursor) {
  2331. tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
  2332. unsigned IncludesBeginOffset = Includes.front().Offset;
  2333. unsigned IncludesEndOffset =
  2334. Includes.back().Offset + Includes.back().Text.size();
  2335. unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
  2336. if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
  2337. return;
  2338. SmallVector<unsigned, 16> Indices;
  2339. Indices.resize(Includes.size());
  2340. std::iota(Indices.begin(), Indices.end(), 0);
  2341. if (Style.SortIncludes == FormatStyle::SI_CaseInsensitive) {
  2342. llvm::stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
  2343. const auto LHSFilenameLower = Includes[LHSI].Filename.lower();
  2344. const auto RHSFilenameLower = Includes[RHSI].Filename.lower();
  2345. return std::tie(Includes[LHSI].Priority, LHSFilenameLower,
  2346. Includes[LHSI].Filename) <
  2347. std::tie(Includes[RHSI].Priority, RHSFilenameLower,
  2348. Includes[RHSI].Filename);
  2349. });
  2350. } else {
  2351. llvm::stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
  2352. return std::tie(Includes[LHSI].Priority, Includes[LHSI].Filename) <
  2353. std::tie(Includes[RHSI].Priority, Includes[RHSI].Filename);
  2354. });
  2355. }
  2356. // The index of the include on which the cursor will be put after
  2357. // sorting/deduplicating.
  2358. unsigned CursorIndex;
  2359. // The offset from cursor to the end of line.
  2360. unsigned CursorToEOLOffset;
  2361. if (Cursor)
  2362. std::tie(CursorIndex, CursorToEOLOffset) =
  2363. FindCursorIndex(Includes, Indices, *Cursor);
  2364. // Deduplicate #includes.
  2365. Indices.erase(std::unique(Indices.begin(), Indices.end(),
  2366. [&](unsigned LHSI, unsigned RHSI) {
  2367. return Includes[LHSI].Text.trim() ==
  2368. Includes[RHSI].Text.trim();
  2369. }),
  2370. Indices.end());
  2371. int CurrentCategory = Includes.front().Category;
  2372. // If the #includes are out of order, we generate a single replacement fixing
  2373. // the entire block. Otherwise, no replacement is generated.
  2374. // In case Style.IncldueStyle.IncludeBlocks != IBS_Preserve, this check is not
  2375. // enough as additional newlines might be added or removed across #include
  2376. // blocks. This we handle below by generating the updated #imclude blocks and
  2377. // comparing it to the original.
  2378. if (Indices.size() == Includes.size() && llvm::is_sorted(Indices) &&
  2379. Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve)
  2380. return;
  2381. std::string result;
  2382. for (unsigned Index : Indices) {
  2383. if (!result.empty()) {
  2384. result += "\n";
  2385. if (Style.IncludeStyle.IncludeBlocks ==
  2386. tooling::IncludeStyle::IBS_Regroup &&
  2387. CurrentCategory != Includes[Index].Category)
  2388. result += "\n";
  2389. }
  2390. result += Includes[Index].Text;
  2391. if (Cursor && CursorIndex == Index)
  2392. *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
  2393. CurrentCategory = Includes[Index].Category;
  2394. }
  2395. // If the #includes are out of order, we generate a single replacement fixing
  2396. // the entire range of blocks. Otherwise, no replacement is generated.
  2397. if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
  2398. IncludesBeginOffset, IncludesBlockSize))))
  2399. return;
  2400. auto Err = Replaces.add(tooling::Replacement(
  2401. FileName, Includes.front().Offset, IncludesBlockSize, result));
  2402. // FIXME: better error handling. For now, just skip the replacement for the
  2403. // release version.
  2404. if (Err) {
  2405. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  2406. assert(false);
  2407. }
  2408. }
  2409. namespace {
  2410. const char CppIncludeRegexPattern[] =
  2411. R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
  2412. } // anonymous namespace
  2413. tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
  2414. ArrayRef<tooling::Range> Ranges,
  2415. StringRef FileName,
  2416. tooling::Replacements &Replaces,
  2417. unsigned *Cursor) {
  2418. unsigned Prev = llvm::StringSwitch<size_t>(Code)
  2419. .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
  2420. .Default(0);
  2421. unsigned SearchFrom = 0;
  2422. llvm::Regex IncludeRegex(CppIncludeRegexPattern);
  2423. SmallVector<StringRef, 4> Matches;
  2424. SmallVector<IncludeDirective, 16> IncludesInBlock;
  2425. // In compiled files, consider the first #include to be the main #include of
  2426. // the file if it is not a system #include. This ensures that the header
  2427. // doesn't have hidden dependencies
  2428. // (http://llvm.org/docs/CodingStandards.html#include-style).
  2429. //
  2430. // FIXME: Do some validation, e.g. edit distance of the base name, to fix
  2431. // cases where the first #include is unlikely to be the main header.
  2432. tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
  2433. bool FirstIncludeBlock = true;
  2434. bool MainIncludeFound = false;
  2435. bool FormattingOff = false;
  2436. // '[' must be the first and '-' the last character inside [...].
  2437. llvm::Regex RawStringRegex(
  2438. "R\"([][A-Za-z0-9_{}#<>%:;.?*+/^&\\$|~!=,'-]*)\\(");
  2439. SmallVector<StringRef, 2> RawStringMatches;
  2440. std::string RawStringTermination = ")\"";
  2441. for (;;) {
  2442. auto Pos = Code.find('\n', SearchFrom);
  2443. StringRef Line =
  2444. Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
  2445. StringRef Trimmed = Line.trim();
  2446. // #includes inside raw string literals need to be ignored.
  2447. // or we will sort the contents of the string.
  2448. // Skip past until we think we are at the rawstring literal close.
  2449. if (RawStringRegex.match(Trimmed, &RawStringMatches)) {
  2450. std::string CharSequence = RawStringMatches[1].str();
  2451. RawStringTermination = ")" + CharSequence + "\"";
  2452. FormattingOff = true;
  2453. }
  2454. if (Trimmed.contains(RawStringTermination)) {
  2455. FormattingOff = false;
  2456. }
  2457. if (Trimmed == "// clang-format off" || Trimmed == "/* clang-format off */")
  2458. FormattingOff = true;
  2459. else if (Trimmed == "// clang-format on" ||
  2460. Trimmed == "/* clang-format on */")
  2461. FormattingOff = false;
  2462. const bool EmptyLineSkipped =
  2463. Trimmed.empty() &&
  2464. (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge ||
  2465. Style.IncludeStyle.IncludeBlocks ==
  2466. tooling::IncludeStyle::IBS_Regroup);
  2467. bool MergeWithNextLine = Trimmed.endswith("\\");
  2468. if (!FormattingOff && !MergeWithNextLine) {
  2469. if (IncludeRegex.match(Line, &Matches)) {
  2470. StringRef IncludeName = Matches[2];
  2471. if (Line.contains("/*") && !Line.contains("*/")) {
  2472. // #include with a start of a block comment, but without the end.
  2473. // Need to keep all the lines until the end of the comment together.
  2474. // FIXME: This is somehow simplified check that probably does not work
  2475. // correctly if there are multiple comments on a line.
  2476. Pos = Code.find("*/", SearchFrom);
  2477. Line = Code.substr(
  2478. Prev, (Pos != StringRef::npos ? Pos + 2 : Code.size()) - Prev);
  2479. }
  2480. int Category = Categories.getIncludePriority(
  2481. IncludeName,
  2482. /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
  2483. int Priority = Categories.getSortIncludePriority(
  2484. IncludeName, !MainIncludeFound && FirstIncludeBlock);
  2485. if (Category == 0)
  2486. MainIncludeFound = true;
  2487. IncludesInBlock.push_back(
  2488. {IncludeName, Line, Prev, Category, Priority});
  2489. } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
  2490. sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code,
  2491. Replaces, Cursor);
  2492. IncludesInBlock.clear();
  2493. if (Trimmed.startswith("#pragma hdrstop")) // Precompiled headers.
  2494. FirstIncludeBlock = true;
  2495. else
  2496. FirstIncludeBlock = false;
  2497. }
  2498. }
  2499. if (Pos == StringRef::npos || Pos + 1 == Code.size())
  2500. break;
  2501. if (!MergeWithNextLine)
  2502. Prev = Pos + 1;
  2503. SearchFrom = Pos + 1;
  2504. }
  2505. if (!IncludesInBlock.empty()) {
  2506. sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code, Replaces,
  2507. Cursor);
  2508. }
  2509. return Replaces;
  2510. }
  2511. // Returns group number to use as a first order sort on imports. Gives UINT_MAX
  2512. // if the import does not match any given groups.
  2513. static unsigned findJavaImportGroup(const FormatStyle &Style,
  2514. StringRef ImportIdentifier) {
  2515. unsigned LongestMatchIndex = UINT_MAX;
  2516. unsigned LongestMatchLength = 0;
  2517. for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
  2518. const std::string &GroupPrefix = Style.JavaImportGroups[I];
  2519. if (ImportIdentifier.startswith(GroupPrefix) &&
  2520. GroupPrefix.length() > LongestMatchLength) {
  2521. LongestMatchIndex = I;
  2522. LongestMatchLength = GroupPrefix.length();
  2523. }
  2524. }
  2525. return LongestMatchIndex;
  2526. }
  2527. // Sorts and deduplicates a block of includes given by 'Imports' based on
  2528. // JavaImportGroups, then adding the necessary replacement to 'Replaces'.
  2529. // Import declarations with the same text will be deduplicated. Between each
  2530. // import group, a newline is inserted, and within each import group, a
  2531. // lexicographic sort based on ASCII value is performed.
  2532. static void sortJavaImports(const FormatStyle &Style,
  2533. const SmallVectorImpl<JavaImportDirective> &Imports,
  2534. ArrayRef<tooling::Range> Ranges, StringRef FileName,
  2535. StringRef Code, tooling::Replacements &Replaces) {
  2536. unsigned ImportsBeginOffset = Imports.front().Offset;
  2537. unsigned ImportsEndOffset =
  2538. Imports.back().Offset + Imports.back().Text.size();
  2539. unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
  2540. if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
  2541. return;
  2542. SmallVector<unsigned, 16> Indices;
  2543. Indices.resize(Imports.size());
  2544. std::iota(Indices.begin(), Indices.end(), 0);
  2545. SmallVector<unsigned, 16> JavaImportGroups;
  2546. JavaImportGroups.reserve(Imports.size());
  2547. for (const JavaImportDirective &Import : Imports)
  2548. JavaImportGroups.push_back(findJavaImportGroup(Style, Import.Identifier));
  2549. bool StaticImportAfterNormalImport =
  2550. Style.SortJavaStaticImport == FormatStyle::SJSIO_After;
  2551. llvm::sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
  2552. // Negating IsStatic to push static imports above non-static imports.
  2553. return std::make_tuple(!Imports[LHSI].IsStatic ^
  2554. StaticImportAfterNormalImport,
  2555. JavaImportGroups[LHSI], Imports[LHSI].Identifier) <
  2556. std::make_tuple(!Imports[RHSI].IsStatic ^
  2557. StaticImportAfterNormalImport,
  2558. JavaImportGroups[RHSI], Imports[RHSI].Identifier);
  2559. });
  2560. // Deduplicate imports.
  2561. Indices.erase(std::unique(Indices.begin(), Indices.end(),
  2562. [&](unsigned LHSI, unsigned RHSI) {
  2563. return Imports[LHSI].Text == Imports[RHSI].Text;
  2564. }),
  2565. Indices.end());
  2566. bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
  2567. unsigned CurrentImportGroup = JavaImportGroups[Indices.front()];
  2568. std::string result;
  2569. for (unsigned Index : Indices) {
  2570. if (!result.empty()) {
  2571. result += "\n";
  2572. if (CurrentIsStatic != Imports[Index].IsStatic ||
  2573. CurrentImportGroup != JavaImportGroups[Index])
  2574. result += "\n";
  2575. }
  2576. for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
  2577. result += CommentLine;
  2578. result += "\n";
  2579. }
  2580. result += Imports[Index].Text;
  2581. CurrentIsStatic = Imports[Index].IsStatic;
  2582. CurrentImportGroup = JavaImportGroups[Index];
  2583. }
  2584. // If the imports are out of order, we generate a single replacement fixing
  2585. // the entire block. Otherwise, no replacement is generated.
  2586. if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
  2587. Imports.front().Offset, ImportsBlockSize))))
  2588. return;
  2589. auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset,
  2590. ImportsBlockSize, result));
  2591. // FIXME: better error handling. For now, just skip the replacement for the
  2592. // release version.
  2593. if (Err) {
  2594. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  2595. assert(false);
  2596. }
  2597. }
  2598. namespace {
  2599. const char JavaImportRegexPattern[] =
  2600. "^[\t ]*import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;";
  2601. } // anonymous namespace
  2602. tooling::Replacements sortJavaImports(const FormatStyle &Style, StringRef Code,
  2603. ArrayRef<tooling::Range> Ranges,
  2604. StringRef FileName,
  2605. tooling::Replacements &Replaces) {
  2606. unsigned Prev = 0;
  2607. unsigned SearchFrom = 0;
  2608. llvm::Regex ImportRegex(JavaImportRegexPattern);
  2609. SmallVector<StringRef, 4> Matches;
  2610. SmallVector<JavaImportDirective, 16> ImportsInBlock;
  2611. std::vector<StringRef> AssociatedCommentLines;
  2612. bool FormattingOff = false;
  2613. for (;;) {
  2614. auto Pos = Code.find('\n', SearchFrom);
  2615. StringRef Line =
  2616. Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
  2617. StringRef Trimmed = Line.trim();
  2618. if (Trimmed == "// clang-format off")
  2619. FormattingOff = true;
  2620. else if (Trimmed == "// clang-format on")
  2621. FormattingOff = false;
  2622. if (ImportRegex.match(Line, &Matches)) {
  2623. if (FormattingOff) {
  2624. // If at least one import line has formatting turned off, turn off
  2625. // formatting entirely.
  2626. return Replaces;
  2627. }
  2628. StringRef Static = Matches[1];
  2629. StringRef Identifier = Matches[2];
  2630. bool IsStatic = false;
  2631. if (Static.contains("static")) {
  2632. IsStatic = true;
  2633. }
  2634. ImportsInBlock.push_back(
  2635. {Identifier, Line, Prev, AssociatedCommentLines, IsStatic});
  2636. AssociatedCommentLines.clear();
  2637. } else if (Trimmed.size() > 0 && !ImportsInBlock.empty()) {
  2638. // Associating comments within the imports with the nearest import below
  2639. AssociatedCommentLines.push_back(Line);
  2640. }
  2641. Prev = Pos + 1;
  2642. if (Pos == StringRef::npos || Pos + 1 == Code.size())
  2643. break;
  2644. SearchFrom = Pos + 1;
  2645. }
  2646. if (!ImportsInBlock.empty())
  2647. sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
  2648. return Replaces;
  2649. }
  2650. bool isMpegTS(StringRef Code) {
  2651. // MPEG transport streams use the ".ts" file extension. clang-format should
  2652. // not attempt to format those. MPEG TS' frame format starts with 0x47 every
  2653. // 189 bytes - detect that and return.
  2654. return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
  2655. }
  2656. bool isLikelyXml(StringRef Code) { return Code.ltrim().startswith("<"); }
  2657. tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
  2658. ArrayRef<tooling::Range> Ranges,
  2659. StringRef FileName, unsigned *Cursor) {
  2660. tooling::Replacements Replaces;
  2661. if (!Style.SortIncludes || Style.DisableFormat)
  2662. return Replaces;
  2663. if (isLikelyXml(Code))
  2664. return Replaces;
  2665. if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
  2666. isMpegTS(Code))
  2667. return Replaces;
  2668. if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
  2669. return sortJavaScriptImports(Style, Code, Ranges, FileName);
  2670. if (Style.Language == FormatStyle::LanguageKind::LK_Java)
  2671. return sortJavaImports(Style, Code, Ranges, FileName, Replaces);
  2672. sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
  2673. return Replaces;
  2674. }
  2675. template <typename T>
  2676. static llvm::Expected<tooling::Replacements>
  2677. processReplacements(T ProcessFunc, StringRef Code,
  2678. const tooling::Replacements &Replaces,
  2679. const FormatStyle &Style) {
  2680. if (Replaces.empty())
  2681. return tooling::Replacements();
  2682. auto NewCode = applyAllReplacements(Code, Replaces);
  2683. if (!NewCode)
  2684. return NewCode.takeError();
  2685. std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
  2686. StringRef FileName = Replaces.begin()->getFilePath();
  2687. tooling::Replacements FormatReplaces =
  2688. ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
  2689. return Replaces.merge(FormatReplaces);
  2690. }
  2691. llvm::Expected<tooling::Replacements>
  2692. formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
  2693. const FormatStyle &Style) {
  2694. // We need to use lambda function here since there are two versions of
  2695. // `sortIncludes`.
  2696. auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
  2697. std::vector<tooling::Range> Ranges,
  2698. StringRef FileName) -> tooling::Replacements {
  2699. return sortIncludes(Style, Code, Ranges, FileName);
  2700. };
  2701. auto SortedReplaces =
  2702. processReplacements(SortIncludes, Code, Replaces, Style);
  2703. if (!SortedReplaces)
  2704. return SortedReplaces.takeError();
  2705. // We need to use lambda function here since there are two versions of
  2706. // `reformat`.
  2707. auto Reformat = [](const FormatStyle &Style, StringRef Code,
  2708. std::vector<tooling::Range> Ranges,
  2709. StringRef FileName) -> tooling::Replacements {
  2710. return reformat(Style, Code, Ranges, FileName);
  2711. };
  2712. return processReplacements(Reformat, Code, *SortedReplaces, Style);
  2713. }
  2714. namespace {
  2715. inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
  2716. return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 &&
  2717. llvm::Regex(CppIncludeRegexPattern)
  2718. .match(Replace.getReplacementText());
  2719. }
  2720. inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
  2721. return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1;
  2722. }
  2723. // FIXME: insert empty lines between newly created blocks.
  2724. tooling::Replacements
  2725. fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
  2726. const FormatStyle &Style) {
  2727. if (!Style.isCpp())
  2728. return Replaces;
  2729. tooling::Replacements HeaderInsertions;
  2730. std::set<llvm::StringRef> HeadersToDelete;
  2731. tooling::Replacements Result;
  2732. for (const auto &R : Replaces) {
  2733. if (isHeaderInsertion(R)) {
  2734. // Replacements from \p Replaces must be conflict-free already, so we can
  2735. // simply consume the error.
  2736. llvm::consumeError(HeaderInsertions.add(R));
  2737. } else if (isHeaderDeletion(R)) {
  2738. HeadersToDelete.insert(R.getReplacementText());
  2739. } else if (R.getOffset() == UINT_MAX) {
  2740. llvm::errs() << "Insertions other than header #include insertion are "
  2741. "not supported! "
  2742. << R.getReplacementText() << "\n";
  2743. } else {
  2744. llvm::consumeError(Result.add(R));
  2745. }
  2746. }
  2747. if (HeaderInsertions.empty() && HeadersToDelete.empty())
  2748. return Replaces;
  2749. StringRef FileName = Replaces.begin()->getFilePath();
  2750. tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle);
  2751. for (const auto &Header : HeadersToDelete) {
  2752. tooling::Replacements Replaces =
  2753. Includes.remove(Header.trim("\"<>"), Header.startswith("<"));
  2754. for (const auto &R : Replaces) {
  2755. auto Err = Result.add(R);
  2756. if (Err) {
  2757. // Ignore the deletion on conflict.
  2758. llvm::errs() << "Failed to add header deletion replacement for "
  2759. << Header << ": " << llvm::toString(std::move(Err))
  2760. << "\n";
  2761. }
  2762. }
  2763. }
  2764. llvm::Regex IncludeRegex = llvm::Regex(CppIncludeRegexPattern);
  2765. llvm::SmallVector<StringRef, 4> Matches;
  2766. for (const auto &R : HeaderInsertions) {
  2767. auto IncludeDirective = R.getReplacementText();
  2768. bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
  2769. assert(Matched && "Header insertion replacement must have replacement text "
  2770. "'#include ...'");
  2771. (void)Matched;
  2772. auto IncludeName = Matches[2];
  2773. auto Replace =
  2774. Includes.insert(IncludeName.trim("\"<>"), IncludeName.startswith("<"));
  2775. if (Replace) {
  2776. auto Err = Result.add(*Replace);
  2777. if (Err) {
  2778. llvm::consumeError(std::move(Err));
  2779. unsigned NewOffset =
  2780. Result.getShiftedCodePosition(Replace->getOffset());
  2781. auto Shifted = tooling::Replacement(FileName, NewOffset, 0,
  2782. Replace->getReplacementText());
  2783. Result = Result.merge(tooling::Replacements(Shifted));
  2784. }
  2785. }
  2786. }
  2787. return Result;
  2788. }
  2789. } // anonymous namespace
  2790. llvm::Expected<tooling::Replacements>
  2791. cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
  2792. const FormatStyle &Style) {
  2793. // We need to use lambda function here since there are two versions of
  2794. // `cleanup`.
  2795. auto Cleanup = [](const FormatStyle &Style, StringRef Code,
  2796. std::vector<tooling::Range> Ranges,
  2797. StringRef FileName) -> tooling::Replacements {
  2798. return cleanup(Style, Code, Ranges, FileName);
  2799. };
  2800. // Make header insertion replacements insert new headers into correct blocks.
  2801. tooling::Replacements NewReplaces =
  2802. fixCppIncludeInsertions(Code, Replaces, Style);
  2803. return processReplacements(Cleanup, Code, NewReplaces, Style);
  2804. }
  2805. namespace internal {
  2806. std::pair<tooling::Replacements, unsigned>
  2807. reformat(const FormatStyle &Style, StringRef Code,
  2808. ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
  2809. unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
  2810. FormattingAttemptStatus *Status) {
  2811. FormatStyle Expanded = Style;
  2812. expandPresetsBraceWrapping(Expanded);
  2813. expandPresetsSpaceBeforeParens(Expanded);
  2814. if (Expanded.DisableFormat)
  2815. return {tooling::Replacements(), 0};
  2816. if (isLikelyXml(Code))
  2817. return {tooling::Replacements(), 0};
  2818. if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
  2819. return {tooling::Replacements(), 0};
  2820. // JSON only needs the formatting passing.
  2821. if (Style.isJson()) {
  2822. std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
  2823. auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
  2824. NextStartColumn, LastStartColumn);
  2825. if (!Env)
  2826. return {};
  2827. // Perform the actual formatting pass.
  2828. tooling::Replacements Replaces =
  2829. Formatter(*Env, Style, Status).process().first;
  2830. // add a replacement to remove the "x = " from the result.
  2831. if (!Replaces.add(tooling::Replacement(FileName, 0, 4, ""))) {
  2832. // apply the reformatting changes and the removal of "x = ".
  2833. if (applyAllReplacements(Code, Replaces)) {
  2834. return {Replaces, 0};
  2835. }
  2836. }
  2837. return {tooling::Replacements(), 0};
  2838. }
  2839. typedef std::function<std::pair<tooling::Replacements, unsigned>(
  2840. const Environment &)>
  2841. AnalyzerPass;
  2842. SmallVector<AnalyzerPass, 4> Passes;
  2843. if (Style.isCpp() && Style.QualifierAlignment != FormatStyle::QAS_Leave) {
  2844. Passes.emplace_back([&](const Environment &Env) {
  2845. return QualifierAlignmentFixer(Env, Expanded, Code, Ranges,
  2846. FirstStartColumn, NextStartColumn,
  2847. LastStartColumn, FileName)
  2848. .process();
  2849. });
  2850. }
  2851. if (Style.isCpp() && Style.RemoveBracesLLVM)
  2852. Passes.emplace_back([&](const Environment &Env) {
  2853. return BracesRemover(Env, Expanded).process();
  2854. });
  2855. if (Style.Language == FormatStyle::LK_Cpp) {
  2856. if (Style.FixNamespaceComments)
  2857. Passes.emplace_back([&](const Environment &Env) {
  2858. return NamespaceEndCommentsFixer(Env, Expanded).process();
  2859. });
  2860. if (Style.SortUsingDeclarations)
  2861. Passes.emplace_back([&](const Environment &Env) {
  2862. return UsingDeclarationsSorter(Env, Expanded).process();
  2863. });
  2864. }
  2865. if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave)
  2866. Passes.emplace_back([&](const Environment &Env) {
  2867. return DefinitionBlockSeparator(Env, Expanded).process();
  2868. });
  2869. if (Style.isJavaScript() && Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
  2870. Passes.emplace_back([&](const Environment &Env) {
  2871. return JavaScriptRequoter(Env, Expanded).process();
  2872. });
  2873. Passes.emplace_back([&](const Environment &Env) {
  2874. return Formatter(Env, Expanded, Status).process();
  2875. });
  2876. if (Style.isJavaScript() &&
  2877. Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped)
  2878. Passes.emplace_back([&](const Environment &Env) {
  2879. return TrailingCommaInserter(Env, Expanded).process();
  2880. });
  2881. auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
  2882. NextStartColumn, LastStartColumn);
  2883. if (!Env)
  2884. return {};
  2885. llvm::Optional<std::string> CurrentCode = None;
  2886. tooling::Replacements Fixes;
  2887. unsigned Penalty = 0;
  2888. for (size_t I = 0, E = Passes.size(); I < E; ++I) {
  2889. std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
  2890. auto NewCode = applyAllReplacements(
  2891. CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
  2892. if (NewCode) {
  2893. Fixes = Fixes.merge(PassFixes.first);
  2894. Penalty += PassFixes.second;
  2895. if (I + 1 < E) {
  2896. CurrentCode = std::move(*NewCode);
  2897. Env = Environment::make(
  2898. *CurrentCode, FileName,
  2899. tooling::calculateRangesAfterReplacements(Fixes, Ranges),
  2900. FirstStartColumn, NextStartColumn, LastStartColumn);
  2901. if (!Env)
  2902. return {};
  2903. }
  2904. }
  2905. }
  2906. return {Fixes, Penalty};
  2907. }
  2908. } // namespace internal
  2909. tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
  2910. ArrayRef<tooling::Range> Ranges,
  2911. StringRef FileName,
  2912. FormattingAttemptStatus *Status) {
  2913. return internal::reformat(Style, Code, Ranges,
  2914. /*FirstStartColumn=*/0,
  2915. /*NextStartColumn=*/0,
  2916. /*LastStartColumn=*/0, FileName, Status)
  2917. .first;
  2918. }
  2919. tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
  2920. ArrayRef<tooling::Range> Ranges,
  2921. StringRef FileName) {
  2922. // cleanups only apply to C++ (they mostly concern ctor commas etc.)
  2923. if (Style.Language != FormatStyle::LK_Cpp)
  2924. return tooling::Replacements();
  2925. auto Env = Environment::make(Code, FileName, Ranges);
  2926. if (!Env)
  2927. return {};
  2928. return Cleaner(*Env, Style).process().first;
  2929. }
  2930. tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
  2931. ArrayRef<tooling::Range> Ranges,
  2932. StringRef FileName, bool *IncompleteFormat) {
  2933. FormattingAttemptStatus Status;
  2934. auto Result = reformat(Style, Code, Ranges, FileName, &Status);
  2935. if (!Status.FormatComplete)
  2936. *IncompleteFormat = true;
  2937. return Result;
  2938. }
  2939. tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
  2940. StringRef Code,
  2941. ArrayRef<tooling::Range> Ranges,
  2942. StringRef FileName) {
  2943. auto Env = Environment::make(Code, FileName, Ranges);
  2944. if (!Env)
  2945. return {};
  2946. return NamespaceEndCommentsFixer(*Env, Style).process().first;
  2947. }
  2948. tooling::Replacements separateDefinitionBlocks(const FormatStyle &Style,
  2949. StringRef Code,
  2950. ArrayRef<tooling::Range> Ranges,
  2951. StringRef FileName) {
  2952. auto Env = Environment::make(Code, FileName, Ranges);
  2953. if (!Env)
  2954. return {};
  2955. return DefinitionBlockSeparator(*Env, Style).process().first;
  2956. }
  2957. tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
  2958. StringRef Code,
  2959. ArrayRef<tooling::Range> Ranges,
  2960. StringRef FileName) {
  2961. auto Env = Environment::make(Code, FileName, Ranges);
  2962. if (!Env)
  2963. return {};
  2964. return UsingDeclarationsSorter(*Env, Style).process().first;
  2965. }
  2966. LangOptions getFormattingLangOpts(const FormatStyle &Style) {
  2967. LangOptions LangOpts;
  2968. FormatStyle::LanguageStandard LexingStd = Style.Standard;
  2969. if (LexingStd == FormatStyle::LS_Auto)
  2970. LexingStd = FormatStyle::LS_Latest;
  2971. if (LexingStd == FormatStyle::LS_Latest)
  2972. LexingStd = FormatStyle::LS_Cpp20;
  2973. LangOpts.CPlusPlus = 1;
  2974. LangOpts.CPlusPlus11 = LexingStd >= FormatStyle::LS_Cpp11;
  2975. LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
  2976. LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
  2977. LangOpts.CPlusPlus20 = LexingStd >= FormatStyle::LS_Cpp20;
  2978. LangOpts.Char8 = LexingStd >= FormatStyle::LS_Cpp20;
  2979. LangOpts.LineComment = 1;
  2980. bool AlternativeOperators = Style.isCpp();
  2981. LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
  2982. LangOpts.Bool = 1;
  2983. LangOpts.ObjC = 1;
  2984. LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
  2985. LangOpts.DeclSpecKeyword = 1; // To get __declspec.
  2986. LangOpts.C99 = 1; // To get kw_restrict for non-underscore-prefixed restrict.
  2987. return LangOpts;
  2988. }
  2989. const char *StyleOptionHelpDescription =
  2990. "Coding style, currently supports:\n"
  2991. " LLVM, GNU, Google, Chromium, Microsoft, Mozilla, WebKit.\n"
  2992. "Use -style=file to load style configuration from\n"
  2993. ".clang-format file located in one of the parent\n"
  2994. "directories of the source file (or current\n"
  2995. "directory for stdin).\n"
  2996. "Use -style=file:<format_file_path> to explicitly specify"
  2997. "the configuration file.\n"
  2998. "Use -style=\"{key: value, ...}\" to set specific\n"
  2999. "parameters, e.g.:\n"
  3000. " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
  3001. static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
  3002. if (FileName.endswith(".java"))
  3003. return FormatStyle::LK_Java;
  3004. if (FileName.endswith_insensitive(".js") ||
  3005. FileName.endswith_insensitive(".mjs") ||
  3006. FileName.endswith_insensitive(".ts"))
  3007. return FormatStyle::LK_JavaScript; // (module) JavaScript or TypeScript.
  3008. if (FileName.endswith(".m") || FileName.endswith(".mm"))
  3009. return FormatStyle::LK_ObjC;
  3010. if (FileName.endswith_insensitive(".proto") ||
  3011. FileName.endswith_insensitive(".protodevel"))
  3012. return FormatStyle::LK_Proto;
  3013. if (FileName.endswith_insensitive(".textpb") ||
  3014. FileName.endswith_insensitive(".pb.txt") ||
  3015. FileName.endswith_insensitive(".textproto") ||
  3016. FileName.endswith_insensitive(".asciipb"))
  3017. return FormatStyle::LK_TextProto;
  3018. if (FileName.endswith_insensitive(".td"))
  3019. return FormatStyle::LK_TableGen;
  3020. if (FileName.endswith_insensitive(".cs"))
  3021. return FormatStyle::LK_CSharp;
  3022. if (FileName.endswith_insensitive(".json"))
  3023. return FormatStyle::LK_Json;
  3024. return FormatStyle::LK_Cpp;
  3025. }
  3026. FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
  3027. const auto GuessedLanguage = getLanguageByFileName(FileName);
  3028. if (GuessedLanguage == FormatStyle::LK_Cpp) {
  3029. auto Extension = llvm::sys::path::extension(FileName);
  3030. // If there's no file extension (or it's .h), we need to check the contents
  3031. // of the code to see if it contains Objective-C.
  3032. if (Extension.empty() || Extension == ".h") {
  3033. auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
  3034. Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
  3035. ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
  3036. Guesser.process();
  3037. if (Guesser.isObjC())
  3038. return FormatStyle::LK_ObjC;
  3039. }
  3040. }
  3041. return GuessedLanguage;
  3042. }
  3043. const char *DefaultFormatStyle = "file";
  3044. const char *DefaultFallbackStyle = "LLVM";
  3045. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  3046. loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
  3047. FormatStyle *Style, bool AllowUnknownOptions) {
  3048. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
  3049. FS->getBufferForFile(ConfigFile.str());
  3050. if (auto EC = Text.getError())
  3051. return EC;
  3052. if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions))
  3053. return EC;
  3054. return Text;
  3055. }
  3056. llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
  3057. StringRef FallbackStyleName,
  3058. StringRef Code, llvm::vfs::FileSystem *FS,
  3059. bool AllowUnknownOptions) {
  3060. if (!FS) {
  3061. FS = llvm::vfs::getRealFileSystem().get();
  3062. }
  3063. FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
  3064. FormatStyle FallbackStyle = getNoStyle();
  3065. if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
  3066. return make_string_error("Invalid fallback style \"" + FallbackStyleName);
  3067. llvm::SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 1>
  3068. ChildFormatTextToApply;
  3069. if (StyleName.startswith("{")) {
  3070. // Parse YAML/JSON style from the command line.
  3071. StringRef Source = "<command-line>";
  3072. if (std::error_code ec =
  3073. parseConfiguration(llvm::MemoryBufferRef(StyleName, Source), &Style,
  3074. AllowUnknownOptions))
  3075. return make_string_error("Error parsing -style: " + ec.message());
  3076. if (Style.InheritsParentConfig)
  3077. ChildFormatTextToApply.emplace_back(
  3078. llvm::MemoryBuffer::getMemBuffer(StyleName, Source, false));
  3079. else
  3080. return Style;
  3081. }
  3082. // User provided clang-format file using -style=file:path/to/format/file.
  3083. if (!Style.InheritsParentConfig &&
  3084. StyleName.startswith_insensitive("file:")) {
  3085. auto ConfigFile = StyleName.substr(5);
  3086. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
  3087. loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions);
  3088. if (auto EC = Text.getError())
  3089. return make_string_error("Error reading " + ConfigFile + ": " +
  3090. EC.message());
  3091. LLVM_DEBUG(llvm::dbgs()
  3092. << "Using configuration file " << ConfigFile << "\n");
  3093. if (!Style.InheritsParentConfig)
  3094. return Style;
  3095. // Search for parent configs starting from the parent directory of
  3096. // ConfigFile.
  3097. FileName = ConfigFile;
  3098. ChildFormatTextToApply.emplace_back(std::move(*Text));
  3099. }
  3100. // If the style inherits the parent configuration it is a command line
  3101. // configuration, which wants to inherit, so we have to skip the check of the
  3102. // StyleName.
  3103. if (!Style.InheritsParentConfig && !StyleName.equals_insensitive("file")) {
  3104. if (!getPredefinedStyle(StyleName, Style.Language, &Style))
  3105. return make_string_error("Invalid value for -style");
  3106. if (!Style.InheritsParentConfig)
  3107. return Style;
  3108. }
  3109. // Reset possible inheritance
  3110. Style.InheritsParentConfig = false;
  3111. // Look for .clang-format/_clang-format file in the file's parent directories.
  3112. SmallString<128> UnsuitableConfigFiles;
  3113. SmallString<128> Path(FileName);
  3114. if (std::error_code EC = FS->makeAbsolute(Path))
  3115. return make_string_error(EC.message());
  3116. llvm::SmallVector<std::string, 2> FilesToLookFor;
  3117. FilesToLookFor.push_back(".clang-format");
  3118. FilesToLookFor.push_back("_clang-format");
  3119. auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
  3120. auto applyChildFormatTexts = [&](FormatStyle *Style) {
  3121. for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
  3122. auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
  3123. dropDiagnosticHandler);
  3124. // It was already correctly parsed.
  3125. assert(!EC);
  3126. static_cast<void>(EC);
  3127. }
  3128. };
  3129. for (StringRef Directory = Path; !Directory.empty();
  3130. Directory = llvm::sys::path::parent_path(Directory)) {
  3131. auto Status = FS->status(Directory);
  3132. if (!Status ||
  3133. Status->getType() != llvm::sys::fs::file_type::directory_file) {
  3134. continue;
  3135. }
  3136. for (const auto &F : FilesToLookFor) {
  3137. SmallString<128> ConfigFile(Directory);
  3138. llvm::sys::path::append(ConfigFile, F);
  3139. LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  3140. Status = FS->status(ConfigFile.str());
  3141. if (Status &&
  3142. (Status->getType() == llvm::sys::fs::file_type::regular_file)) {
  3143. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
  3144. loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions);
  3145. if (auto EC = Text.getError()) {
  3146. if (EC == ParseError::Unsuitable) {
  3147. if (!UnsuitableConfigFiles.empty())
  3148. UnsuitableConfigFiles.append(", ");
  3149. UnsuitableConfigFiles.append(ConfigFile);
  3150. continue;
  3151. }
  3152. return make_string_error("Error reading " + ConfigFile + ": " +
  3153. EC.message());
  3154. }
  3155. LLVM_DEBUG(llvm::dbgs()
  3156. << "Using configuration file " << ConfigFile << "\n");
  3157. if (!Style.InheritsParentConfig) {
  3158. if (ChildFormatTextToApply.empty())
  3159. return Style;
  3160. LLVM_DEBUG(llvm::dbgs() << "Applying child configurations\n");
  3161. applyChildFormatTexts(&Style);
  3162. return Style;
  3163. }
  3164. LLVM_DEBUG(llvm::dbgs() << "Inherits parent configuration\n");
  3165. // Reset inheritance of style
  3166. Style.InheritsParentConfig = false;
  3167. ChildFormatTextToApply.emplace_back(std::move(*Text));
  3168. // Breaking out of the inner loop, since we don't want to parse
  3169. // .clang-format AND _clang-format, if both exist. Then we continue the
  3170. // inner loop (parent directories) in search for the parent
  3171. // configuration.
  3172. break;
  3173. }
  3174. }
  3175. }
  3176. if (!UnsuitableConfigFiles.empty())
  3177. return make_string_error("Configuration file(s) do(es) not support " +
  3178. getLanguageName(Style.Language) + ": " +
  3179. UnsuitableConfigFiles);
  3180. if (!ChildFormatTextToApply.empty()) {
  3181. LLVM_DEBUG(llvm::dbgs()
  3182. << "Applying child configurations on fallback style\n");
  3183. applyChildFormatTexts(&FallbackStyle);
  3184. }
  3185. return FallbackStyle;
  3186. }
  3187. } // namespace format
  3188. } // namespace clang