Format.cpp 95 KB

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