Format.cpp 86 KB

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