Format.cpp 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657
  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 "ContinuationIndenter.h"
  17. #include "FormatInternal.h"
  18. #include "FormatTokenLexer.h"
  19. #include "NamespaceEndCommentsFixer.h"
  20. #include "SortJavaScriptImports.h"
  21. #include "TokenAnalyzer.h"
  22. #include "TokenAnnotator.h"
  23. #include "UnwrappedLineFormatter.h"
  24. #include "UnwrappedLineParser.h"
  25. #include "UsingDeclarationsSorter.h"
  26. #include "WhitespaceManager.h"
  27. #include "clang/Basic/Diagnostic.h"
  28. #include "clang/Basic/DiagnosticOptions.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Lex/Lexer.h"
  31. #include "clang/Tooling/Inclusions/HeaderIncludes.h"
  32. #include "llvm/ADT/STLExtras.h"
  33. #include "llvm/ADT/StringRef.h"
  34. #include "llvm/Support/Allocator.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/Path.h"
  37. #include "llvm/Support/Regex.h"
  38. #include "llvm/Support/VirtualFileSystem.h"
  39. #include "llvm/Support/YAMLTraits.h"
  40. #include <algorithm>
  41. #include <memory>
  42. #include <mutex>
  43. #include <string>
  44. #include <unordered_map>
  45. #define DEBUG_TYPE "format-formatter"
  46. using clang::format::FormatStyle;
  47. LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::RawStringFormat)
  48. namespace llvm {
  49. namespace yaml {
  50. template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
  51. static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
  52. IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
  53. IO.enumCase(Value, "Java", FormatStyle::LK_Java);
  54. IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
  55. IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
  56. IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
  57. IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
  58. IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
  59. IO.enumCase(Value, "CSharp", FormatStyle::LK_CSharp);
  60. }
  61. };
  62. template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
  63. static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
  64. IO.enumCase(Value, "c++03", FormatStyle::LS_Cpp03);
  65. IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03); // Legacy alias
  66. IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03); // Legacy alias
  67. IO.enumCase(Value, "c++11", FormatStyle::LS_Cpp11);
  68. IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11); // Legacy alias
  69. IO.enumCase(Value, "c++14", FormatStyle::LS_Cpp14);
  70. IO.enumCase(Value, "c++17", FormatStyle::LS_Cpp17);
  71. IO.enumCase(Value, "c++20", FormatStyle::LS_Cpp20);
  72. IO.enumCase(Value, "Latest", FormatStyle::LS_Latest);
  73. IO.enumCase(Value, "Cpp11", FormatStyle::LS_Latest); // Legacy alias
  74. IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
  75. }
  76. };
  77. template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
  78. static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
  79. IO.enumCase(Value, "Never", FormatStyle::UT_Never);
  80. IO.enumCase(Value, "false", FormatStyle::UT_Never);
  81. IO.enumCase(Value, "Always", FormatStyle::UT_Always);
  82. IO.enumCase(Value, "true", FormatStyle::UT_Always);
  83. IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
  84. IO.enumCase(Value, "ForContinuationAndIndentation",
  85. FormatStyle::UT_ForContinuationAndIndentation);
  86. }
  87. };
  88. template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
  89. static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
  90. IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
  91. IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
  92. IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
  93. }
  94. };
  95. template <> struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {
  96. static void enumeration(IO &IO, FormatStyle::ShortBlockStyle &Value) {
  97. IO.enumCase(Value, "Never", FormatStyle::SBS_Never);
  98. IO.enumCase(Value, "false", FormatStyle::SBS_Never);
  99. IO.enumCase(Value, "Always", FormatStyle::SBS_Always);
  100. IO.enumCase(Value, "true", FormatStyle::SBS_Always);
  101. IO.enumCase(Value, "Empty", FormatStyle::SBS_Empty);
  102. }
  103. };
  104. template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
  105. static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
  106. IO.enumCase(Value, "None", FormatStyle::SFS_None);
  107. IO.enumCase(Value, "false", FormatStyle::SFS_None);
  108. IO.enumCase(Value, "All", FormatStyle::SFS_All);
  109. IO.enumCase(Value, "true", FormatStyle::SFS_All);
  110. IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
  111. IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly);
  112. IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
  113. }
  114. };
  115. template <> struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
  116. static void enumeration(IO &IO, FormatStyle::ShortIfStyle &Value) {
  117. IO.enumCase(Value, "Never", FormatStyle::SIS_Never);
  118. IO.enumCase(Value, "Always", FormatStyle::SIS_Always);
  119. IO.enumCase(Value, "WithoutElse", FormatStyle::SIS_WithoutElse);
  120. // For backward compatibility.
  121. IO.enumCase(Value, "false", FormatStyle::SIS_Never);
  122. IO.enumCase(Value, "true", FormatStyle::SIS_WithoutElse);
  123. }
  124. };
  125. template <> struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
  126. static void enumeration(IO &IO, FormatStyle::ShortLambdaStyle &Value) {
  127. IO.enumCase(Value, "None", FormatStyle::SLS_None);
  128. IO.enumCase(Value, "false", FormatStyle::SLS_None);
  129. IO.enumCase(Value, "Empty", FormatStyle::SLS_Empty);
  130. IO.enumCase(Value, "Inline", FormatStyle::SLS_Inline);
  131. IO.enumCase(Value, "All", FormatStyle::SLS_All);
  132. IO.enumCase(Value, "true", FormatStyle::SLS_All);
  133. }
  134. };
  135. template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
  136. static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value) {
  137. IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
  138. IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
  139. IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
  140. }
  141. };
  142. template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
  143. static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
  144. IO.enumCase(Value, "All", FormatStyle::BOS_All);
  145. IO.enumCase(Value, "true", FormatStyle::BOS_All);
  146. IO.enumCase(Value, "None", FormatStyle::BOS_None);
  147. IO.enumCase(Value, "false", FormatStyle::BOS_None);
  148. IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
  149. }
  150. };
  151. template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
  152. static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
  153. IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
  154. IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
  155. IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
  156. IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
  157. IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
  158. IO.enumCase(Value, "Whitesmiths", FormatStyle::BS_Whitesmiths);
  159. IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
  160. IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
  161. IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
  162. }
  163. };
  164. template <>
  165. struct ScalarEnumerationTraits<
  166. FormatStyle::BraceWrappingAfterControlStatementStyle> {
  167. static void
  168. enumeration(IO &IO,
  169. FormatStyle::BraceWrappingAfterControlStatementStyle &Value) {
  170. IO.enumCase(Value, "false", FormatStyle::BWACS_Never);
  171. IO.enumCase(Value, "true", FormatStyle::BWACS_Always);
  172. IO.enumCase(Value, "Never", FormatStyle::BWACS_Never);
  173. IO.enumCase(Value, "MultiLine", FormatStyle::BWACS_MultiLine);
  174. IO.enumCase(Value, "Always", FormatStyle::BWACS_Always);
  175. }
  176. };
  177. template <>
  178. struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
  179. static void
  180. enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) {
  181. IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
  182. IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
  183. IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
  184. }
  185. };
  186. template <>
  187. struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
  188. static void enumeration(IO &IO,
  189. FormatStyle::BreakInheritanceListStyle &Value) {
  190. IO.enumCase(Value, "BeforeColon", FormatStyle::BILS_BeforeColon);
  191. IO.enumCase(Value, "BeforeComma", FormatStyle::BILS_BeforeComma);
  192. IO.enumCase(Value, "AfterColon", FormatStyle::BILS_AfterColon);
  193. }
  194. };
  195. template <>
  196. struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
  197. static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) {
  198. IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
  199. IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
  200. IO.enumCase(Value, "BeforeHash", FormatStyle::PPDIS_BeforeHash);
  201. }
  202. };
  203. template <>
  204. struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
  205. static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
  206. IO.enumCase(Value, "None", FormatStyle::RTBS_None);
  207. IO.enumCase(Value, "All", FormatStyle::RTBS_All);
  208. IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
  209. IO.enumCase(Value, "TopLevelDefinitions",
  210. FormatStyle::RTBS_TopLevelDefinitions);
  211. IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
  212. }
  213. };
  214. template <>
  215. struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
  216. static void enumeration(IO &IO,
  217. FormatStyle::BreakTemplateDeclarationsStyle &Value) {
  218. IO.enumCase(Value, "No", FormatStyle::BTDS_No);
  219. IO.enumCase(Value, "MultiLine", FormatStyle::BTDS_MultiLine);
  220. IO.enumCase(Value, "Yes", FormatStyle::BTDS_Yes);
  221. // For backward compatibility.
  222. IO.enumCase(Value, "false", FormatStyle::BTDS_MultiLine);
  223. IO.enumCase(Value, "true", FormatStyle::BTDS_Yes);
  224. }
  225. };
  226. template <>
  227. struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
  228. static void
  229. enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
  230. IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
  231. IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
  232. IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
  233. // For backward compatibility.
  234. IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
  235. IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
  236. }
  237. };
  238. template <>
  239. struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
  240. static void enumeration(IO &IO,
  241. FormatStyle::NamespaceIndentationKind &Value) {
  242. IO.enumCase(Value, "None", FormatStyle::NI_None);
  243. IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
  244. IO.enumCase(Value, "All", FormatStyle::NI_All);
  245. }
  246. };
  247. template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
  248. static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
  249. IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
  250. IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
  251. IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
  252. // For backward compatibility.
  253. IO.enumCase(Value, "true", FormatStyle::BAS_Align);
  254. IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
  255. }
  256. };
  257. template <>
  258. struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
  259. static void enumeration(IO &IO,
  260. FormatStyle::EscapedNewlineAlignmentStyle &Value) {
  261. IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
  262. IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
  263. IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
  264. // For backward compatibility.
  265. IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
  266. IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
  267. }
  268. };
  269. template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
  270. static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
  271. IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
  272. IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
  273. IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
  274. // For backward compatibility.
  275. IO.enumCase(Value, "true", FormatStyle::PAS_Left);
  276. IO.enumCase(Value, "false", FormatStyle::PAS_Right);
  277. }
  278. };
  279. template <>
  280. struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
  281. static void enumeration(IO &IO,
  282. FormatStyle::SpaceBeforeParensOptions &Value) {
  283. IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
  284. IO.enumCase(Value, "ControlStatements",
  285. FormatStyle::SBPO_ControlStatements);
  286. IO.enumCase(Value, "NonEmptyParentheses",
  287. FormatStyle::SBPO_NonEmptyParentheses);
  288. IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
  289. // For backward compatibility.
  290. IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
  291. IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
  292. }
  293. };
  294. template <> struct MappingTraits<FormatStyle> {
  295. static void mapping(IO &IO, FormatStyle &Style) {
  296. // When reading, read the language first, we need it for getPredefinedStyle.
  297. IO.mapOptional("Language", Style.Language);
  298. if (IO.outputting()) {
  299. StringRef StylesArray[] = {"LLVM", "Google", "Chromium", "Mozilla",
  300. "WebKit", "GNU", "Microsoft"};
  301. ArrayRef<StringRef> Styles(StylesArray);
  302. for (size_t i = 0, e = Styles.size(); i < e; ++i) {
  303. StringRef StyleName(Styles[i]);
  304. FormatStyle PredefinedStyle;
  305. if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
  306. Style == PredefinedStyle) {
  307. IO.mapOptional("# BasedOnStyle", StyleName);
  308. break;
  309. }
  310. }
  311. } else {
  312. StringRef BasedOnStyle;
  313. IO.mapOptional("BasedOnStyle", BasedOnStyle);
  314. if (!BasedOnStyle.empty()) {
  315. FormatStyle::LanguageKind OldLanguage = Style.Language;
  316. FormatStyle::LanguageKind Language =
  317. ((FormatStyle *)IO.getContext())->Language;
  318. if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
  319. IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
  320. return;
  321. }
  322. Style.Language = OldLanguage;
  323. }
  324. }
  325. // For backward compatibility.
  326. if (!IO.outputting()) {
  327. IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
  328. IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
  329. IO.mapOptional("IndentFunctionDeclarationAfterType",
  330. Style.IndentWrappedFunctionNames);
  331. IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
  332. IO.mapOptional("SpaceAfterControlStatementKeyword",
  333. Style.SpaceBeforeParens);
  334. }
  335. IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
  336. IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
  337. IO.mapOptional("AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
  338. IO.mapOptional("AlignConsecutiveAssignments",
  339. Style.AlignConsecutiveAssignments);
  340. IO.mapOptional("AlignConsecutiveDeclarations",
  341. Style.AlignConsecutiveDeclarations);
  342. IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
  343. IO.mapOptional("AlignOperands", Style.AlignOperands);
  344. IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
  345. IO.mapOptional("AllowAllArgumentsOnNextLine",
  346. Style.AllowAllArgumentsOnNextLine);
  347. IO.mapOptional("AllowAllConstructorInitializersOnNextLine",
  348. Style.AllowAllConstructorInitializersOnNextLine);
  349. IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
  350. Style.AllowAllParametersOfDeclarationOnNextLine);
  351. IO.mapOptional("AllowShortBlocksOnASingleLine",
  352. Style.AllowShortBlocksOnASingleLine);
  353. IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
  354. Style.AllowShortCaseLabelsOnASingleLine);
  355. IO.mapOptional("AllowShortFunctionsOnASingleLine",
  356. Style.AllowShortFunctionsOnASingleLine);
  357. IO.mapOptional("AllowShortLambdasOnASingleLine",
  358. Style.AllowShortLambdasOnASingleLine);
  359. IO.mapOptional("AllowShortIfStatementsOnASingleLine",
  360. Style.AllowShortIfStatementsOnASingleLine);
  361. IO.mapOptional("AllowShortLoopsOnASingleLine",
  362. Style.AllowShortLoopsOnASingleLine);
  363. IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
  364. Style.AlwaysBreakAfterDefinitionReturnType);
  365. IO.mapOptional("AlwaysBreakAfterReturnType",
  366. Style.AlwaysBreakAfterReturnType);
  367. // If AlwaysBreakAfterDefinitionReturnType was specified but
  368. // AlwaysBreakAfterReturnType was not, initialize the latter from the
  369. // former for backwards compatibility.
  370. if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
  371. Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
  372. if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
  373. Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
  374. else if (Style.AlwaysBreakAfterDefinitionReturnType ==
  375. FormatStyle::DRTBS_TopLevel)
  376. Style.AlwaysBreakAfterReturnType =
  377. FormatStyle::RTBS_TopLevelDefinitions;
  378. }
  379. IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
  380. Style.AlwaysBreakBeforeMultilineStrings);
  381. IO.mapOptional("AlwaysBreakTemplateDeclarations",
  382. Style.AlwaysBreakTemplateDeclarations);
  383. IO.mapOptional("BinPackArguments", Style.BinPackArguments);
  384. IO.mapOptional("BinPackParameters", Style.BinPackParameters);
  385. IO.mapOptional("BraceWrapping", Style.BraceWrapping);
  386. IO.mapOptional("BreakBeforeBinaryOperators",
  387. Style.BreakBeforeBinaryOperators);
  388. IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
  389. bool BreakBeforeInheritanceComma = false;
  390. IO.mapOptional("BreakBeforeInheritanceComma", BreakBeforeInheritanceComma);
  391. IO.mapOptional("BreakInheritanceList", Style.BreakInheritanceList);
  392. // If BreakBeforeInheritanceComma was specified but
  393. // BreakInheritance was not, initialize the latter from the
  394. // former for backwards compatibility.
  395. if (BreakBeforeInheritanceComma &&
  396. Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon)
  397. Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
  398. IO.mapOptional("BreakBeforeTernaryOperators",
  399. Style.BreakBeforeTernaryOperators);
  400. bool BreakConstructorInitializersBeforeComma = false;
  401. IO.mapOptional("BreakConstructorInitializersBeforeComma",
  402. BreakConstructorInitializersBeforeComma);
  403. IO.mapOptional("BreakConstructorInitializers",
  404. Style.BreakConstructorInitializers);
  405. // If BreakConstructorInitializersBeforeComma was specified but
  406. // BreakConstructorInitializers was not, initialize the latter from the
  407. // former for backwards compatibility.
  408. if (BreakConstructorInitializersBeforeComma &&
  409. Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon)
  410. Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
  411. IO.mapOptional("BreakAfterJavaFieldAnnotations",
  412. Style.BreakAfterJavaFieldAnnotations);
  413. IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
  414. IO.mapOptional("ColumnLimit", Style.ColumnLimit);
  415. IO.mapOptional("CommentPragmas", Style.CommentPragmas);
  416. IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
  417. IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
  418. Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
  419. IO.mapOptional("ConstructorInitializerIndentWidth",
  420. Style.ConstructorInitializerIndentWidth);
  421. IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
  422. IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
  423. IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
  424. IO.mapOptional("DisableFormat", Style.DisableFormat);
  425. IO.mapOptional("ExperimentalAutoDetectBinPacking",
  426. Style.ExperimentalAutoDetectBinPacking);
  427. IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
  428. IO.mapOptional("ForEachMacros", Style.ForEachMacros);
  429. IO.mapOptional("IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
  430. IO.mapOptional("IncludeCategories", Style.IncludeStyle.IncludeCategories);
  431. IO.mapOptional("IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
  432. IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
  433. IO.mapOptional("IndentGotoLabels", Style.IndentGotoLabels);
  434. IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
  435. IO.mapOptional("IndentWidth", Style.IndentWidth);
  436. IO.mapOptional("IndentWrappedFunctionNames",
  437. Style.IndentWrappedFunctionNames);
  438. IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
  439. IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
  440. IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
  441. IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
  442. Style.KeepEmptyLinesAtTheStartOfBlocks);
  443. IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
  444. IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
  445. IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
  446. IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
  447. IO.mapOptional("NamespaceMacros", Style.NamespaceMacros);
  448. IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
  449. IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
  450. IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
  451. IO.mapOptional("ObjCSpaceBeforeProtocolList",
  452. Style.ObjCSpaceBeforeProtocolList);
  453. IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
  454. IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
  455. Style.PenaltyBreakBeforeFirstCallParameter);
  456. IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
  457. IO.mapOptional("PenaltyBreakFirstLessLess",
  458. Style.PenaltyBreakFirstLessLess);
  459. IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
  460. IO.mapOptional("PenaltyBreakTemplateDeclaration",
  461. Style.PenaltyBreakTemplateDeclaration);
  462. IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
  463. IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
  464. Style.PenaltyReturnTypeOnItsOwnLine);
  465. IO.mapOptional("PointerAlignment", Style.PointerAlignment);
  466. IO.mapOptional("RawStringFormats", Style.RawStringFormats);
  467. IO.mapOptional("ReflowComments", Style.ReflowComments);
  468. IO.mapOptional("SortIncludes", Style.SortIncludes);
  469. IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
  470. IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
  471. IO.mapOptional("SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
  472. IO.mapOptional("SpaceAfterTemplateKeyword",
  473. Style.SpaceAfterTemplateKeyword);
  474. IO.mapOptional("SpaceBeforeAssignmentOperators",
  475. Style.SpaceBeforeAssignmentOperators);
  476. IO.mapOptional("SpaceBeforeCpp11BracedList",
  477. Style.SpaceBeforeCpp11BracedList);
  478. IO.mapOptional("SpaceBeforeCtorInitializerColon",
  479. Style.SpaceBeforeCtorInitializerColon);
  480. IO.mapOptional("SpaceBeforeInheritanceColon",
  481. Style.SpaceBeforeInheritanceColon);
  482. IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
  483. IO.mapOptional("SpaceBeforeRangeBasedForLoopColon",
  484. Style.SpaceBeforeRangeBasedForLoopColon);
  485. IO.mapOptional("SpaceInEmptyBlock", Style.SpaceInEmptyBlock);
  486. IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
  487. IO.mapOptional("SpacesBeforeTrailingComments",
  488. Style.SpacesBeforeTrailingComments);
  489. IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
  490. IO.mapOptional("SpacesInContainerLiterals",
  491. Style.SpacesInContainerLiterals);
  492. IO.mapOptional("SpacesInCStyleCastParentheses",
  493. Style.SpacesInCStyleCastParentheses);
  494. IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
  495. IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
  496. IO.mapOptional("Standard", Style.Standard);
  497. IO.mapOptional("StatementMacros", Style.StatementMacros);
  498. IO.mapOptional("TabWidth", Style.TabWidth);
  499. IO.mapOptional("TypenameMacros", Style.TypenameMacros);
  500. IO.mapOptional("UseTab", Style.UseTab);
  501. }
  502. };
  503. template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
  504. static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
  505. IO.mapOptional("AfterCaseLabel", Wrapping.AfterCaseLabel);
  506. IO.mapOptional("AfterClass", Wrapping.AfterClass);
  507. IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
  508. IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
  509. IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
  510. IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
  511. IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
  512. IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
  513. IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
  514. IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
  515. IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
  516. IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
  517. IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
  518. IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
  519. IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
  520. IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
  521. }
  522. };
  523. template <> struct MappingTraits<FormatStyle::RawStringFormat> {
  524. static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
  525. IO.mapOptional("Language", Format.Language);
  526. IO.mapOptional("Delimiters", Format.Delimiters);
  527. IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
  528. IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
  529. IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
  530. }
  531. };
  532. // Allows to read vector<FormatStyle> while keeping default values.
  533. // IO.getContext() should contain a pointer to the FormatStyle structure, that
  534. // will be used to get default values for missing keys.
  535. // If the first element has no Language specified, it will be treated as the
  536. // default one for the following elements.
  537. template <> struct DocumentListTraits<std::vector<FormatStyle>> {
  538. static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
  539. return Seq.size();
  540. }
  541. static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
  542. size_t Index) {
  543. if (Index >= Seq.size()) {
  544. assert(Index == Seq.size());
  545. FormatStyle Template;
  546. if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
  547. Template = Seq[0];
  548. } else {
  549. Template = *((const FormatStyle *)IO.getContext());
  550. Template.Language = FormatStyle::LK_None;
  551. }
  552. Seq.resize(Index + 1, Template);
  553. }
  554. return Seq[Index];
  555. }
  556. };
  557. } // namespace yaml
  558. } // namespace llvm
  559. namespace clang {
  560. namespace format {
  561. const std::error_category &getParseCategory() {
  562. static const ParseErrorCategory C{};
  563. return C;
  564. }
  565. std::error_code make_error_code(ParseError e) {
  566. return std::error_code(static_cast<int>(e), getParseCategory());
  567. }
  568. inline llvm::Error make_string_error(const llvm::Twine &Message) {
  569. return llvm::make_error<llvm::StringError>(Message,
  570. llvm::inconvertibleErrorCode());
  571. }
  572. const char *ParseErrorCategory::name() const noexcept {
  573. return "clang-format.parse_error";
  574. }
  575. std::string ParseErrorCategory::message(int EV) const {
  576. switch (static_cast<ParseError>(EV)) {
  577. case ParseError::Success:
  578. return "Success";
  579. case ParseError::Error:
  580. return "Invalid argument";
  581. case ParseError::Unsuitable:
  582. return "Unsuitable";
  583. }
  584. llvm_unreachable("unexpected parse error");
  585. }
  586. static FormatStyle expandPresets(const FormatStyle &Style) {
  587. if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
  588. return Style;
  589. FormatStyle Expanded = Style;
  590. Expanded.BraceWrapping = {false, false, FormatStyle::BWACS_Never,
  591. false, false, false,
  592. false, false, false,
  593. false, false, false,
  594. false, true, true,
  595. true};
  596. switch (Style.BreakBeforeBraces) {
  597. case FormatStyle::BS_Linux:
  598. Expanded.BraceWrapping.AfterClass = true;
  599. Expanded.BraceWrapping.AfterFunction = true;
  600. Expanded.BraceWrapping.AfterNamespace = true;
  601. break;
  602. case FormatStyle::BS_Mozilla:
  603. Expanded.BraceWrapping.AfterClass = true;
  604. Expanded.BraceWrapping.AfterEnum = true;
  605. Expanded.BraceWrapping.AfterFunction = true;
  606. Expanded.BraceWrapping.AfterStruct = true;
  607. Expanded.BraceWrapping.AfterUnion = true;
  608. Expanded.BraceWrapping.AfterExternBlock = true;
  609. Expanded.BraceWrapping.SplitEmptyFunction = true;
  610. Expanded.BraceWrapping.SplitEmptyRecord = false;
  611. break;
  612. case FormatStyle::BS_Stroustrup:
  613. Expanded.BraceWrapping.AfterFunction = true;
  614. Expanded.BraceWrapping.BeforeCatch = true;
  615. Expanded.BraceWrapping.BeforeElse = true;
  616. break;
  617. case FormatStyle::BS_Allman:
  618. Expanded.BraceWrapping.AfterCaseLabel = true;
  619. Expanded.BraceWrapping.AfterClass = true;
  620. Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
  621. Expanded.BraceWrapping.AfterEnum = true;
  622. Expanded.BraceWrapping.AfterFunction = true;
  623. Expanded.BraceWrapping.AfterNamespace = true;
  624. Expanded.BraceWrapping.AfterObjCDeclaration = true;
  625. Expanded.BraceWrapping.AfterStruct = true;
  626. Expanded.BraceWrapping.AfterUnion = true;
  627. Expanded.BraceWrapping.AfterExternBlock = true;
  628. Expanded.BraceWrapping.BeforeCatch = true;
  629. Expanded.BraceWrapping.BeforeElse = true;
  630. break;
  631. case FormatStyle::BS_Whitesmiths:
  632. Expanded.BraceWrapping.AfterCaseLabel = true;
  633. Expanded.BraceWrapping.AfterClass = true;
  634. Expanded.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
  635. Expanded.BraceWrapping.AfterEnum = true;
  636. Expanded.BraceWrapping.AfterFunction = true;
  637. Expanded.BraceWrapping.AfterNamespace = true;
  638. Expanded.BraceWrapping.AfterObjCDeclaration = true;
  639. Expanded.BraceWrapping.AfterStruct = true;
  640. Expanded.BraceWrapping.AfterExternBlock = true;
  641. Expanded.BraceWrapping.BeforeCatch = true;
  642. Expanded.BraceWrapping.BeforeElse = true;
  643. break;
  644. case FormatStyle::BS_GNU:
  645. Expanded.BraceWrapping = {true, true, FormatStyle::BWACS_Always,
  646. true, true, true,
  647. true, true, true,
  648. true, true, true,
  649. true, true, true,
  650. true};
  651. break;
  652. case FormatStyle::BS_WebKit:
  653. Expanded.BraceWrapping.AfterFunction = true;
  654. break;
  655. default:
  656. break;
  657. }
  658. return Expanded;
  659. }
  660. FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) {
  661. FormatStyle LLVMStyle;
  662. LLVMStyle.Language = Language;
  663. LLVMStyle.AccessModifierOffset = -2;
  664. LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
  665. LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
  666. LLVMStyle.AlignOperands = true;
  667. LLVMStyle.AlignTrailingComments = true;
  668. LLVMStyle.AlignConsecutiveAssignments = false;
  669. LLVMStyle.AlignConsecutiveDeclarations = false;
  670. LLVMStyle.AlignConsecutiveMacros = false;
  671. LLVMStyle.AllowAllArgumentsOnNextLine = true;
  672. LLVMStyle.AllowAllConstructorInitializersOnNextLine = true;
  673. LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
  674. LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
  675. LLVMStyle.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
  676. LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
  677. LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
  678. LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
  679. LLVMStyle.AllowShortLoopsOnASingleLine = false;
  680. LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
  681. LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
  682. LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
  683. LLVMStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
  684. LLVMStyle.BinPackArguments = true;
  685. LLVMStyle.BinPackParameters = true;
  686. LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
  687. LLVMStyle.BreakBeforeTernaryOperators = true;
  688. LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
  689. LLVMStyle.BraceWrapping = {false, false, FormatStyle::BWACS_Never,
  690. false, false, false,
  691. false, false, false,
  692. false, false, false,
  693. false, true, true,
  694. true};
  695. LLVMStyle.BreakAfterJavaFieldAnnotations = false;
  696. LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
  697. LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
  698. LLVMStyle.BreakStringLiterals = true;
  699. LLVMStyle.ColumnLimit = 80;
  700. LLVMStyle.CommentPragmas = "^ IWYU pragma:";
  701. LLVMStyle.CompactNamespaces = false;
  702. LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
  703. LLVMStyle.ConstructorInitializerIndentWidth = 4;
  704. LLVMStyle.ContinuationIndentWidth = 4;
  705. LLVMStyle.Cpp11BracedListStyle = true;
  706. LLVMStyle.DerivePointerAlignment = false;
  707. LLVMStyle.ExperimentalAutoDetectBinPacking = false;
  708. LLVMStyle.FixNamespaceComments = true;
  709. LLVMStyle.ForEachMacros.push_back("foreach");
  710. LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
  711. LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
  712. LLVMStyle.IncludeStyle.IncludeCategories = {
  713. {"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0},
  714. {"^(<|\"(gtest|gmock|isl|json)/)", 3, 0},
  715. {".*", 1, 0}};
  716. LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
  717. LLVMStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve;
  718. LLVMStyle.IndentCaseLabels = false;
  719. LLVMStyle.IndentGotoLabels = true;
  720. LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
  721. LLVMStyle.IndentWrappedFunctionNames = false;
  722. LLVMStyle.IndentWidth = 2;
  723. LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
  724. LLVMStyle.JavaScriptWrapImports = true;
  725. LLVMStyle.TabWidth = 8;
  726. LLVMStyle.MaxEmptyLinesToKeep = 1;
  727. LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
  728. LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
  729. LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
  730. LLVMStyle.ObjCBlockIndentWidth = 2;
  731. LLVMStyle.ObjCSpaceAfterProperty = false;
  732. LLVMStyle.ObjCSpaceBeforeProtocolList = true;
  733. LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
  734. LLVMStyle.SpacesBeforeTrailingComments = 1;
  735. LLVMStyle.Standard = FormatStyle::LS_Latest;
  736. LLVMStyle.UseTab = FormatStyle::UT_Never;
  737. LLVMStyle.ReflowComments = true;
  738. LLVMStyle.SpacesInParentheses = false;
  739. LLVMStyle.SpacesInSquareBrackets = false;
  740. LLVMStyle.SpaceInEmptyBlock = false;
  741. LLVMStyle.SpaceInEmptyParentheses = false;
  742. LLVMStyle.SpacesInContainerLiterals = true;
  743. LLVMStyle.SpacesInCStyleCastParentheses = false;
  744. LLVMStyle.SpaceAfterCStyleCast = false;
  745. LLVMStyle.SpaceAfterLogicalNot = false;
  746. LLVMStyle.SpaceAfterTemplateKeyword = true;
  747. LLVMStyle.SpaceBeforeCtorInitializerColon = true;
  748. LLVMStyle.SpaceBeforeInheritanceColon = true;
  749. LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
  750. LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
  751. LLVMStyle.SpaceBeforeAssignmentOperators = true;
  752. LLVMStyle.SpaceBeforeCpp11BracedList = false;
  753. LLVMStyle.SpacesInAngles = false;
  754. LLVMStyle.PenaltyBreakAssignment = prec::Assignment;
  755. LLVMStyle.PenaltyBreakComment = 300;
  756. LLVMStyle.PenaltyBreakFirstLessLess = 120;
  757. LLVMStyle.PenaltyBreakString = 1000;
  758. LLVMStyle.PenaltyExcessCharacter = 1000000;
  759. LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
  760. LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
  761. LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational;
  762. LLVMStyle.DisableFormat = false;
  763. LLVMStyle.SortIncludes = true;
  764. LLVMStyle.SortUsingDeclarations = true;
  765. LLVMStyle.StatementMacros.push_back("Q_UNUSED");
  766. LLVMStyle.StatementMacros.push_back("QT_REQUIRE_VERSION");
  767. // Defaults that differ when not C++.
  768. if (Language == FormatStyle::LK_TableGen) {
  769. LLVMStyle.SpacesInContainerLiterals = false;
  770. }
  771. return LLVMStyle;
  772. }
  773. FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
  774. if (Language == FormatStyle::LK_TextProto) {
  775. FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
  776. GoogleStyle.Language = FormatStyle::LK_TextProto;
  777. return GoogleStyle;
  778. }
  779. FormatStyle GoogleStyle = getLLVMStyle(Language);
  780. GoogleStyle.AccessModifierOffset = -1;
  781. GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
  782. GoogleStyle.AllowShortIfStatementsOnASingleLine =
  783. FormatStyle::SIS_WithoutElse;
  784. GoogleStyle.AllowShortLoopsOnASingleLine = true;
  785. GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
  786. GoogleStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
  787. GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
  788. GoogleStyle.DerivePointerAlignment = true;
  789. GoogleStyle.IncludeStyle.IncludeCategories = {{"^<ext/.*\\.h>", 2, 0},
  790. {"^<.*\\.h>", 1, 0},
  791. {"^<.*", 2, 0},
  792. {".*", 3, 0}};
  793. GoogleStyle.IncludeStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
  794. GoogleStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup;
  795. GoogleStyle.IndentCaseLabels = true;
  796. GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
  797. GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
  798. GoogleStyle.ObjCSpaceAfterProperty = false;
  799. GoogleStyle.ObjCSpaceBeforeProtocolList = true;
  800. GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
  801. GoogleStyle.RawStringFormats = {
  802. {
  803. FormatStyle::LK_Cpp,
  804. /*Delimiters=*/
  805. {
  806. "cc",
  807. "CC",
  808. "cpp",
  809. "Cpp",
  810. "CPP",
  811. "c++",
  812. "C++",
  813. },
  814. /*EnclosingFunctionNames=*/
  815. {},
  816. /*CanonicalDelimiter=*/"",
  817. /*BasedOnStyle=*/"google",
  818. },
  819. {
  820. FormatStyle::LK_TextProto,
  821. /*Delimiters=*/
  822. {
  823. "pb",
  824. "PB",
  825. "proto",
  826. "PROTO",
  827. },
  828. /*EnclosingFunctionNames=*/
  829. {
  830. "EqualsProto",
  831. "EquivToProto",
  832. "PARSE_PARTIAL_TEXT_PROTO",
  833. "PARSE_TEST_PROTO",
  834. "PARSE_TEXT_PROTO",
  835. "ParseTextOrDie",
  836. "ParseTextProtoOrDie",
  837. },
  838. /*CanonicalDelimiter=*/"",
  839. /*BasedOnStyle=*/"google",
  840. },
  841. };
  842. GoogleStyle.SpacesBeforeTrailingComments = 2;
  843. GoogleStyle.Standard = FormatStyle::LS_Auto;
  844. GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  845. GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
  846. if (Language == FormatStyle::LK_Java) {
  847. GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
  848. GoogleStyle.AlignOperands = false;
  849. GoogleStyle.AlignTrailingComments = false;
  850. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
  851. GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
  852. GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
  853. GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
  854. GoogleStyle.ColumnLimit = 100;
  855. GoogleStyle.SpaceAfterCStyleCast = true;
  856. GoogleStyle.SpacesBeforeTrailingComments = 1;
  857. } else if (Language == FormatStyle::LK_JavaScript) {
  858. GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
  859. GoogleStyle.AlignOperands = false;
  860. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
  861. GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
  862. GoogleStyle.BreakBeforeTernaryOperators = false;
  863. // taze:, triple slash directives (`/// <...`), @see, which is commonly
  864. // followed by overlong URLs.
  865. GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|@see)";
  866. GoogleStyle.MaxEmptyLinesToKeep = 3;
  867. GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
  868. GoogleStyle.SpacesInContainerLiterals = false;
  869. GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
  870. GoogleStyle.JavaScriptWrapImports = false;
  871. } else if (Language == FormatStyle::LK_Proto) {
  872. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
  873. GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
  874. GoogleStyle.SpacesInContainerLiterals = false;
  875. GoogleStyle.Cpp11BracedListStyle = false;
  876. // This affects protocol buffer options specifications and text protos.
  877. // Text protos are currently mostly formatted inside C++ raw string literals
  878. // and often the current breaking behavior of string literals is not
  879. // beneficial there. Investigate turning this on once proper string reflow
  880. // has been implemented.
  881. GoogleStyle.BreakStringLiterals = false;
  882. } else if (Language == FormatStyle::LK_ObjC) {
  883. GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
  884. GoogleStyle.ColumnLimit = 100;
  885. // "Regroup" doesn't work well for ObjC yet (main header heuristic,
  886. // relationship between ObjC standard library headers and other heades,
  887. // #imports, etc.)
  888. GoogleStyle.IncludeStyle.IncludeBlocks =
  889. tooling::IncludeStyle::IBS_Preserve;
  890. }
  891. return GoogleStyle;
  892. }
  893. FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
  894. FormatStyle ChromiumStyle = getGoogleStyle(Language);
  895. // Disable include reordering across blocks in Chromium code.
  896. // - clang-format tries to detect that foo.h is the "main" header for
  897. // foo.cc and foo_unittest.cc via IncludeIsMainRegex. However, Chromium
  898. // uses many other suffices (_win.cc, _mac.mm, _posix.cc, _browsertest.cc,
  899. // _private.cc, _impl.cc etc) in different permutations
  900. // (_win_browsertest.cc) so disable this until IncludeIsMainRegex has a
  901. // better default for Chromium code.
  902. // - The default for .cc and .mm files is different (r357695) for Google style
  903. // for the same reason. The plan is to unify this again once the main
  904. // header detection works for Google's ObjC code, but this hasn't happened
  905. // yet. Since Chromium has some ObjC code, switching Chromium is blocked
  906. // on that.
  907. // - Finally, "If include reordering is harmful, put things in different
  908. // blocks to prevent it" has been a recommendation for a long time that
  909. // people are used to. We'll need a dev education push to change this to
  910. // "If include reordering is harmful, put things in a different block and
  911. // _prepend that with a comment_ to prevent it" before changing behavior.
  912. ChromiumStyle.IncludeStyle.IncludeBlocks =
  913. tooling::IncludeStyle::IBS_Preserve;
  914. if (Language == FormatStyle::LK_Java) {
  915. ChromiumStyle.AllowShortIfStatementsOnASingleLine =
  916. FormatStyle::SIS_WithoutElse;
  917. ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
  918. ChromiumStyle.ContinuationIndentWidth = 8;
  919. ChromiumStyle.IndentWidth = 4;
  920. // See styleguide for import groups:
  921. // https://chromium.googlesource.com/chromium/src/+/master/styleguide/java/java.md#Import-Order
  922. ChromiumStyle.JavaImportGroups = {
  923. "android",
  924. "androidx",
  925. "com",
  926. "dalvik",
  927. "junit",
  928. "org",
  929. "com.google.android.apps.chrome",
  930. "org.chromium",
  931. "java",
  932. "javax",
  933. };
  934. ChromiumStyle.SortIncludes = true;
  935. } else if (Language == FormatStyle::LK_JavaScript) {
  936. ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
  937. ChromiumStyle.AllowShortLoopsOnASingleLine = false;
  938. } else {
  939. ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  940. ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
  941. ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
  942. ChromiumStyle.AllowShortLoopsOnASingleLine = false;
  943. ChromiumStyle.BinPackParameters = false;
  944. ChromiumStyle.DerivePointerAlignment = false;
  945. if (Language == FormatStyle::LK_ObjC)
  946. ChromiumStyle.ColumnLimit = 80;
  947. }
  948. return ChromiumStyle;
  949. }
  950. FormatStyle getMozillaStyle() {
  951. FormatStyle MozillaStyle = getLLVMStyle();
  952. MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  953. MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
  954. MozillaStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
  955. MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
  956. FormatStyle::DRTBS_TopLevel;
  957. MozillaStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
  958. MozillaStyle.BinPackParameters = false;
  959. MozillaStyle.BinPackArguments = false;
  960. MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
  961. MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
  962. MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
  963. MozillaStyle.ConstructorInitializerIndentWidth = 2;
  964. MozillaStyle.ContinuationIndentWidth = 2;
  965. MozillaStyle.Cpp11BracedListStyle = false;
  966. MozillaStyle.FixNamespaceComments = false;
  967. MozillaStyle.IndentCaseLabels = true;
  968. MozillaStyle.ObjCSpaceAfterProperty = true;
  969. MozillaStyle.ObjCSpaceBeforeProtocolList = false;
  970. MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  971. MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
  972. MozillaStyle.SpaceAfterTemplateKeyword = false;
  973. return MozillaStyle;
  974. }
  975. FormatStyle getWebKitStyle() {
  976. FormatStyle Style = getLLVMStyle();
  977. Style.AccessModifierOffset = -4;
  978. Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
  979. Style.AlignOperands = false;
  980. Style.AlignTrailingComments = false;
  981. Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
  982. Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
  983. Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
  984. Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
  985. Style.Cpp11BracedListStyle = false;
  986. Style.ColumnLimit = 0;
  987. Style.FixNamespaceComments = false;
  988. Style.IndentWidth = 4;
  989. Style.NamespaceIndentation = FormatStyle::NI_Inner;
  990. Style.ObjCBlockIndentWidth = 4;
  991. Style.ObjCSpaceAfterProperty = true;
  992. Style.PointerAlignment = FormatStyle::PAS_Left;
  993. Style.SpaceBeforeCpp11BracedList = true;
  994. Style.SpaceInEmptyBlock = true;
  995. return Style;
  996. }
  997. FormatStyle getGNUStyle() {
  998. FormatStyle Style = getLLVMStyle();
  999. Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
  1000. Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
  1001. Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
  1002. Style.BreakBeforeBraces = FormatStyle::BS_GNU;
  1003. Style.BreakBeforeTernaryOperators = true;
  1004. Style.Cpp11BracedListStyle = false;
  1005. Style.ColumnLimit = 79;
  1006. Style.FixNamespaceComments = false;
  1007. Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
  1008. Style.Standard = FormatStyle::LS_Cpp03;
  1009. return Style;
  1010. }
  1011. FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language) {
  1012. FormatStyle Style = getLLVMStyle();
  1013. Style.ColumnLimit = 120;
  1014. Style.TabWidth = 4;
  1015. Style.IndentWidth = 4;
  1016. Style.UseTab = FormatStyle::UT_Never;
  1017. Style.BreakBeforeBraces = FormatStyle::BS_Custom;
  1018. Style.BraceWrapping.AfterClass = true;
  1019. Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
  1020. Style.BraceWrapping.AfterEnum = true;
  1021. Style.BraceWrapping.AfterFunction = true;
  1022. Style.BraceWrapping.AfterNamespace = true;
  1023. Style.BraceWrapping.AfterObjCDeclaration = true;
  1024. Style.BraceWrapping.AfterStruct = true;
  1025. Style.BraceWrapping.AfterExternBlock = true;
  1026. Style.BraceWrapping.BeforeCatch = true;
  1027. Style.BraceWrapping.BeforeElse = true;
  1028. Style.PenaltyReturnTypeOnItsOwnLine = 1000;
  1029. Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
  1030. Style.AllowShortCaseLabelsOnASingleLine = false;
  1031. Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
  1032. Style.AllowShortLoopsOnASingleLine = false;
  1033. return Style;
  1034. }
  1035. FormatStyle getNoStyle() {
  1036. FormatStyle NoStyle = getLLVMStyle();
  1037. NoStyle.DisableFormat = true;
  1038. NoStyle.SortIncludes = false;
  1039. NoStyle.SortUsingDeclarations = false;
  1040. return NoStyle;
  1041. }
  1042. bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
  1043. FormatStyle *Style) {
  1044. if (Name.equals_lower("llvm")) {
  1045. *Style = getLLVMStyle(Language);
  1046. } else if (Name.equals_lower("chromium")) {
  1047. *Style = getChromiumStyle(Language);
  1048. } else if (Name.equals_lower("mozilla")) {
  1049. *Style = getMozillaStyle();
  1050. } else if (Name.equals_lower("google")) {
  1051. *Style = getGoogleStyle(Language);
  1052. } else if (Name.equals_lower("webkit")) {
  1053. *Style = getWebKitStyle();
  1054. } else if (Name.equals_lower("gnu")) {
  1055. *Style = getGNUStyle();
  1056. } else if (Name.equals_lower("microsoft")) {
  1057. *Style = getMicrosoftStyle(Language);
  1058. } else if (Name.equals_lower("none")) {
  1059. *Style = getNoStyle();
  1060. } else {
  1061. return false;
  1062. }
  1063. Style->Language = Language;
  1064. return true;
  1065. }
  1066. std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
  1067. assert(Style);
  1068. FormatStyle::LanguageKind Language = Style->Language;
  1069. assert(Language != FormatStyle::LK_None);
  1070. if (Text.trim().empty())
  1071. return make_error_code(ParseError::Error);
  1072. Style->StyleSet.Clear();
  1073. std::vector<FormatStyle> Styles;
  1074. llvm::yaml::Input Input(Text);
  1075. // DocumentListTraits<vector<FormatStyle>> uses the context to get default
  1076. // values for the fields, keys for which are missing from the configuration.
  1077. // Mapping also uses the context to get the language to find the correct
  1078. // base style.
  1079. Input.setContext(Style);
  1080. Input >> Styles;
  1081. if (Input.error())
  1082. return Input.error();
  1083. for (unsigned i = 0; i < Styles.size(); ++i) {
  1084. // Ensures that only the first configuration can skip the Language option.
  1085. if (Styles[i].Language == FormatStyle::LK_None && i != 0)
  1086. return make_error_code(ParseError::Error);
  1087. // Ensure that each language is configured at most once.
  1088. for (unsigned j = 0; j < i; ++j) {
  1089. if (Styles[i].Language == Styles[j].Language) {
  1090. LLVM_DEBUG(llvm::dbgs()
  1091. << "Duplicate languages in the config file on positions "
  1092. << j << " and " << i << "\n");
  1093. return make_error_code(ParseError::Error);
  1094. }
  1095. }
  1096. }
  1097. // Look for a suitable configuration starting from the end, so we can
  1098. // find the configuration for the specific language first, and the default
  1099. // configuration (which can only be at slot 0) after it.
  1100. FormatStyle::FormatStyleSet StyleSet;
  1101. bool LanguageFound = false;
  1102. for (int i = Styles.size() - 1; i >= 0; --i) {
  1103. if (Styles[i].Language != FormatStyle::LK_None)
  1104. StyleSet.Add(Styles[i]);
  1105. if (Styles[i].Language == Language)
  1106. LanguageFound = true;
  1107. }
  1108. if (!LanguageFound) {
  1109. if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None)
  1110. return make_error_code(ParseError::Unsuitable);
  1111. FormatStyle DefaultStyle = Styles[0];
  1112. DefaultStyle.Language = Language;
  1113. StyleSet.Add(std::move(DefaultStyle));
  1114. }
  1115. *Style = *StyleSet.Get(Language);
  1116. return make_error_code(ParseError::Success);
  1117. }
  1118. std::string configurationAsText(const FormatStyle &Style) {
  1119. std::string Text;
  1120. llvm::raw_string_ostream Stream(Text);
  1121. llvm::yaml::Output Output(Stream);
  1122. // We use the same mapping method for input and output, so we need a non-const
  1123. // reference here.
  1124. FormatStyle NonConstStyle = expandPresets(Style);
  1125. Output << NonConstStyle;
  1126. return Stream.str();
  1127. }
  1128. llvm::Optional<FormatStyle>
  1129. FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const {
  1130. if (!Styles)
  1131. return None;
  1132. auto It = Styles->find(Language);
  1133. if (It == Styles->end())
  1134. return None;
  1135. FormatStyle Style = It->second;
  1136. Style.StyleSet = *this;
  1137. return Style;
  1138. }
  1139. void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
  1140. assert(Style.Language != LK_None &&
  1141. "Cannot add a style for LK_None to a StyleSet");
  1142. assert(
  1143. !Style.StyleSet.Styles &&
  1144. "Cannot add a style associated with an existing StyleSet to a StyleSet");
  1145. if (!Styles)
  1146. Styles = std::make_shared<MapType>();
  1147. (*Styles)[Style.Language] = std::move(Style);
  1148. }
  1149. void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
  1150. llvm::Optional<FormatStyle>
  1151. FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const {
  1152. return StyleSet.Get(Language);
  1153. }
  1154. namespace {
  1155. class JavaScriptRequoter : public TokenAnalyzer {
  1156. public:
  1157. JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
  1158. : TokenAnalyzer(Env, Style) {}
  1159. std::pair<tooling::Replacements, unsigned>
  1160. analyze(TokenAnnotator &Annotator,
  1161. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1162. FormatTokenLexer &Tokens) override {
  1163. AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
  1164. tooling::Replacements Result;
  1165. requoteJSStringLiteral(AnnotatedLines, Result);
  1166. return {Result, 0};
  1167. }
  1168. private:
  1169. // Replaces double/single-quoted string literal as appropriate, re-escaping
  1170. // the contents in the process.
  1171. void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
  1172. tooling::Replacements &Result) {
  1173. for (AnnotatedLine *Line : Lines) {
  1174. requoteJSStringLiteral(Line->Children, Result);
  1175. if (!Line->Affected)
  1176. continue;
  1177. for (FormatToken *FormatTok = Line->First; FormatTok;
  1178. FormatTok = FormatTok->Next) {
  1179. StringRef Input = FormatTok->TokenText;
  1180. if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
  1181. // NB: testing for not starting with a double quote to avoid
  1182. // breaking `template strings`.
  1183. (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
  1184. !Input.startswith("\"")) ||
  1185. (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
  1186. !Input.startswith("\'")))
  1187. continue;
  1188. // Change start and end quote.
  1189. bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
  1190. SourceLocation Start = FormatTok->Tok.getLocation();
  1191. auto Replace = [&](SourceLocation Start, unsigned Length,
  1192. StringRef ReplacementText) {
  1193. auto Err = Result.add(tooling::Replacement(
  1194. Env.getSourceManager(), Start, Length, ReplacementText));
  1195. // FIXME: handle error. For now, print error message and skip the
  1196. // replacement for release version.
  1197. if (Err) {
  1198. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  1199. assert(false);
  1200. }
  1201. };
  1202. Replace(Start, 1, IsSingle ? "'" : "\"");
  1203. Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
  1204. IsSingle ? "'" : "\"");
  1205. // Escape internal quotes.
  1206. bool Escaped = false;
  1207. for (size_t i = 1; i < Input.size() - 1; i++) {
  1208. switch (Input[i]) {
  1209. case '\\':
  1210. if (!Escaped && i + 1 < Input.size() &&
  1211. ((IsSingle && Input[i + 1] == '"') ||
  1212. (!IsSingle && Input[i + 1] == '\''))) {
  1213. // Remove this \, it's escaping a " or ' that no longer needs
  1214. // escaping
  1215. Replace(Start.getLocWithOffset(i), 1, "");
  1216. continue;
  1217. }
  1218. Escaped = !Escaped;
  1219. break;
  1220. case '\"':
  1221. case '\'':
  1222. if (!Escaped && IsSingle == (Input[i] == '\'')) {
  1223. // Escape the quote.
  1224. Replace(Start.getLocWithOffset(i), 0, "\\");
  1225. }
  1226. Escaped = false;
  1227. break;
  1228. default:
  1229. Escaped = false;
  1230. break;
  1231. }
  1232. }
  1233. }
  1234. }
  1235. }
  1236. };
  1237. class Formatter : public TokenAnalyzer {
  1238. public:
  1239. Formatter(const Environment &Env, const FormatStyle &Style,
  1240. FormattingAttemptStatus *Status)
  1241. : TokenAnalyzer(Env, Style), Status(Status) {}
  1242. std::pair<tooling::Replacements, unsigned>
  1243. analyze(TokenAnnotator &Annotator,
  1244. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1245. FormatTokenLexer &Tokens) override {
  1246. tooling::Replacements Result;
  1247. deriveLocalStyle(AnnotatedLines);
  1248. AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
  1249. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  1250. Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
  1251. }
  1252. Annotator.setCommentLineLevels(AnnotatedLines);
  1253. WhitespaceManager Whitespaces(
  1254. Env.getSourceManager(), Style,
  1255. inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID())));
  1256. ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
  1257. Env.getSourceManager(), Whitespaces, Encoding,
  1258. BinPackInconclusiveFunctions);
  1259. unsigned Penalty =
  1260. UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
  1261. Tokens.getKeywords(), Env.getSourceManager(),
  1262. Status)
  1263. .format(AnnotatedLines, /*DryRun=*/false,
  1264. /*AdditionalIndent=*/0,
  1265. /*FixBadIndentation=*/false,
  1266. /*FirstStartColumn=*/Env.getFirstStartColumn(),
  1267. /*NextStartColumn=*/Env.getNextStartColumn(),
  1268. /*LastStartColumn=*/Env.getLastStartColumn());
  1269. for (const auto &R : Whitespaces.generateReplacements())
  1270. if (Result.add(R))
  1271. return std::make_pair(Result, 0);
  1272. return std::make_pair(Result, Penalty);
  1273. }
  1274. private:
  1275. static bool inputUsesCRLF(StringRef Text) {
  1276. return Text.count('\r') * 2 > Text.count('\n');
  1277. }
  1278. bool
  1279. hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
  1280. for (const AnnotatedLine *Line : Lines) {
  1281. if (hasCpp03IncompatibleFormat(Line->Children))
  1282. return true;
  1283. for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
  1284. if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
  1285. if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
  1286. return true;
  1287. if (Tok->is(TT_TemplateCloser) &&
  1288. Tok->Previous->is(TT_TemplateCloser))
  1289. return true;
  1290. }
  1291. }
  1292. }
  1293. return false;
  1294. }
  1295. int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
  1296. int AlignmentDiff = 0;
  1297. for (const AnnotatedLine *Line : Lines) {
  1298. AlignmentDiff += countVariableAlignments(Line->Children);
  1299. for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
  1300. if (!Tok->is(TT_PointerOrReference))
  1301. continue;
  1302. bool SpaceBefore =
  1303. Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
  1304. bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
  1305. Tok->Next->WhitespaceRange.getEnd();
  1306. if (SpaceBefore && !SpaceAfter)
  1307. ++AlignmentDiff;
  1308. if (!SpaceBefore && SpaceAfter)
  1309. --AlignmentDiff;
  1310. }
  1311. }
  1312. return AlignmentDiff;
  1313. }
  1314. void
  1315. deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  1316. bool HasBinPackedFunction = false;
  1317. bool HasOnePerLineFunction = false;
  1318. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  1319. if (!AnnotatedLines[i]->First->Next)
  1320. continue;
  1321. FormatToken *Tok = AnnotatedLines[i]->First->Next;
  1322. while (Tok->Next) {
  1323. if (Tok->PackingKind == PPK_BinPacked)
  1324. HasBinPackedFunction = true;
  1325. if (Tok->PackingKind == PPK_OnePerLine)
  1326. HasOnePerLineFunction = true;
  1327. Tok = Tok->Next;
  1328. }
  1329. }
  1330. if (Style.DerivePointerAlignment)
  1331. Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
  1332. ? FormatStyle::PAS_Left
  1333. : FormatStyle::PAS_Right;
  1334. if (Style.Standard == FormatStyle::LS_Auto)
  1335. Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
  1336. ? FormatStyle::LS_Latest
  1337. : FormatStyle::LS_Cpp03;
  1338. BinPackInconclusiveFunctions =
  1339. HasBinPackedFunction || !HasOnePerLineFunction;
  1340. }
  1341. bool BinPackInconclusiveFunctions;
  1342. FormattingAttemptStatus *Status;
  1343. };
  1344. // This class clean up the erroneous/redundant code around the given ranges in
  1345. // file.
  1346. class Cleaner : public TokenAnalyzer {
  1347. public:
  1348. Cleaner(const Environment &Env, const FormatStyle &Style)
  1349. : TokenAnalyzer(Env, Style),
  1350. DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
  1351. // FIXME: eliminate unused parameters.
  1352. std::pair<tooling::Replacements, unsigned>
  1353. analyze(TokenAnnotator &Annotator,
  1354. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1355. FormatTokenLexer &Tokens) override {
  1356. // FIXME: in the current implementation the granularity of affected range
  1357. // is an annotated line. However, this is not sufficient. Furthermore,
  1358. // redundant code introduced by replacements does not necessarily
  1359. // intercept with ranges of replacements that result in the redundancy.
  1360. // To determine if some redundant code is actually introduced by
  1361. // replacements(e.g. deletions), we need to come up with a more
  1362. // sophisticated way of computing affected ranges.
  1363. AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
  1364. checkEmptyNamespace(AnnotatedLines);
  1365. for (auto *Line : AnnotatedLines)
  1366. cleanupLine(Line);
  1367. return {generateFixes(), 0};
  1368. }
  1369. private:
  1370. void cleanupLine(AnnotatedLine *Line) {
  1371. for (auto *Child : Line->Children) {
  1372. cleanupLine(Child);
  1373. }
  1374. if (Line->Affected) {
  1375. cleanupRight(Line->First, tok::comma, tok::comma);
  1376. cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
  1377. cleanupRight(Line->First, tok::l_paren, tok::comma);
  1378. cleanupLeft(Line->First, tok::comma, tok::r_paren);
  1379. cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
  1380. cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
  1381. cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
  1382. }
  1383. }
  1384. bool containsOnlyComments(const AnnotatedLine &Line) {
  1385. for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
  1386. if (Tok->isNot(tok::comment))
  1387. return false;
  1388. }
  1389. return true;
  1390. }
  1391. // Iterate through all lines and remove any empty (nested) namespaces.
  1392. void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  1393. std::set<unsigned> DeletedLines;
  1394. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  1395. auto &Line = *AnnotatedLines[i];
  1396. if (Line.startsWithNamespace()) {
  1397. checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
  1398. }
  1399. }
  1400. for (auto Line : DeletedLines) {
  1401. FormatToken *Tok = AnnotatedLines[Line]->First;
  1402. while (Tok) {
  1403. deleteToken(Tok);
  1404. Tok = Tok->Next;
  1405. }
  1406. }
  1407. }
  1408. // The function checks if the namespace, which starts from \p CurrentLine, and
  1409. // its nested namespaces are empty and delete them if they are empty. It also
  1410. // sets \p NewLine to the last line checked.
  1411. // Returns true if the current namespace is empty.
  1412. bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1413. unsigned CurrentLine, unsigned &NewLine,
  1414. std::set<unsigned> &DeletedLines) {
  1415. unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
  1416. if (Style.BraceWrapping.AfterNamespace) {
  1417. // If the left brace is in a new line, we should consume it first so that
  1418. // it does not make the namespace non-empty.
  1419. // FIXME: error handling if there is no left brace.
  1420. if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
  1421. NewLine = CurrentLine;
  1422. return false;
  1423. }
  1424. } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
  1425. return false;
  1426. }
  1427. while (++CurrentLine < End) {
  1428. if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
  1429. break;
  1430. if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
  1431. if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
  1432. DeletedLines))
  1433. return false;
  1434. CurrentLine = NewLine;
  1435. continue;
  1436. }
  1437. if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
  1438. continue;
  1439. // If there is anything other than comments or nested namespaces in the
  1440. // current namespace, the namespace cannot be empty.
  1441. NewLine = CurrentLine;
  1442. return false;
  1443. }
  1444. NewLine = CurrentLine;
  1445. if (CurrentLine >= End)
  1446. return false;
  1447. // Check if the empty namespace is actually affected by changed ranges.
  1448. if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
  1449. AnnotatedLines[InitLine]->First->Tok.getLocation(),
  1450. AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
  1451. return false;
  1452. for (unsigned i = InitLine; i <= CurrentLine; ++i) {
  1453. DeletedLines.insert(i);
  1454. }
  1455. return true;
  1456. }
  1457. // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
  1458. // of the token in the pair if the left token has \p LK token kind and the
  1459. // right token has \p RK token kind. If \p DeleteLeft is true, the left token
  1460. // is deleted on match; otherwise, the right token is deleted.
  1461. template <typename LeftKind, typename RightKind>
  1462. void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
  1463. bool DeleteLeft) {
  1464. auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
  1465. for (auto *Res = Tok.Next; Res; Res = Res->Next)
  1466. if (!Res->is(tok::comment) &&
  1467. DeletedTokens.find(Res) == DeletedTokens.end())
  1468. return Res;
  1469. return nullptr;
  1470. };
  1471. for (auto *Left = Start; Left;) {
  1472. auto *Right = NextNotDeleted(*Left);
  1473. if (!Right)
  1474. break;
  1475. if (Left->is(LK) && Right->is(RK)) {
  1476. deleteToken(DeleteLeft ? Left : Right);
  1477. for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
  1478. deleteToken(Tok);
  1479. // If the right token is deleted, we should keep the left token
  1480. // unchanged and pair it with the new right token.
  1481. if (!DeleteLeft)
  1482. continue;
  1483. }
  1484. Left = Right;
  1485. }
  1486. }
  1487. template <typename LeftKind, typename RightKind>
  1488. void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
  1489. cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
  1490. }
  1491. template <typename LeftKind, typename RightKind>
  1492. void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
  1493. cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
  1494. }
  1495. // Delete the given token.
  1496. inline void deleteToken(FormatToken *Tok) {
  1497. if (Tok)
  1498. DeletedTokens.insert(Tok);
  1499. }
  1500. tooling::Replacements generateFixes() {
  1501. tooling::Replacements Fixes;
  1502. std::vector<FormatToken *> Tokens;
  1503. std::copy(DeletedTokens.begin(), DeletedTokens.end(),
  1504. std::back_inserter(Tokens));
  1505. // Merge multiple continuous token deletions into one big deletion so that
  1506. // the number of replacements can be reduced. This makes computing affected
  1507. // ranges more efficient when we run reformat on the changed code.
  1508. unsigned Idx = 0;
  1509. while (Idx < Tokens.size()) {
  1510. unsigned St = Idx, End = Idx;
  1511. while ((End + 1) < Tokens.size() &&
  1512. Tokens[End]->Next == Tokens[End + 1]) {
  1513. End++;
  1514. }
  1515. auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
  1516. Tokens[End]->Tok.getEndLoc());
  1517. auto Err =
  1518. Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
  1519. // FIXME: better error handling. for now just print error message and skip
  1520. // for the release version.
  1521. if (Err) {
  1522. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  1523. assert(false && "Fixes must not conflict!");
  1524. }
  1525. Idx = End + 1;
  1526. }
  1527. return Fixes;
  1528. }
  1529. // Class for less-than inequality comparason for the set `RedundantTokens`.
  1530. // We store tokens in the order they appear in the translation unit so that
  1531. // we do not need to sort them in `generateFixes()`.
  1532. struct FormatTokenLess {
  1533. FormatTokenLess(const SourceManager &SM) : SM(SM) {}
  1534. bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
  1535. return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
  1536. RHS->Tok.getLocation());
  1537. }
  1538. const SourceManager &SM;
  1539. };
  1540. // Tokens to be deleted.
  1541. std::set<FormatToken *, FormatTokenLess> DeletedTokens;
  1542. };
  1543. class ObjCHeaderStyleGuesser : public TokenAnalyzer {
  1544. public:
  1545. ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
  1546. : TokenAnalyzer(Env, Style), IsObjC(false) {}
  1547. std::pair<tooling::Replacements, unsigned>
  1548. analyze(TokenAnnotator &Annotator,
  1549. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1550. FormatTokenLexer &Tokens) override {
  1551. assert(Style.Language == FormatStyle::LK_Cpp);
  1552. IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
  1553. Tokens.getKeywords());
  1554. tooling::Replacements Result;
  1555. return {Result, 0};
  1556. }
  1557. bool isObjC() { return IsObjC; }
  1558. private:
  1559. static bool
  1560. guessIsObjC(const SourceManager &SourceManager,
  1561. const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1562. const AdditionalKeywords &Keywords) {
  1563. // Keep this array sorted, since we are binary searching over it.
  1564. static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
  1565. "CGFloat",
  1566. "CGPoint",
  1567. "CGPointMake",
  1568. "CGPointZero",
  1569. "CGRect",
  1570. "CGRectEdge",
  1571. "CGRectInfinite",
  1572. "CGRectMake",
  1573. "CGRectNull",
  1574. "CGRectZero",
  1575. "CGSize",
  1576. "CGSizeMake",
  1577. "CGVector",
  1578. "CGVectorMake",
  1579. "NSAffineTransform",
  1580. "NSArray",
  1581. "NSAttributedString",
  1582. "NSBlockOperation",
  1583. "NSBundle",
  1584. "NSCache",
  1585. "NSCalendar",
  1586. "NSCharacterSet",
  1587. "NSCountedSet",
  1588. "NSData",
  1589. "NSDataDetector",
  1590. "NSDecimal",
  1591. "NSDecimalNumber",
  1592. "NSDictionary",
  1593. "NSEdgeInsets",
  1594. "NSHashTable",
  1595. "NSIndexPath",
  1596. "NSIndexSet",
  1597. "NSInteger",
  1598. "NSInvocationOperation",
  1599. "NSLocale",
  1600. "NSMapTable",
  1601. "NSMutableArray",
  1602. "NSMutableAttributedString",
  1603. "NSMutableCharacterSet",
  1604. "NSMutableData",
  1605. "NSMutableDictionary",
  1606. "NSMutableIndexSet",
  1607. "NSMutableOrderedSet",
  1608. "NSMutableSet",
  1609. "NSMutableString",
  1610. "NSNumber",
  1611. "NSNumberFormatter",
  1612. "NSObject",
  1613. "NSOperation",
  1614. "NSOperationQueue",
  1615. "NSOperationQueuePriority",
  1616. "NSOrderedSet",
  1617. "NSPoint",
  1618. "NSPointerArray",
  1619. "NSQualityOfService",
  1620. "NSRange",
  1621. "NSRect",
  1622. "NSRegularExpression",
  1623. "NSSet",
  1624. "NSSize",
  1625. "NSString",
  1626. "NSTimeZone",
  1627. "NSUInteger",
  1628. "NSURL",
  1629. "NSURLComponents",
  1630. "NSURLQueryItem",
  1631. "NSUUID",
  1632. "NSValue",
  1633. "UIImage",
  1634. "UIView",
  1635. };
  1636. for (auto Line : AnnotatedLines) {
  1637. for (const FormatToken *FormatTok = Line->First; FormatTok;
  1638. FormatTok = FormatTok->Next) {
  1639. if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
  1640. (FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword ||
  1641. FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
  1642. tok::l_brace))) ||
  1643. (FormatTok->Tok.isAnyIdentifier() &&
  1644. std::binary_search(std::begin(FoundationIdentifiers),
  1645. std::end(FoundationIdentifiers),
  1646. FormatTok->TokenText)) ||
  1647. FormatTok->is(TT_ObjCStringLiteral) ||
  1648. FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
  1649. Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
  1650. TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
  1651. TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
  1652. TT_ObjCProperty)) {
  1653. LLVM_DEBUG(llvm::dbgs()
  1654. << "Detected ObjC at location "
  1655. << FormatTok->Tok.getLocation().printToString(
  1656. SourceManager)
  1657. << " token: " << FormatTok->TokenText << " token type: "
  1658. << getTokenTypeName(FormatTok->Type) << "\n");
  1659. return true;
  1660. }
  1661. if (guessIsObjC(SourceManager, Line->Children, Keywords))
  1662. return true;
  1663. }
  1664. }
  1665. return false;
  1666. }
  1667. bool IsObjC;
  1668. };
  1669. struct IncludeDirective {
  1670. StringRef Filename;
  1671. StringRef Text;
  1672. unsigned Offset;
  1673. int Category;
  1674. int Priority;
  1675. };
  1676. struct JavaImportDirective {
  1677. StringRef Identifier;
  1678. StringRef Text;
  1679. unsigned Offset;
  1680. std::vector<StringRef> AssociatedCommentLines;
  1681. bool IsStatic;
  1682. };
  1683. } // end anonymous namespace
  1684. // Determines whether 'Ranges' intersects with ('Start', 'End').
  1685. static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
  1686. unsigned End) {
  1687. for (auto Range : Ranges) {
  1688. if (Range.getOffset() < End &&
  1689. Range.getOffset() + Range.getLength() > Start)
  1690. return true;
  1691. }
  1692. return false;
  1693. }
  1694. // Returns a pair (Index, OffsetToEOL) describing the position of the cursor
  1695. // before sorting/deduplicating. Index is the index of the include under the
  1696. // cursor in the original set of includes. If this include has duplicates, it is
  1697. // the index of the first of the duplicates as the others are going to be
  1698. // removed. OffsetToEOL describes the cursor's position relative to the end of
  1699. // its current line.
  1700. // If `Cursor` is not on any #include, `Index` will be UINT_MAX.
  1701. static std::pair<unsigned, unsigned>
  1702. FindCursorIndex(const SmallVectorImpl<IncludeDirective> &Includes,
  1703. const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) {
  1704. unsigned CursorIndex = UINT_MAX;
  1705. unsigned OffsetToEOL = 0;
  1706. for (int i = 0, e = Includes.size(); i != e; ++i) {
  1707. unsigned Start = Includes[Indices[i]].Offset;
  1708. unsigned End = Start + Includes[Indices[i]].Text.size();
  1709. if (!(Cursor >= Start && Cursor < End))
  1710. continue;
  1711. CursorIndex = Indices[i];
  1712. OffsetToEOL = End - Cursor;
  1713. // Put the cursor on the only remaining #include among the duplicate
  1714. // #includes.
  1715. while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
  1716. CursorIndex = i;
  1717. break;
  1718. }
  1719. return std::make_pair(CursorIndex, OffsetToEOL);
  1720. }
  1721. // Replace all "\r\n" with "\n".
  1722. std::string replaceCRLF(const std::string &Code) {
  1723. std::string NewCode;
  1724. size_t Pos = 0, LastPos = 0;
  1725. do {
  1726. Pos = Code.find("\r\n", LastPos);
  1727. if (Pos == LastPos) {
  1728. LastPos++;
  1729. continue;
  1730. }
  1731. if (Pos == std::string::npos) {
  1732. NewCode += Code.substr(LastPos);
  1733. break;
  1734. }
  1735. NewCode += Code.substr(LastPos, Pos - LastPos) + "\n";
  1736. LastPos = Pos + 2;
  1737. } while (Pos != std::string::npos);
  1738. return NewCode;
  1739. }
  1740. // Sorts and deduplicate a block of includes given by 'Includes' alphabetically
  1741. // adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
  1742. // source order.
  1743. // #include directives with the same text will be deduplicated, and only the
  1744. // first #include in the duplicate #includes remains. If the `Cursor` is
  1745. // provided and put on a deleted #include, it will be moved to the remaining
  1746. // #include in the duplicate #includes.
  1747. static void sortCppIncludes(const FormatStyle &Style,
  1748. const SmallVectorImpl<IncludeDirective> &Includes,
  1749. ArrayRef<tooling::Range> Ranges, StringRef FileName,
  1750. StringRef Code, tooling::Replacements &Replaces,
  1751. unsigned *Cursor) {
  1752. tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
  1753. unsigned IncludesBeginOffset = Includes.front().Offset;
  1754. unsigned IncludesEndOffset =
  1755. Includes.back().Offset + Includes.back().Text.size();
  1756. unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
  1757. if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
  1758. return;
  1759. SmallVector<unsigned, 16> Indices;
  1760. for (unsigned i = 0, e = Includes.size(); i != e; ++i) {
  1761. Indices.push_back(i);
  1762. }
  1763. llvm::stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
  1764. return std::tie(Includes[LHSI].Priority, Includes[LHSI].Filename) <
  1765. std::tie(Includes[RHSI].Priority, Includes[RHSI].Filename);
  1766. });
  1767. // The index of the include on which the cursor will be put after
  1768. // sorting/deduplicating.
  1769. unsigned CursorIndex;
  1770. // The offset from cursor to the end of line.
  1771. unsigned CursorToEOLOffset;
  1772. if (Cursor)
  1773. std::tie(CursorIndex, CursorToEOLOffset) =
  1774. FindCursorIndex(Includes, Indices, *Cursor);
  1775. // Deduplicate #includes.
  1776. Indices.erase(std::unique(Indices.begin(), Indices.end(),
  1777. [&](unsigned LHSI, unsigned RHSI) {
  1778. return Includes[LHSI].Text == Includes[RHSI].Text;
  1779. }),
  1780. Indices.end());
  1781. int CurrentCategory = Includes.front().Category;
  1782. // If the #includes are out of order, we generate a single replacement fixing
  1783. // the entire block. Otherwise, no replacement is generated.
  1784. // In case Style.IncldueStyle.IncludeBlocks != IBS_Preserve, this check is not
  1785. // enough as additional newlines might be added or removed across #include
  1786. // blocks. This we handle below by generating the updated #imclude blocks and
  1787. // comparing it to the original.
  1788. if (Indices.size() == Includes.size() &&
  1789. std::is_sorted(Indices.begin(), Indices.end()) &&
  1790. Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve)
  1791. return;
  1792. std::string result;
  1793. for (unsigned Index : Indices) {
  1794. if (!result.empty()) {
  1795. result += "\n";
  1796. if (Style.IncludeStyle.IncludeBlocks ==
  1797. tooling::IncludeStyle::IBS_Regroup &&
  1798. CurrentCategory != Includes[Index].Category)
  1799. result += "\n";
  1800. }
  1801. result += Includes[Index].Text;
  1802. if (Cursor && CursorIndex == Index)
  1803. *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
  1804. CurrentCategory = Includes[Index].Category;
  1805. }
  1806. // If the #includes are out of order, we generate a single replacement fixing
  1807. // the entire range of blocks. Otherwise, no replacement is generated.
  1808. if (replaceCRLF(result) ==
  1809. replaceCRLF(Code.substr(IncludesBeginOffset, IncludesBlockSize)))
  1810. return;
  1811. auto Err = Replaces.add(tooling::Replacement(
  1812. FileName, Includes.front().Offset, IncludesBlockSize, result));
  1813. // FIXME: better error handling. For now, just skip the replacement for the
  1814. // release version.
  1815. if (Err) {
  1816. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  1817. assert(false);
  1818. }
  1819. }
  1820. namespace {
  1821. const char CppIncludeRegexPattern[] =
  1822. R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
  1823. } // anonymous namespace
  1824. tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
  1825. ArrayRef<tooling::Range> Ranges,
  1826. StringRef FileName,
  1827. tooling::Replacements &Replaces,
  1828. unsigned *Cursor) {
  1829. unsigned Prev = 0;
  1830. unsigned SearchFrom = 0;
  1831. llvm::Regex IncludeRegex(CppIncludeRegexPattern);
  1832. SmallVector<StringRef, 4> Matches;
  1833. SmallVector<IncludeDirective, 16> IncludesInBlock;
  1834. // In compiled files, consider the first #include to be the main #include of
  1835. // the file if it is not a system #include. This ensures that the header
  1836. // doesn't have hidden dependencies
  1837. // (http://llvm.org/docs/CodingStandards.html#include-style).
  1838. //
  1839. // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
  1840. // cases where the first #include is unlikely to be the main header.
  1841. tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
  1842. bool FirstIncludeBlock = true;
  1843. bool MainIncludeFound = false;
  1844. bool FormattingOff = false;
  1845. for (;;) {
  1846. auto Pos = Code.find('\n', SearchFrom);
  1847. StringRef Line =
  1848. Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
  1849. StringRef Trimmed = Line.trim();
  1850. if (Trimmed == "// clang-format off" || Trimmed == "/* clang-format off */")
  1851. FormattingOff = true;
  1852. else if (Trimmed == "// clang-format on" ||
  1853. Trimmed == "/* clang-format on */")
  1854. FormattingOff = false;
  1855. const bool EmptyLineSkipped =
  1856. Trimmed.empty() &&
  1857. (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge ||
  1858. Style.IncludeStyle.IncludeBlocks ==
  1859. tooling::IncludeStyle::IBS_Regroup);
  1860. if (!FormattingOff && !Line.endswith("\\")) {
  1861. if (IncludeRegex.match(Line, &Matches)) {
  1862. StringRef IncludeName = Matches[2];
  1863. int Category = Categories.getIncludePriority(
  1864. IncludeName,
  1865. /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
  1866. int Priority = Categories.getSortIncludePriority(
  1867. IncludeName, !MainIncludeFound && FirstIncludeBlock);
  1868. if (Category == 0)
  1869. MainIncludeFound = true;
  1870. IncludesInBlock.push_back(
  1871. {IncludeName, Line, Prev, Category, Priority});
  1872. } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
  1873. sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code,
  1874. Replaces, Cursor);
  1875. IncludesInBlock.clear();
  1876. FirstIncludeBlock = false;
  1877. }
  1878. Prev = Pos + 1;
  1879. }
  1880. if (Pos == StringRef::npos || Pos + 1 == Code.size())
  1881. break;
  1882. SearchFrom = Pos + 1;
  1883. }
  1884. if (!IncludesInBlock.empty()) {
  1885. sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code, Replaces,
  1886. Cursor);
  1887. }
  1888. return Replaces;
  1889. }
  1890. // Returns group number to use as a first order sort on imports. Gives UINT_MAX
  1891. // if the import does not match any given groups.
  1892. static unsigned findJavaImportGroup(const FormatStyle &Style,
  1893. StringRef ImportIdentifier) {
  1894. unsigned LongestMatchIndex = UINT_MAX;
  1895. unsigned LongestMatchLength = 0;
  1896. for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
  1897. std::string GroupPrefix = Style.JavaImportGroups[I];
  1898. if (ImportIdentifier.startswith(GroupPrefix) &&
  1899. GroupPrefix.length() > LongestMatchLength) {
  1900. LongestMatchIndex = I;
  1901. LongestMatchLength = GroupPrefix.length();
  1902. }
  1903. }
  1904. return LongestMatchIndex;
  1905. }
  1906. // Sorts and deduplicates a block of includes given by 'Imports' based on
  1907. // JavaImportGroups, then adding the necessary replacement to 'Replaces'.
  1908. // Import declarations with the same text will be deduplicated. Between each
  1909. // import group, a newline is inserted, and within each import group, a
  1910. // lexicographic sort based on ASCII value is performed.
  1911. static void sortJavaImports(const FormatStyle &Style,
  1912. const SmallVectorImpl<JavaImportDirective> &Imports,
  1913. ArrayRef<tooling::Range> Ranges, StringRef FileName,
  1914. StringRef Code, tooling::Replacements &Replaces) {
  1915. unsigned ImportsBeginOffset = Imports.front().Offset;
  1916. unsigned ImportsEndOffset =
  1917. Imports.back().Offset + Imports.back().Text.size();
  1918. unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
  1919. if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
  1920. return;
  1921. SmallVector<unsigned, 16> Indices;
  1922. SmallVector<unsigned, 16> JavaImportGroups;
  1923. for (unsigned i = 0, e = Imports.size(); i != e; ++i) {
  1924. Indices.push_back(i);
  1925. JavaImportGroups.push_back(
  1926. findJavaImportGroup(Style, Imports[i].Identifier));
  1927. }
  1928. llvm::sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
  1929. // Negating IsStatic to push static imports above non-static imports.
  1930. return std::make_tuple(!Imports[LHSI].IsStatic, JavaImportGroups[LHSI],
  1931. Imports[LHSI].Identifier) <
  1932. std::make_tuple(!Imports[RHSI].IsStatic, JavaImportGroups[RHSI],
  1933. Imports[RHSI].Identifier);
  1934. });
  1935. // Deduplicate imports.
  1936. Indices.erase(std::unique(Indices.begin(), Indices.end(),
  1937. [&](unsigned LHSI, unsigned RHSI) {
  1938. return Imports[LHSI].Text == Imports[RHSI].Text;
  1939. }),
  1940. Indices.end());
  1941. bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
  1942. unsigned CurrentImportGroup = JavaImportGroups[Indices.front()];
  1943. std::string result;
  1944. for (unsigned Index : Indices) {
  1945. if (!result.empty()) {
  1946. result += "\n";
  1947. if (CurrentIsStatic != Imports[Index].IsStatic ||
  1948. CurrentImportGroup != JavaImportGroups[Index])
  1949. result += "\n";
  1950. }
  1951. for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
  1952. result += CommentLine;
  1953. result += "\n";
  1954. }
  1955. result += Imports[Index].Text;
  1956. CurrentIsStatic = Imports[Index].IsStatic;
  1957. CurrentImportGroup = JavaImportGroups[Index];
  1958. }
  1959. // If the imports are out of order, we generate a single replacement fixing
  1960. // the entire block. Otherwise, no replacement is generated.
  1961. if (replaceCRLF(result) ==
  1962. replaceCRLF(Code.substr(Imports.front().Offset, ImportsBlockSize)))
  1963. return;
  1964. auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset,
  1965. ImportsBlockSize, result));
  1966. // FIXME: better error handling. For now, just skip the replacement for the
  1967. // release version.
  1968. if (Err) {
  1969. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  1970. assert(false);
  1971. }
  1972. }
  1973. namespace {
  1974. const char JavaImportRegexPattern[] =
  1975. "^[\t ]*import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;";
  1976. } // anonymous namespace
  1977. tooling::Replacements sortJavaImports(const FormatStyle &Style, StringRef Code,
  1978. ArrayRef<tooling::Range> Ranges,
  1979. StringRef FileName,
  1980. tooling::Replacements &Replaces) {
  1981. unsigned Prev = 0;
  1982. unsigned SearchFrom = 0;
  1983. llvm::Regex ImportRegex(JavaImportRegexPattern);
  1984. SmallVector<StringRef, 4> Matches;
  1985. SmallVector<JavaImportDirective, 16> ImportsInBlock;
  1986. std::vector<StringRef> AssociatedCommentLines;
  1987. bool FormattingOff = false;
  1988. for (;;) {
  1989. auto Pos = Code.find('\n', SearchFrom);
  1990. StringRef Line =
  1991. Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
  1992. StringRef Trimmed = Line.trim();
  1993. if (Trimmed == "// clang-format off")
  1994. FormattingOff = true;
  1995. else if (Trimmed == "// clang-format on")
  1996. FormattingOff = false;
  1997. if (ImportRegex.match(Line, &Matches)) {
  1998. if (FormattingOff) {
  1999. // If at least one import line has formatting turned off, turn off
  2000. // formatting entirely.
  2001. return Replaces;
  2002. }
  2003. StringRef Static = Matches[1];
  2004. StringRef Identifier = Matches[2];
  2005. bool IsStatic = false;
  2006. if (Static.contains("static")) {
  2007. IsStatic = true;
  2008. }
  2009. ImportsInBlock.push_back(
  2010. {Identifier, Line, Prev, AssociatedCommentLines, IsStatic});
  2011. AssociatedCommentLines.clear();
  2012. } else if (Trimmed.size() > 0 && !ImportsInBlock.empty()) {
  2013. // Associating comments within the imports with the nearest import below
  2014. AssociatedCommentLines.push_back(Line);
  2015. }
  2016. Prev = Pos + 1;
  2017. if (Pos == StringRef::npos || Pos + 1 == Code.size())
  2018. break;
  2019. SearchFrom = Pos + 1;
  2020. }
  2021. if (!ImportsInBlock.empty())
  2022. sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
  2023. return Replaces;
  2024. }
  2025. bool isMpegTS(StringRef Code) {
  2026. // MPEG transport streams use the ".ts" file extension. clang-format should
  2027. // not attempt to format those. MPEG TS' frame format starts with 0x47 every
  2028. // 189 bytes - detect that and return.
  2029. return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
  2030. }
  2031. bool isLikelyXml(StringRef Code) { return Code.ltrim().startswith("<"); }
  2032. tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
  2033. ArrayRef<tooling::Range> Ranges,
  2034. StringRef FileName, unsigned *Cursor) {
  2035. tooling::Replacements Replaces;
  2036. if (!Style.SortIncludes)
  2037. return Replaces;
  2038. if (isLikelyXml(Code))
  2039. return Replaces;
  2040. if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
  2041. isMpegTS(Code))
  2042. return Replaces;
  2043. if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
  2044. return sortJavaScriptImports(Style, Code, Ranges, FileName);
  2045. if (Style.Language == FormatStyle::LanguageKind::LK_Java)
  2046. return sortJavaImports(Style, Code, Ranges, FileName, Replaces);
  2047. sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
  2048. return Replaces;
  2049. }
  2050. template <typename T>
  2051. static llvm::Expected<tooling::Replacements>
  2052. processReplacements(T ProcessFunc, StringRef Code,
  2053. const tooling::Replacements &Replaces,
  2054. const FormatStyle &Style) {
  2055. if (Replaces.empty())
  2056. return tooling::Replacements();
  2057. auto NewCode = applyAllReplacements(Code, Replaces);
  2058. if (!NewCode)
  2059. return NewCode.takeError();
  2060. std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
  2061. StringRef FileName = Replaces.begin()->getFilePath();
  2062. tooling::Replacements FormatReplaces =
  2063. ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
  2064. return Replaces.merge(FormatReplaces);
  2065. }
  2066. llvm::Expected<tooling::Replacements>
  2067. formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
  2068. const FormatStyle &Style) {
  2069. // We need to use lambda function here since there are two versions of
  2070. // `sortIncludes`.
  2071. auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
  2072. std::vector<tooling::Range> Ranges,
  2073. StringRef FileName) -> tooling::Replacements {
  2074. return sortIncludes(Style, Code, Ranges, FileName);
  2075. };
  2076. auto SortedReplaces =
  2077. processReplacements(SortIncludes, Code, Replaces, Style);
  2078. if (!SortedReplaces)
  2079. return SortedReplaces.takeError();
  2080. // We need to use lambda function here since there are two versions of
  2081. // `reformat`.
  2082. auto Reformat = [](const FormatStyle &Style, StringRef Code,
  2083. std::vector<tooling::Range> Ranges,
  2084. StringRef FileName) -> tooling::Replacements {
  2085. return reformat(Style, Code, Ranges, FileName);
  2086. };
  2087. return processReplacements(Reformat, Code, *SortedReplaces, Style);
  2088. }
  2089. namespace {
  2090. inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
  2091. return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 &&
  2092. llvm::Regex(CppIncludeRegexPattern)
  2093. .match(Replace.getReplacementText());
  2094. }
  2095. inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
  2096. return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1;
  2097. }
  2098. // FIXME: insert empty lines between newly created blocks.
  2099. tooling::Replacements
  2100. fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
  2101. const FormatStyle &Style) {
  2102. if (!Style.isCpp())
  2103. return Replaces;
  2104. tooling::Replacements HeaderInsertions;
  2105. std::set<llvm::StringRef> HeadersToDelete;
  2106. tooling::Replacements Result;
  2107. for (const auto &R : Replaces) {
  2108. if (isHeaderInsertion(R)) {
  2109. // Replacements from \p Replaces must be conflict-free already, so we can
  2110. // simply consume the error.
  2111. llvm::consumeError(HeaderInsertions.add(R));
  2112. } else if (isHeaderDeletion(R)) {
  2113. HeadersToDelete.insert(R.getReplacementText());
  2114. } else if (R.getOffset() == UINT_MAX) {
  2115. llvm::errs() << "Insertions other than header #include insertion are "
  2116. "not supported! "
  2117. << R.getReplacementText() << "\n";
  2118. } else {
  2119. llvm::consumeError(Result.add(R));
  2120. }
  2121. }
  2122. if (HeaderInsertions.empty() && HeadersToDelete.empty())
  2123. return Replaces;
  2124. StringRef FileName = Replaces.begin()->getFilePath();
  2125. tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle);
  2126. for (const auto &Header : HeadersToDelete) {
  2127. tooling::Replacements Replaces =
  2128. Includes.remove(Header.trim("\"<>"), Header.startswith("<"));
  2129. for (const auto &R : Replaces) {
  2130. auto Err = Result.add(R);
  2131. if (Err) {
  2132. // Ignore the deletion on conflict.
  2133. llvm::errs() << "Failed to add header deletion replacement for "
  2134. << Header << ": " << llvm::toString(std::move(Err))
  2135. << "\n";
  2136. }
  2137. }
  2138. }
  2139. llvm::Regex IncludeRegex = llvm::Regex(CppIncludeRegexPattern);
  2140. llvm::SmallVector<StringRef, 4> Matches;
  2141. for (const auto &R : HeaderInsertions) {
  2142. auto IncludeDirective = R.getReplacementText();
  2143. bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
  2144. assert(Matched && "Header insertion replacement must have replacement text "
  2145. "'#include ...'");
  2146. (void)Matched;
  2147. auto IncludeName = Matches[2];
  2148. auto Replace =
  2149. Includes.insert(IncludeName.trim("\"<>"), IncludeName.startswith("<"));
  2150. if (Replace) {
  2151. auto Err = Result.add(*Replace);
  2152. if (Err) {
  2153. llvm::consumeError(std::move(Err));
  2154. unsigned NewOffset =
  2155. Result.getShiftedCodePosition(Replace->getOffset());
  2156. auto Shifted = tooling::Replacement(FileName, NewOffset, 0,
  2157. Replace->getReplacementText());
  2158. Result = Result.merge(tooling::Replacements(Shifted));
  2159. }
  2160. }
  2161. }
  2162. return Result;
  2163. }
  2164. } // anonymous namespace
  2165. llvm::Expected<tooling::Replacements>
  2166. cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
  2167. const FormatStyle &Style) {
  2168. // We need to use lambda function here since there are two versions of
  2169. // `cleanup`.
  2170. auto Cleanup = [](const FormatStyle &Style, StringRef Code,
  2171. std::vector<tooling::Range> Ranges,
  2172. StringRef FileName) -> tooling::Replacements {
  2173. return cleanup(Style, Code, Ranges, FileName);
  2174. };
  2175. // Make header insertion replacements insert new headers into correct blocks.
  2176. tooling::Replacements NewReplaces =
  2177. fixCppIncludeInsertions(Code, Replaces, Style);
  2178. return processReplacements(Cleanup, Code, NewReplaces, Style);
  2179. }
  2180. namespace internal {
  2181. std::pair<tooling::Replacements, unsigned>
  2182. reformat(const FormatStyle &Style, StringRef Code,
  2183. ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
  2184. unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
  2185. FormattingAttemptStatus *Status) {
  2186. FormatStyle Expanded = expandPresets(Style);
  2187. if (Expanded.DisableFormat)
  2188. return {tooling::Replacements(), 0};
  2189. if (isLikelyXml(Code))
  2190. return {tooling::Replacements(), 0};
  2191. if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
  2192. return {tooling::Replacements(), 0};
  2193. typedef std::function<std::pair<tooling::Replacements, unsigned>(
  2194. const Environment &)>
  2195. AnalyzerPass;
  2196. SmallVector<AnalyzerPass, 4> Passes;
  2197. if (Style.Language == FormatStyle::LK_Cpp) {
  2198. if (Style.FixNamespaceComments)
  2199. Passes.emplace_back([&](const Environment &Env) {
  2200. return NamespaceEndCommentsFixer(Env, Expanded).process();
  2201. });
  2202. if (Style.SortUsingDeclarations)
  2203. Passes.emplace_back([&](const Environment &Env) {
  2204. return UsingDeclarationsSorter(Env, Expanded).process();
  2205. });
  2206. }
  2207. if (Style.Language == FormatStyle::LK_JavaScript &&
  2208. Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
  2209. Passes.emplace_back([&](const Environment &Env) {
  2210. return JavaScriptRequoter(Env, Expanded).process();
  2211. });
  2212. Passes.emplace_back([&](const Environment &Env) {
  2213. return Formatter(Env, Expanded, Status).process();
  2214. });
  2215. auto Env =
  2216. std::make_unique<Environment>(Code, FileName, Ranges, FirstStartColumn,
  2217. NextStartColumn, LastStartColumn);
  2218. llvm::Optional<std::string> CurrentCode = None;
  2219. tooling::Replacements Fixes;
  2220. unsigned Penalty = 0;
  2221. for (size_t I = 0, E = Passes.size(); I < E; ++I) {
  2222. std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
  2223. auto NewCode = applyAllReplacements(
  2224. CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
  2225. if (NewCode) {
  2226. Fixes = Fixes.merge(PassFixes.first);
  2227. Penalty += PassFixes.second;
  2228. if (I + 1 < E) {
  2229. CurrentCode = std::move(*NewCode);
  2230. Env = std::make_unique<Environment>(
  2231. *CurrentCode, FileName,
  2232. tooling::calculateRangesAfterReplacements(Fixes, Ranges),
  2233. FirstStartColumn, NextStartColumn, LastStartColumn);
  2234. }
  2235. }
  2236. }
  2237. return {Fixes, Penalty};
  2238. }
  2239. } // namespace internal
  2240. tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
  2241. ArrayRef<tooling::Range> Ranges,
  2242. StringRef FileName,
  2243. FormattingAttemptStatus *Status) {
  2244. return internal::reformat(Style, Code, Ranges,
  2245. /*FirstStartColumn=*/0,
  2246. /*NextStartColumn=*/0,
  2247. /*LastStartColumn=*/0, FileName, Status)
  2248. .first;
  2249. }
  2250. tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
  2251. ArrayRef<tooling::Range> Ranges,
  2252. StringRef FileName) {
  2253. // cleanups only apply to C++ (they mostly concern ctor commas etc.)
  2254. if (Style.Language != FormatStyle::LK_Cpp)
  2255. return tooling::Replacements();
  2256. return Cleaner(Environment(Code, FileName, Ranges), Style).process().first;
  2257. }
  2258. tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
  2259. ArrayRef<tooling::Range> Ranges,
  2260. StringRef FileName, bool *IncompleteFormat) {
  2261. FormattingAttemptStatus Status;
  2262. auto Result = reformat(Style, Code, Ranges, FileName, &Status);
  2263. if (!Status.FormatComplete)
  2264. *IncompleteFormat = true;
  2265. return Result;
  2266. }
  2267. tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
  2268. StringRef Code,
  2269. ArrayRef<tooling::Range> Ranges,
  2270. StringRef FileName) {
  2271. return NamespaceEndCommentsFixer(Environment(Code, FileName, Ranges), Style)
  2272. .process()
  2273. .first;
  2274. }
  2275. tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
  2276. StringRef Code,
  2277. ArrayRef<tooling::Range> Ranges,
  2278. StringRef FileName) {
  2279. return UsingDeclarationsSorter(Environment(Code, FileName, Ranges), Style)
  2280. .process()
  2281. .first;
  2282. }
  2283. LangOptions getFormattingLangOpts(const FormatStyle &Style) {
  2284. LangOptions LangOpts;
  2285. FormatStyle::LanguageStandard LexingStd = Style.Standard;
  2286. if (LexingStd == FormatStyle::LS_Auto)
  2287. LexingStd = FormatStyle::LS_Latest;
  2288. if (LexingStd == FormatStyle::LS_Latest)
  2289. LexingStd = FormatStyle::LS_Cpp20;
  2290. LangOpts.CPlusPlus = 1;
  2291. LangOpts.CPlusPlus11 = LexingStd >= FormatStyle::LS_Cpp11;
  2292. LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
  2293. LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
  2294. LangOpts.CPlusPlus2a = LexingStd >= FormatStyle::LS_Cpp20;
  2295. LangOpts.LineComment = 1;
  2296. bool AlternativeOperators = Style.isCpp();
  2297. LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
  2298. LangOpts.Bool = 1;
  2299. LangOpts.ObjC = 1;
  2300. LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
  2301. LangOpts.DeclSpecKeyword = 1; // To get __declspec.
  2302. return LangOpts;
  2303. }
  2304. const char *StyleOptionHelpDescription =
  2305. "Coding style, currently supports:\n"
  2306. " LLVM, Google, Chromium, Mozilla, WebKit.\n"
  2307. "Use -style=file to load style configuration from\n"
  2308. ".clang-format file located in one of the parent\n"
  2309. "directories of the source file (or current\n"
  2310. "directory for stdin).\n"
  2311. "Use -style=\"{key: value, ...}\" to set specific\n"
  2312. "parameters, e.g.:\n"
  2313. " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
  2314. static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
  2315. if (FileName.endswith(".java"))
  2316. return FormatStyle::LK_Java;
  2317. if (FileName.endswith_lower(".js") || FileName.endswith_lower(".mjs") ||
  2318. FileName.endswith_lower(".ts"))
  2319. return FormatStyle::LK_JavaScript; // (module) JavaScript or TypeScript.
  2320. if (FileName.endswith(".m") || FileName.endswith(".mm"))
  2321. return FormatStyle::LK_ObjC;
  2322. if (FileName.endswith_lower(".proto") ||
  2323. FileName.endswith_lower(".protodevel"))
  2324. return FormatStyle::LK_Proto;
  2325. if (FileName.endswith_lower(".textpb") ||
  2326. FileName.endswith_lower(".pb.txt") ||
  2327. FileName.endswith_lower(".textproto") ||
  2328. FileName.endswith_lower(".asciipb"))
  2329. return FormatStyle::LK_TextProto;
  2330. if (FileName.endswith_lower(".td"))
  2331. return FormatStyle::LK_TableGen;
  2332. if (FileName.endswith_lower(".cs"))
  2333. return FormatStyle::LK_CSharp;
  2334. return FormatStyle::LK_Cpp;
  2335. }
  2336. FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
  2337. const auto GuessedLanguage = getLanguageByFileName(FileName);
  2338. if (GuessedLanguage == FormatStyle::LK_Cpp) {
  2339. auto Extension = llvm::sys::path::extension(FileName);
  2340. // If there's no file extension (or it's .h), we need to check the contents
  2341. // of the code to see if it contains Objective-C.
  2342. if (Extension.empty() || Extension == ".h") {
  2343. auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
  2344. Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
  2345. ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
  2346. Guesser.process();
  2347. if (Guesser.isObjC())
  2348. return FormatStyle::LK_ObjC;
  2349. }
  2350. }
  2351. return GuessedLanguage;
  2352. }
  2353. const char *DefaultFormatStyle = "file";
  2354. const char *DefaultFallbackStyle = "LLVM";
  2355. llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
  2356. StringRef FallbackStyleName,
  2357. StringRef Code,
  2358. llvm::vfs::FileSystem *FS) {
  2359. if (!FS) {
  2360. FS = llvm::vfs::getRealFileSystem().get();
  2361. }
  2362. FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
  2363. FormatStyle FallbackStyle = getNoStyle();
  2364. if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
  2365. return make_string_error("Invalid fallback style \"" + FallbackStyleName);
  2366. if (StyleName.startswith("{")) {
  2367. // Parse YAML/JSON style from the command line.
  2368. if (std::error_code ec = parseConfiguration(StyleName, &Style))
  2369. return make_string_error("Error parsing -style: " + ec.message());
  2370. return Style;
  2371. }
  2372. if (!StyleName.equals_lower("file")) {
  2373. if (!getPredefinedStyle(StyleName, Style.Language, &Style))
  2374. return make_string_error("Invalid value for -style");
  2375. return Style;
  2376. }
  2377. // Look for .clang-format/_clang-format file in the file's parent directories.
  2378. SmallString<128> UnsuitableConfigFiles;
  2379. SmallString<128> Path(FileName);
  2380. if (std::error_code EC = FS->makeAbsolute(Path))
  2381. return make_string_error(EC.message());
  2382. for (StringRef Directory = Path; !Directory.empty();
  2383. Directory = llvm::sys::path::parent_path(Directory)) {
  2384. auto Status = FS->status(Directory);
  2385. if (!Status ||
  2386. Status->getType() != llvm::sys::fs::file_type::directory_file) {
  2387. continue;
  2388. }
  2389. SmallString<128> ConfigFile(Directory);
  2390. llvm::sys::path::append(ConfigFile, ".clang-format");
  2391. LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  2392. Status = FS->status(ConfigFile.str());
  2393. bool FoundConfigFile =
  2394. Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
  2395. if (!FoundConfigFile) {
  2396. // Try _clang-format too, since dotfiles are not commonly used on Windows.
  2397. ConfigFile = Directory;
  2398. llvm::sys::path::append(ConfigFile, "_clang-format");
  2399. LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  2400. Status = FS->status(ConfigFile.str());
  2401. FoundConfigFile = Status && (Status->getType() ==
  2402. llvm::sys::fs::file_type::regular_file);
  2403. }
  2404. if (FoundConfigFile) {
  2405. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
  2406. FS->getBufferForFile(ConfigFile.str());
  2407. if (std::error_code EC = Text.getError())
  2408. return make_string_error(EC.message());
  2409. if (std::error_code ec =
  2410. parseConfiguration(Text.get()->getBuffer(), &Style)) {
  2411. if (ec == ParseError::Unsuitable) {
  2412. if (!UnsuitableConfigFiles.empty())
  2413. UnsuitableConfigFiles.append(", ");
  2414. UnsuitableConfigFiles.append(ConfigFile);
  2415. continue;
  2416. }
  2417. return make_string_error("Error reading " + ConfigFile + ": " +
  2418. ec.message());
  2419. }
  2420. LLVM_DEBUG(llvm::dbgs()
  2421. << "Using configuration file " << ConfigFile << "\n");
  2422. return Style;
  2423. }
  2424. }
  2425. if (!UnsuitableConfigFiles.empty())
  2426. return make_string_error("Configuration file(s) do(es) not support " +
  2427. getLanguageName(Style.Language) + ": " +
  2428. UnsuitableConfigFiles);
  2429. return FallbackStyle;
  2430. }
  2431. } // namespace format
  2432. } // namespace clang