Format.cpp 85 KB

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