Format.cpp 99 KB

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