Format.cpp 95 KB

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