Format.cpp 95 KB

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