Format.cpp 94 KB

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