Format.cpp 156 KB

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