Format.cpp 85 KB

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