Format.cpp 103 KB

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