Format.cpp 99 KB

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