Format.cpp 105 KB

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