Format.cpp 100 KB

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