Format.cpp 99 KB

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