Format.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  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. #define DEBUG_TYPE "format-formatter"
  16. #include "ContinuationIndenter.h"
  17. #include "TokenAnnotator.h"
  18. #include "UnwrappedLineParser.h"
  19. #include "WhitespaceManager.h"
  20. #include "clang/Basic/Diagnostic.h"
  21. #include "clang/Basic/SourceManager.h"
  22. #include "clang/Format/Format.h"
  23. #include "clang/Lex/Lexer.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/Support/Allocator.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "llvm/Support/YAMLTraits.h"
  28. #include "llvm/Support/Path.h"
  29. #include <queue>
  30. #include <string>
  31. namespace llvm {
  32. namespace yaml {
  33. template <>
  34. struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
  35. static void enumeration(IO &IO,
  36. clang::format::FormatStyle::LanguageStandard &Value) {
  37. IO.enumCase(Value, "Cpp03", clang::format::FormatStyle::LS_Cpp03);
  38. IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
  39. IO.enumCase(Value, "Cpp11", clang::format::FormatStyle::LS_Cpp11);
  40. IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
  41. IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
  42. }
  43. };
  44. template <>
  45. struct ScalarEnumerationTraits<clang::format::FormatStyle::UseTabStyle> {
  46. static void
  47. enumeration(IO &IO, clang::format::FormatStyle::UseTabStyle &Value) {
  48. IO.enumCase(Value, "Never", clang::format::FormatStyle::UT_Never);
  49. IO.enumCase(Value, "false", clang::format::FormatStyle::UT_Never);
  50. IO.enumCase(Value, "Always", clang::format::FormatStyle::UT_Always);
  51. IO.enumCase(Value, "true", clang::format::FormatStyle::UT_Always);
  52. IO.enumCase(Value, "ForIndentation",
  53. clang::format::FormatStyle::UT_ForIndentation);
  54. }
  55. };
  56. template <>
  57. struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
  58. static void
  59. enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
  60. IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
  61. IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
  62. IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
  63. IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman);
  64. }
  65. };
  66. template <>
  67. struct ScalarEnumerationTraits<
  68. clang::format::FormatStyle::NamespaceIndentationKind> {
  69. static void
  70. enumeration(IO &IO,
  71. clang::format::FormatStyle::NamespaceIndentationKind &Value) {
  72. IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None);
  73. IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner);
  74. IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All);
  75. }
  76. };
  77. template <> struct MappingTraits<clang::format::FormatStyle> {
  78. static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
  79. if (IO.outputting()) {
  80. StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
  81. "Mozilla", "WebKit" };
  82. ArrayRef<StringRef> Styles(StylesArray);
  83. for (size_t i = 0, e = Styles.size(); i < e; ++i) {
  84. StringRef StyleName(Styles[i]);
  85. clang::format::FormatStyle PredefinedStyle;
  86. if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
  87. Style == PredefinedStyle) {
  88. IO.mapOptional("# BasedOnStyle", StyleName);
  89. break;
  90. }
  91. }
  92. } else {
  93. StringRef BasedOnStyle;
  94. IO.mapOptional("BasedOnStyle", BasedOnStyle);
  95. if (!BasedOnStyle.empty())
  96. if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
  97. IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
  98. return;
  99. }
  100. }
  101. IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
  102. IO.mapOptional("ConstructorInitializerIndentWidth",
  103. Style.ConstructorInitializerIndentWidth);
  104. IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
  105. IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
  106. IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
  107. Style.AllowAllParametersOfDeclarationOnNextLine);
  108. IO.mapOptional("AllowShortIfStatementsOnASingleLine",
  109. Style.AllowShortIfStatementsOnASingleLine);
  110. IO.mapOptional("AllowShortLoopsOnASingleLine",
  111. Style.AllowShortLoopsOnASingleLine);
  112. IO.mapOptional("AlwaysBreakTemplateDeclarations",
  113. Style.AlwaysBreakTemplateDeclarations);
  114. IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
  115. Style.AlwaysBreakBeforeMultilineStrings);
  116. IO.mapOptional("BreakBeforeBinaryOperators",
  117. Style.BreakBeforeBinaryOperators);
  118. IO.mapOptional("BreakConstructorInitializersBeforeComma",
  119. Style.BreakConstructorInitializersBeforeComma);
  120. IO.mapOptional("BinPackParameters", Style.BinPackParameters);
  121. IO.mapOptional("ColumnLimit", Style.ColumnLimit);
  122. IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
  123. Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
  124. IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
  125. IO.mapOptional("ExperimentalAutoDetectBinPacking",
  126. Style.ExperimentalAutoDetectBinPacking);
  127. IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
  128. IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
  129. IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
  130. IO.mapOptional("ObjCSpaceBeforeProtocolList",
  131. Style.ObjCSpaceBeforeProtocolList);
  132. IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
  133. IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
  134. IO.mapOptional("PenaltyBreakFirstLessLess",
  135. Style.PenaltyBreakFirstLessLess);
  136. IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
  137. IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
  138. Style.PenaltyReturnTypeOnItsOwnLine);
  139. IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
  140. IO.mapOptional("SpacesBeforeTrailingComments",
  141. Style.SpacesBeforeTrailingComments);
  142. IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
  143. IO.mapOptional("Standard", Style.Standard);
  144. IO.mapOptional("IndentWidth", Style.IndentWidth);
  145. IO.mapOptional("TabWidth", Style.TabWidth);
  146. IO.mapOptional("UseTab", Style.UseTab);
  147. IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
  148. IO.mapOptional("IndentFunctionDeclarationAfterType",
  149. Style.IndentFunctionDeclarationAfterType);
  150. IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
  151. IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
  152. IO.mapOptional("SpacesInCStyleCastParentheses",
  153. Style.SpacesInCStyleCastParentheses);
  154. IO.mapOptional("SpaceAfterControlStatementKeyword",
  155. Style.SpaceAfterControlStatementKeyword);
  156. IO.mapOptional("SpaceBeforeAssignmentOperators",
  157. Style.SpaceBeforeAssignmentOperators);
  158. }
  159. };
  160. }
  161. }
  162. namespace clang {
  163. namespace format {
  164. void setDefaultPenalties(FormatStyle &Style) {
  165. Style.PenaltyBreakComment = 60;
  166. Style.PenaltyBreakFirstLessLess = 120;
  167. Style.PenaltyBreakString = 1000;
  168. Style.PenaltyExcessCharacter = 1000000;
  169. }
  170. FormatStyle getLLVMStyle() {
  171. FormatStyle LLVMStyle;
  172. LLVMStyle.AccessModifierOffset = -2;
  173. LLVMStyle.AlignEscapedNewlinesLeft = false;
  174. LLVMStyle.AlignTrailingComments = true;
  175. LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
  176. LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
  177. LLVMStyle.AllowShortLoopsOnASingleLine = false;
  178. LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
  179. LLVMStyle.AlwaysBreakTemplateDeclarations = false;
  180. LLVMStyle.BinPackParameters = true;
  181. LLVMStyle.BreakBeforeBinaryOperators = false;
  182. LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
  183. LLVMStyle.BreakConstructorInitializersBeforeComma = false;
  184. LLVMStyle.ColumnLimit = 80;
  185. LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
  186. LLVMStyle.ConstructorInitializerIndentWidth = 4;
  187. LLVMStyle.Cpp11BracedListStyle = false;
  188. LLVMStyle.DerivePointerBinding = false;
  189. LLVMStyle.ExperimentalAutoDetectBinPacking = false;
  190. LLVMStyle.IndentCaseLabels = false;
  191. LLVMStyle.IndentFunctionDeclarationAfterType = false;
  192. LLVMStyle.IndentWidth = 2;
  193. LLVMStyle.TabWidth = 8;
  194. LLVMStyle.MaxEmptyLinesToKeep = 1;
  195. LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
  196. LLVMStyle.ObjCSpaceBeforeProtocolList = true;
  197. LLVMStyle.PointerBindsToType = false;
  198. LLVMStyle.SpacesBeforeTrailingComments = 1;
  199. LLVMStyle.Standard = FormatStyle::LS_Cpp03;
  200. LLVMStyle.UseTab = FormatStyle::UT_Never;
  201. LLVMStyle.SpacesInParentheses = false;
  202. LLVMStyle.SpaceInEmptyParentheses = false;
  203. LLVMStyle.SpacesInCStyleCastParentheses = false;
  204. LLVMStyle.SpaceAfterControlStatementKeyword = true;
  205. LLVMStyle.SpaceBeforeAssignmentOperators = true;
  206. setDefaultPenalties(LLVMStyle);
  207. LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
  208. return LLVMStyle;
  209. }
  210. FormatStyle getGoogleStyle() {
  211. FormatStyle GoogleStyle;
  212. GoogleStyle.AccessModifierOffset = -1;
  213. GoogleStyle.AlignEscapedNewlinesLeft = true;
  214. GoogleStyle.AlignTrailingComments = true;
  215. GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
  216. GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
  217. GoogleStyle.AllowShortLoopsOnASingleLine = true;
  218. GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
  219. GoogleStyle.AlwaysBreakTemplateDeclarations = true;
  220. GoogleStyle.BinPackParameters = true;
  221. GoogleStyle.BreakBeforeBinaryOperators = false;
  222. GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
  223. GoogleStyle.BreakConstructorInitializersBeforeComma = false;
  224. GoogleStyle.ColumnLimit = 80;
  225. GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
  226. GoogleStyle.ConstructorInitializerIndentWidth = 4;
  227. GoogleStyle.Cpp11BracedListStyle = true;
  228. GoogleStyle.DerivePointerBinding = true;
  229. GoogleStyle.ExperimentalAutoDetectBinPacking = false;
  230. GoogleStyle.IndentCaseLabels = true;
  231. GoogleStyle.IndentFunctionDeclarationAfterType = true;
  232. GoogleStyle.IndentWidth = 2;
  233. GoogleStyle.TabWidth = 8;
  234. GoogleStyle.MaxEmptyLinesToKeep = 1;
  235. GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
  236. GoogleStyle.ObjCSpaceBeforeProtocolList = false;
  237. GoogleStyle.PointerBindsToType = true;
  238. GoogleStyle.SpacesBeforeTrailingComments = 2;
  239. GoogleStyle.Standard = FormatStyle::LS_Auto;
  240. GoogleStyle.UseTab = FormatStyle::UT_Never;
  241. GoogleStyle.SpacesInParentheses = false;
  242. GoogleStyle.SpaceInEmptyParentheses = false;
  243. GoogleStyle.SpacesInCStyleCastParentheses = false;
  244. GoogleStyle.SpaceAfterControlStatementKeyword = true;
  245. GoogleStyle.SpaceBeforeAssignmentOperators = true;
  246. setDefaultPenalties(GoogleStyle);
  247. GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  248. return GoogleStyle;
  249. }
  250. FormatStyle getChromiumStyle() {
  251. FormatStyle ChromiumStyle = getGoogleStyle();
  252. ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  253. ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
  254. ChromiumStyle.AllowShortLoopsOnASingleLine = false;
  255. ChromiumStyle.BinPackParameters = false;
  256. ChromiumStyle.DerivePointerBinding = false;
  257. ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
  258. return ChromiumStyle;
  259. }
  260. FormatStyle getMozillaStyle() {
  261. FormatStyle MozillaStyle = getLLVMStyle();
  262. MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  263. MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
  264. MozillaStyle.DerivePointerBinding = true;
  265. MozillaStyle.IndentCaseLabels = true;
  266. MozillaStyle.ObjCSpaceBeforeProtocolList = false;
  267. MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  268. MozillaStyle.PointerBindsToType = true;
  269. return MozillaStyle;
  270. }
  271. FormatStyle getWebKitStyle() {
  272. FormatStyle Style = getLLVMStyle();
  273. Style.AccessModifierOffset = -4;
  274. Style.AlignTrailingComments = false;
  275. Style.BreakBeforeBinaryOperators = true;
  276. Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
  277. Style.BreakConstructorInitializersBeforeComma = true;
  278. Style.ColumnLimit = 0;
  279. Style.IndentWidth = 4;
  280. Style.NamespaceIndentation = FormatStyle::NI_Inner;
  281. Style.PointerBindsToType = true;
  282. return Style;
  283. }
  284. bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
  285. if (Name.equals_lower("llvm"))
  286. *Style = getLLVMStyle();
  287. else if (Name.equals_lower("chromium"))
  288. *Style = getChromiumStyle();
  289. else if (Name.equals_lower("mozilla"))
  290. *Style = getMozillaStyle();
  291. else if (Name.equals_lower("google"))
  292. *Style = getGoogleStyle();
  293. else if (Name.equals_lower("webkit"))
  294. *Style = getWebKitStyle();
  295. else
  296. return false;
  297. return true;
  298. }
  299. llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
  300. if (Text.trim().empty())
  301. return llvm::make_error_code(llvm::errc::invalid_argument);
  302. llvm::yaml::Input Input(Text);
  303. Input >> *Style;
  304. return Input.error();
  305. }
  306. std::string configurationAsText(const FormatStyle &Style) {
  307. std::string Text;
  308. llvm::raw_string_ostream Stream(Text);
  309. llvm::yaml::Output Output(Stream);
  310. // We use the same mapping method for input and output, so we need a non-const
  311. // reference here.
  312. FormatStyle NonConstStyle = Style;
  313. Output << NonConstStyle;
  314. return Stream.str();
  315. }
  316. namespace {
  317. class NoColumnLimitFormatter {
  318. public:
  319. NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
  320. /// \brief Formats the line starting at \p State, simply keeping all of the
  321. /// input's line breaking decisions.
  322. void format(unsigned FirstIndent, const AnnotatedLine *Line) {
  323. LineState State =
  324. Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
  325. while (State.NextToken != NULL) {
  326. bool Newline =
  327. Indenter->mustBreak(State) ||
  328. (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
  329. Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
  330. }
  331. }
  332. private:
  333. ContinuationIndenter *Indenter;
  334. };
  335. class UnwrappedLineFormatter {
  336. public:
  337. UnwrappedLineFormatter(ContinuationIndenter *Indenter,
  338. WhitespaceManager *Whitespaces,
  339. const FormatStyle &Style, const AnnotatedLine &Line)
  340. : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), Line(Line),
  341. Count(0) {}
  342. /// \brief Formats an \c UnwrappedLine and returns the penalty.
  343. ///
  344. /// If \p DryRun is \c false, directly applies the changes.
  345. unsigned format(unsigned FirstIndent, bool DryRun = false) {
  346. LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
  347. // If the ObjC method declaration does not fit on a line, we should format
  348. // it with one arg per line.
  349. if (Line.Type == LT_ObjCMethodDecl)
  350. State.Stack.back().BreakBeforeParameter = true;
  351. // Find best solution in solution space.
  352. return analyzeSolutionSpace(State, DryRun);
  353. }
  354. private:
  355. /// \brief An edge in the solution space from \c Previous->State to \c State,
  356. /// inserting a newline dependent on the \c NewLine.
  357. struct StateNode {
  358. StateNode(const LineState &State, bool NewLine, StateNode *Previous)
  359. : State(State), NewLine(NewLine), Previous(Previous) {}
  360. LineState State;
  361. bool NewLine;
  362. StateNode *Previous;
  363. };
  364. /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
  365. ///
  366. /// In case of equal penalties, we want to prefer states that were inserted
  367. /// first. During state generation we make sure that we insert states first
  368. /// that break the line as late as possible.
  369. typedef std::pair<unsigned, unsigned> OrderedPenalty;
  370. /// \brief An item in the prioritized BFS search queue. The \c StateNode's
  371. /// \c State has the given \c OrderedPenalty.
  372. typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
  373. /// \brief The BFS queue type.
  374. typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
  375. std::greater<QueueItem> > QueueType;
  376. /// \brief Analyze the entire solution space starting from \p InitialState.
  377. ///
  378. /// This implements a variant of Dijkstra's algorithm on the graph that spans
  379. /// the solution space (\c LineStates are the nodes). The algorithm tries to
  380. /// find the shortest path (the one with lowest penalty) from \p InitialState
  381. /// to a state where all tokens are placed. Returns the penalty.
  382. ///
  383. /// If \p DryRun is \c false, directly applies the changes.
  384. unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
  385. std::set<LineState> Seen;
  386. // Insert start element into queue.
  387. StateNode *Node =
  388. new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
  389. Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
  390. ++Count;
  391. unsigned Penalty = 0;
  392. // While not empty, take first element and follow edges.
  393. while (!Queue.empty()) {
  394. Penalty = Queue.top().first.first;
  395. StateNode *Node = Queue.top().second;
  396. if (Node->State.NextToken == NULL) {
  397. DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
  398. break;
  399. }
  400. Queue.pop();
  401. // Cut off the analysis of certain solutions if the analysis gets too
  402. // complex. See description of IgnoreStackForComparison.
  403. if (Count > 10000)
  404. Node->State.IgnoreStackForComparison = true;
  405. if (!Seen.insert(Node->State).second)
  406. // State already examined with lower penalty.
  407. continue;
  408. FormatDecision LastFormat = Node->State.NextToken->Decision;
  409. if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
  410. addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
  411. if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
  412. addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
  413. }
  414. if (Queue.empty()) {
  415. // We were unable to find a solution, do nothing.
  416. // FIXME: Add diagnostic?
  417. DEBUG(llvm::dbgs() << "Could not find a solution.\n");
  418. return 0;
  419. }
  420. // Reconstruct the solution.
  421. if (!DryRun)
  422. reconstructPath(InitialState, Queue.top().second);
  423. DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
  424. DEBUG(llvm::dbgs() << "---\n");
  425. return Penalty;
  426. }
  427. void reconstructPath(LineState &State, StateNode *Current) {
  428. std::deque<StateNode *> Path;
  429. // We do not need a break before the initial token.
  430. while (Current->Previous) {
  431. Path.push_front(Current);
  432. Current = Current->Previous;
  433. }
  434. for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
  435. I != E; ++I) {
  436. unsigned Penalty = 0;
  437. formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
  438. Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
  439. DEBUG({
  440. if ((*I)->NewLine) {
  441. llvm::dbgs() << "Penalty for placing "
  442. << (*I)->Previous->State.NextToken->Tok.getName() << ": "
  443. << Penalty << "\n";
  444. }
  445. });
  446. }
  447. }
  448. /// \brief Add the following state to the analysis queue \c Queue.
  449. ///
  450. /// Assume the current state is \p PreviousNode and has been reached with a
  451. /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
  452. void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
  453. bool NewLine) {
  454. if (NewLine && !Indenter->canBreak(PreviousNode->State))
  455. return;
  456. if (!NewLine && Indenter->mustBreak(PreviousNode->State))
  457. return;
  458. StateNode *Node = new (Allocator.Allocate())
  459. StateNode(PreviousNode->State, NewLine, PreviousNode);
  460. if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
  461. return;
  462. Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
  463. Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
  464. ++Count;
  465. }
  466. /// \brief If the \p State's next token is an r_brace closing a nested block,
  467. /// format the nested block before it.
  468. ///
  469. /// Returns \c true if all children could be placed successfully and adapts
  470. /// \p Penalty as well as \p State. If \p DryRun is false, also directly
  471. /// creates changes using \c Whitespaces.
  472. ///
  473. /// The crucial idea here is that children always get formatted upon
  474. /// encountering the closing brace right after the nested block. Now, if we
  475. /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
  476. /// \c false), the entire block has to be kept on the same line (which is only
  477. /// possible if it fits on the line, only contains a single statement, etc.
  478. ///
  479. /// If \p NewLine is true, we format the nested block on separate lines, i.e.
  480. /// break after the "{", format all lines with correct indentation and the put
  481. /// the closing "}" on yet another new line.
  482. ///
  483. /// This enables us to keep the simple structure of the
  484. /// \c UnwrappedLineFormatter, where we only have two options for each token:
  485. /// break or don't break.
  486. bool formatChildren(LineState &State, bool NewLine, bool DryRun,
  487. unsigned &Penalty) {
  488. const FormatToken &LBrace = *State.NextToken->Previous;
  489. if (LBrace.isNot(tok::l_brace) || LBrace.BlockKind != BK_Block ||
  490. LBrace.Children.size() == 0)
  491. // The previous token does not open a block. Nothing to do. We don't
  492. // assert so that we can simply call this function for all tokens.
  493. return true;
  494. if (NewLine) {
  495. unsigned ParentIndent = State.Stack.back().Indent;
  496. for (SmallVector<AnnotatedLine *, 1>::const_iterator
  497. I = LBrace.Children.begin(),
  498. E = LBrace.Children.end();
  499. I != E; ++I) {
  500. unsigned Indent =
  501. ParentIndent + ((*I)->Level - Line.Level - 1) * Style.IndentWidth;
  502. if (!DryRun) {
  503. unsigned Newlines = std::min((*I)->First->NewlinesBefore,
  504. Style.MaxEmptyLinesToKeep + 1);
  505. Newlines = std::max(1u, Newlines);
  506. Whitespaces->replaceWhitespace(
  507. *(*I)->First, Newlines, (*I)->Level, /*Spaces=*/Indent,
  508. /*StartOfTokenColumn=*/Indent, Line.InPPDirective);
  509. }
  510. UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style, **I);
  511. Penalty += Formatter.format(Indent, DryRun);
  512. }
  513. return true;
  514. }
  515. if (LBrace.Children.size() > 1)
  516. return false; // Cannot merge multiple statements into a single line.
  517. // We can't put the closing "}" on a line with a trailing comment.
  518. if (LBrace.Children[0]->Last->isTrailingComment())
  519. return false;
  520. if (!DryRun) {
  521. Whitespaces->replaceWhitespace(
  522. *LBrace.Children[0]->First,
  523. /*Newlines=*/0, /*IndentLevel=*/1, /*Spaces=*/1,
  524. /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
  525. UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style,
  526. *LBrace.Children[0]);
  527. Penalty += Formatter.format(State.Column + 1, DryRun);
  528. }
  529. State.Column += 1 + LBrace.Children[0]->Last->TotalLength;
  530. return true;
  531. }
  532. ContinuationIndenter *Indenter;
  533. WhitespaceManager *Whitespaces;
  534. FormatStyle Style;
  535. const AnnotatedLine &Line;
  536. llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
  537. QueueType Queue;
  538. // Increasing count of \c StateNode items we have created. This is used
  539. // to create a deterministic order independent of the container.
  540. unsigned Count;
  541. };
  542. class FormatTokenLexer {
  543. public:
  544. FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
  545. encoding::Encoding Encoding)
  546. : FormatTok(NULL), GreaterStashed(false), Column(0),
  547. TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
  548. IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
  549. Lex.SetKeepWhitespaceMode(true);
  550. }
  551. ArrayRef<FormatToken *> lex() {
  552. assert(Tokens.empty());
  553. do {
  554. Tokens.push_back(getNextToken());
  555. maybeJoinPreviousTokens();
  556. } while (Tokens.back()->Tok.isNot(tok::eof));
  557. return Tokens;
  558. }
  559. IdentifierTable &getIdentTable() { return IdentTable; }
  560. private:
  561. void maybeJoinPreviousTokens() {
  562. if (Tokens.size() < 4)
  563. return;
  564. FormatToken *Last = Tokens.back();
  565. if (!Last->is(tok::r_paren))
  566. return;
  567. FormatToken *String = Tokens[Tokens.size() - 2];
  568. if (!String->is(tok::string_literal) || String->IsMultiline)
  569. return;
  570. if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
  571. return;
  572. FormatToken *Macro = Tokens[Tokens.size() - 4];
  573. if (Macro->TokenText != "_T")
  574. return;
  575. const char *Start = Macro->TokenText.data();
  576. const char *End = Last->TokenText.data() + Last->TokenText.size();
  577. String->TokenText = StringRef(Start, End - Start);
  578. String->IsFirst = Macro->IsFirst;
  579. String->LastNewlineOffset = Macro->LastNewlineOffset;
  580. String->WhitespaceRange = Macro->WhitespaceRange;
  581. String->OriginalColumn = Macro->OriginalColumn;
  582. String->ColumnWidth = encoding::columnWidthWithTabs(
  583. String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
  584. Tokens.pop_back();
  585. Tokens.pop_back();
  586. Tokens.pop_back();
  587. Tokens.back() = String;
  588. }
  589. FormatToken *getNextToken() {
  590. if (GreaterStashed) {
  591. // Create a synthesized second '>' token.
  592. // FIXME: Increment Column and set OriginalColumn.
  593. Token Greater = FormatTok->Tok;
  594. FormatTok = new (Allocator.Allocate()) FormatToken;
  595. FormatTok->Tok = Greater;
  596. SourceLocation GreaterLocation =
  597. FormatTok->Tok.getLocation().getLocWithOffset(1);
  598. FormatTok->WhitespaceRange =
  599. SourceRange(GreaterLocation, GreaterLocation);
  600. FormatTok->TokenText = ">";
  601. FormatTok->ColumnWidth = 1;
  602. GreaterStashed = false;
  603. return FormatTok;
  604. }
  605. FormatTok = new (Allocator.Allocate()) FormatToken;
  606. readRawToken(*FormatTok);
  607. SourceLocation WhitespaceStart =
  608. FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
  609. if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
  610. FormatTok->IsFirst = true;
  611. // Consume and record whitespace until we find a significant token.
  612. unsigned WhitespaceLength = TrailingWhitespace;
  613. while (FormatTok->Tok.is(tok::unknown)) {
  614. for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
  615. switch (FormatTok->TokenText[i]) {
  616. case '\n':
  617. ++FormatTok->NewlinesBefore;
  618. // FIXME: This is technically incorrect, as it could also
  619. // be a literal backslash at the end of the line.
  620. if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
  621. (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
  622. FormatTok->TokenText[i - 2] != '\\')))
  623. FormatTok->HasUnescapedNewline = true;
  624. FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
  625. Column = 0;
  626. break;
  627. case '\r':
  628. case '\f':
  629. case '\v':
  630. Column = 0;
  631. break;
  632. case ' ':
  633. ++Column;
  634. break;
  635. case '\t':
  636. Column += Style.TabWidth - Column % Style.TabWidth;
  637. break;
  638. case '\\':
  639. ++Column;
  640. if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
  641. FormatTok->TokenText[i + 1] != '\n'))
  642. FormatTok->Type = TT_ImplicitStringLiteral;
  643. break;
  644. default:
  645. FormatTok->Type = TT_ImplicitStringLiteral;
  646. ++Column;
  647. break;
  648. }
  649. }
  650. if (FormatTok->Type == TT_ImplicitStringLiteral)
  651. break;
  652. WhitespaceLength += FormatTok->Tok.getLength();
  653. readRawToken(*FormatTok);
  654. }
  655. // In case the token starts with escaped newlines, we want to
  656. // take them into account as whitespace - this pattern is quite frequent
  657. // in macro definitions.
  658. // FIXME: Add a more explicit test.
  659. while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
  660. FormatTok->TokenText[1] == '\n') {
  661. // FIXME: ++FormatTok->NewlinesBefore is missing...
  662. WhitespaceLength += 2;
  663. Column = 0;
  664. FormatTok->TokenText = FormatTok->TokenText.substr(2);
  665. }
  666. FormatTok->WhitespaceRange = SourceRange(
  667. WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
  668. FormatTok->OriginalColumn = Column;
  669. TrailingWhitespace = 0;
  670. if (FormatTok->Tok.is(tok::comment)) {
  671. // FIXME: Add the trimmed whitespace to Column.
  672. StringRef UntrimmedText = FormatTok->TokenText;
  673. FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
  674. TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
  675. } else if (FormatTok->Tok.is(tok::raw_identifier)) {
  676. IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
  677. FormatTok->Tok.setIdentifierInfo(&Info);
  678. FormatTok->Tok.setKind(Info.getTokenID());
  679. } else if (FormatTok->Tok.is(tok::greatergreater)) {
  680. FormatTok->Tok.setKind(tok::greater);
  681. FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
  682. GreaterStashed = true;
  683. }
  684. // Now FormatTok is the next non-whitespace token.
  685. StringRef Text = FormatTok->TokenText;
  686. size_t FirstNewlinePos = Text.find('\n');
  687. if (FirstNewlinePos == StringRef::npos) {
  688. // FIXME: ColumnWidth actually depends on the start column, we need to
  689. // take this into account when the token is moved.
  690. FormatTok->ColumnWidth =
  691. encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
  692. Column += FormatTok->ColumnWidth;
  693. } else {
  694. FormatTok->IsMultiline = true;
  695. // FIXME: ColumnWidth actually depends on the start column, we need to
  696. // take this into account when the token is moved.
  697. FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
  698. Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
  699. // The last line of the token always starts in column 0.
  700. // Thus, the length can be precomputed even in the presence of tabs.
  701. FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
  702. Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
  703. Encoding);
  704. Column = FormatTok->LastLineColumnWidth;
  705. }
  706. return FormatTok;
  707. }
  708. FormatToken *FormatTok;
  709. bool GreaterStashed;
  710. unsigned Column;
  711. unsigned TrailingWhitespace;
  712. Lexer &Lex;
  713. SourceManager &SourceMgr;
  714. FormatStyle &Style;
  715. IdentifierTable IdentTable;
  716. encoding::Encoding Encoding;
  717. llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
  718. SmallVector<FormatToken *, 16> Tokens;
  719. void readRawToken(FormatToken &Tok) {
  720. Lex.LexFromRawLexer(Tok.Tok);
  721. Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
  722. Tok.Tok.getLength());
  723. // For formatting, treat unterminated string literals like normal string
  724. // literals.
  725. if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
  726. Tok.TokenText[0] == '"') {
  727. Tok.Tok.setKind(tok::string_literal);
  728. Tok.IsUnterminatedLiteral = true;
  729. }
  730. }
  731. };
  732. class Formatter : public UnwrappedLineConsumer {
  733. public:
  734. Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
  735. const std::vector<CharSourceRange> &Ranges)
  736. : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
  737. Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
  738. Ranges(Ranges), UnwrappedLines(1),
  739. Encoding(encoding::detectEncoding(Lex.getBuffer())) {
  740. DEBUG(llvm::dbgs() << "File encoding: "
  741. << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
  742. : "unknown")
  743. << "\n");
  744. }
  745. tooling::Replacements format() {
  746. tooling::Replacements Result;
  747. FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
  748. UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
  749. bool StructuralError = Parser.parse();
  750. assert(UnwrappedLines.rbegin()->empty());
  751. for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
  752. ++Run) {
  753. DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
  754. SmallVector<AnnotatedLine *, 16> AnnotatedLines;
  755. for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
  756. AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
  757. }
  758. tooling::Replacements RunResult =
  759. format(AnnotatedLines, StructuralError, Tokens);
  760. DEBUG({
  761. llvm::dbgs() << "Replacements for run " << Run << ":\n";
  762. for (tooling::Replacements::iterator I = RunResult.begin(),
  763. E = RunResult.end();
  764. I != E; ++I) {
  765. llvm::dbgs() << I->toString() << "\n";
  766. }
  767. });
  768. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  769. delete AnnotatedLines[i];
  770. }
  771. Result.insert(RunResult.begin(), RunResult.end());
  772. Whitespaces.reset();
  773. }
  774. return Result;
  775. }
  776. tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  777. bool StructuralError, FormatTokenLexer &Tokens) {
  778. TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
  779. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  780. Annotator.annotate(*AnnotatedLines[i]);
  781. }
  782. deriveLocalStyle(AnnotatedLines);
  783. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  784. Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
  785. }
  786. Annotator.setCommentLineLevels(AnnotatedLines);
  787. std::vector<int> IndentForLevel;
  788. bool PreviousLineWasTouched = false;
  789. const AnnotatedLine *PreviousLine = NULL;
  790. bool FormatPPDirective = false;
  791. for (SmallVectorImpl<AnnotatedLine *>::iterator I = AnnotatedLines.begin(),
  792. E = AnnotatedLines.end();
  793. I != E; ++I) {
  794. const AnnotatedLine &TheLine = **I;
  795. const FormatToken *FirstTok = TheLine.First;
  796. int Offset = getIndentOffset(*TheLine.First);
  797. // Check whether this line is part of a formatted preprocessor directive.
  798. if (FirstTok->HasUnescapedNewline)
  799. FormatPPDirective = false;
  800. if (!FormatPPDirective && TheLine.InPPDirective &&
  801. (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
  802. FormatPPDirective = true;
  803. // Determine indent and try to merge multiple unwrapped lines.
  804. while (IndentForLevel.size() <= TheLine.Level)
  805. IndentForLevel.push_back(-1);
  806. IndentForLevel.resize(TheLine.Level + 1);
  807. unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
  808. if (static_cast<int>(Indent) + Offset >= 0)
  809. Indent += Offset;
  810. tryFitMultipleLinesInOne(Indent, I, E);
  811. bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
  812. if (TheLine.First->is(tok::eof)) {
  813. if (PreviousLineWasTouched) {
  814. unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
  815. Whitespaces.replaceWhitespace(*TheLine.First, NewLines,
  816. /*IndentLevel=*/0, /*Spaces=*/0,
  817. /*TargetColumn=*/0);
  818. }
  819. } else if (TheLine.Type != LT_Invalid &&
  820. (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
  821. unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
  822. if (FirstTok->WhitespaceRange.isValid() &&
  823. // Insert a break even if there is a structural error in case where
  824. // we break apart a line consisting of multiple unwrapped lines.
  825. (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
  826. formatFirstToken(*TheLine.First, PreviousLine, Indent,
  827. TheLine.InPPDirective);
  828. } else {
  829. Indent = LevelIndent = FirstTok->OriginalColumn;
  830. }
  831. ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
  832. BinPackInconclusiveFunctions);
  833. // If everything fits on a single line, just put it there.
  834. unsigned ColumnLimit = Style.ColumnLimit;
  835. AnnotatedLine *NextLine = *(I + 1);
  836. if ((I + 1) != E && NextLine->InPPDirective &&
  837. !NextLine->First->HasUnescapedNewline)
  838. ColumnLimit = getColumnLimit(TheLine.InPPDirective);
  839. if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
  840. LineState State =
  841. Indenter.getInitialState(Indent, &TheLine, /*DryRun=*/false);
  842. while (State.NextToken != NULL)
  843. Indenter.addTokenToState(State, false, false);
  844. } else if (Style.ColumnLimit == 0) {
  845. NoColumnLimitFormatter Formatter(&Indenter);
  846. Formatter.format(Indent, &TheLine);
  847. } else {
  848. UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style,
  849. TheLine);
  850. Formatter.format(Indent);
  851. }
  852. IndentForLevel[TheLine.Level] = LevelIndent;
  853. PreviousLineWasTouched = true;
  854. } else {
  855. // Format the first token if necessary, and notify the WhitespaceManager
  856. // about the unchanged whitespace.
  857. for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
  858. if (Tok == TheLine.First &&
  859. (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
  860. unsigned LevelIndent = Tok->OriginalColumn;
  861. // Remove trailing whitespace of the previous line if it was
  862. // touched.
  863. if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
  864. formatFirstToken(*Tok, PreviousLine, LevelIndent,
  865. TheLine.InPPDirective);
  866. } else {
  867. Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
  868. }
  869. if (static_cast<int>(LevelIndent) - Offset >= 0)
  870. LevelIndent -= Offset;
  871. if (Tok->isNot(tok::comment))
  872. IndentForLevel[TheLine.Level] = LevelIndent;
  873. } else {
  874. Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
  875. }
  876. }
  877. // If we did not reformat this unwrapped line, the column at the end of
  878. // the last token is unchanged - thus, we can calculate the end of the
  879. // last token.
  880. PreviousLineWasTouched = false;
  881. }
  882. for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) {
  883. Tok->Finalized = true;
  884. }
  885. PreviousLine = *I;
  886. }
  887. return Whitespaces.generateReplacements();
  888. }
  889. private:
  890. static bool inputUsesCRLF(StringRef Text) {
  891. return Text.count('\r') * 2 > Text.count('\n');
  892. }
  893. void
  894. deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  895. unsigned CountBoundToVariable = 0;
  896. unsigned CountBoundToType = 0;
  897. bool HasCpp03IncompatibleFormat = false;
  898. bool HasBinPackedFunction = false;
  899. bool HasOnePerLineFunction = false;
  900. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  901. if (!AnnotatedLines[i]->First->Next)
  902. continue;
  903. FormatToken *Tok = AnnotatedLines[i]->First->Next;
  904. while (Tok->Next) {
  905. if (Tok->Type == TT_PointerOrReference) {
  906. bool SpacesBefore =
  907. Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
  908. bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
  909. Tok->Next->WhitespaceRange.getEnd();
  910. if (SpacesBefore && !SpacesAfter)
  911. ++CountBoundToVariable;
  912. else if (!SpacesBefore && SpacesAfter)
  913. ++CountBoundToType;
  914. }
  915. if (Tok->Type == TT_TemplateCloser &&
  916. Tok->Previous->Type == TT_TemplateCloser &&
  917. Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
  918. HasCpp03IncompatibleFormat = true;
  919. if (Tok->PackingKind == PPK_BinPacked)
  920. HasBinPackedFunction = true;
  921. if (Tok->PackingKind == PPK_OnePerLine)
  922. HasOnePerLineFunction = true;
  923. Tok = Tok->Next;
  924. }
  925. }
  926. if (Style.DerivePointerBinding) {
  927. if (CountBoundToType > CountBoundToVariable)
  928. Style.PointerBindsToType = true;
  929. else if (CountBoundToType < CountBoundToVariable)
  930. Style.PointerBindsToType = false;
  931. }
  932. if (Style.Standard == FormatStyle::LS_Auto) {
  933. Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
  934. : FormatStyle::LS_Cpp03;
  935. }
  936. BinPackInconclusiveFunctions =
  937. HasBinPackedFunction || !HasOnePerLineFunction;
  938. }
  939. /// \brief Get the indent of \p Level from \p IndentForLevel.
  940. ///
  941. /// \p IndentForLevel must contain the indent for the level \c l
  942. /// at \p IndentForLevel[l], or a value < 0 if the indent for
  943. /// that level is unknown.
  944. unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
  945. if (IndentForLevel[Level] != -1)
  946. return IndentForLevel[Level];
  947. if (Level == 0)
  948. return 0;
  949. return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
  950. }
  951. /// \brief Get the offset of the line relatively to the level.
  952. ///
  953. /// For example, 'public:' labels in classes are offset by 1 or 2
  954. /// characters to the left from their level.
  955. int getIndentOffset(const FormatToken &RootToken) {
  956. if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
  957. return Style.AccessModifierOffset;
  958. return 0;
  959. }
  960. /// \brief Tries to merge lines into one.
  961. ///
  962. /// This will change \c Line and \c AnnotatedLine to contain the merged line,
  963. /// if possible; note that \c I will be incremented when lines are merged.
  964. void tryFitMultipleLinesInOne(unsigned Indent,
  965. SmallVectorImpl<AnnotatedLine *>::iterator &I,
  966. SmallVectorImpl<AnnotatedLine *>::iterator E) {
  967. // We can never merge stuff if there are trailing line comments.
  968. AnnotatedLine *TheLine = *I;
  969. if (TheLine->Last->Type == TT_LineComment)
  970. return;
  971. if (Indent > Style.ColumnLimit)
  972. return;
  973. unsigned Limit = Style.ColumnLimit - Indent;
  974. // If we already exceed the column limit, we set 'Limit' to 0. The different
  975. // tryMerge..() functions can then decide whether to still do merging.
  976. Limit = TheLine->Last->TotalLength > Limit
  977. ? 0
  978. : Limit - TheLine->Last->TotalLength;
  979. if (I + 1 == E || (*(I + 1))->Type == LT_Invalid)
  980. return;
  981. if (TheLine->Last->is(tok::l_brace)) {
  982. tryMergeSimpleBlock(I, E, Limit);
  983. } else if (Style.AllowShortIfStatementsOnASingleLine &&
  984. TheLine->First->is(tok::kw_if)) {
  985. tryMergeSimpleControlStatement(I, E, Limit);
  986. } else if (Style.AllowShortLoopsOnASingleLine &&
  987. TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
  988. tryMergeSimpleControlStatement(I, E, Limit);
  989. } else if (TheLine->InPPDirective && (TheLine->First->HasUnescapedNewline ||
  990. TheLine->First->IsFirst)) {
  991. tryMergeSimplePPDirective(I, E, Limit);
  992. }
  993. }
  994. void tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::iterator &I,
  995. SmallVectorImpl<AnnotatedLine *>::iterator E,
  996. unsigned Limit) {
  997. if (Limit == 0)
  998. return;
  999. AnnotatedLine &Line = **I;
  1000. if (!(*(I + 1))->InPPDirective || (*(I + 1))->First->HasUnescapedNewline)
  1001. return;
  1002. if (I + 2 != E && (*(I + 2))->InPPDirective &&
  1003. !(*(I + 2))->First->HasUnescapedNewline)
  1004. return;
  1005. if (1 + (*(I + 1))->Last->TotalLength > Limit)
  1006. return;
  1007. join(Line, **(++I));
  1008. }
  1009. void
  1010. tryMergeSimpleControlStatement(SmallVectorImpl<AnnotatedLine *>::iterator &I,
  1011. SmallVectorImpl<AnnotatedLine *>::iterator E,
  1012. unsigned Limit) {
  1013. if (Limit == 0)
  1014. return;
  1015. if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
  1016. (*(I + 1))->First->is(tok::l_brace))
  1017. return;
  1018. if ((*(I + 1))->InPPDirective != (*I)->InPPDirective ||
  1019. ((*(I + 1))->InPPDirective && (*(I + 1))->First->HasUnescapedNewline))
  1020. return;
  1021. AnnotatedLine &Line = **I;
  1022. if (Line.Last->isNot(tok::r_paren))
  1023. return;
  1024. if (1 + (*(I + 1))->Last->TotalLength > Limit)
  1025. return;
  1026. if ((*(I + 1))->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
  1027. tok::kw_while) ||
  1028. (*(I + 1))->First->Type == TT_LineComment)
  1029. return;
  1030. // Only inline simple if's (no nested if or else).
  1031. if (I + 2 != E && Line.First->is(tok::kw_if) &&
  1032. (*(I + 2))->First->is(tok::kw_else))
  1033. return;
  1034. join(Line, **(++I));
  1035. }
  1036. void tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::iterator &I,
  1037. SmallVectorImpl<AnnotatedLine *>::iterator E,
  1038. unsigned Limit) {
  1039. // No merging if the brace already is on the next line.
  1040. if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
  1041. return;
  1042. // First, check that the current line allows merging. This is the case if
  1043. // we're not in a control flow statement and the last token is an opening
  1044. // brace.
  1045. AnnotatedLine &Line = **I;
  1046. if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
  1047. tok::kw_else, tok::kw_try, tok::kw_catch,
  1048. tok::kw_for,
  1049. // This gets rid of all ObjC @ keywords and methods.
  1050. tok::at, tok::minus, tok::plus))
  1051. return;
  1052. FormatToken *Tok = (*(I + 1))->First;
  1053. if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
  1054. (Tok->getNextNonComment() == NULL ||
  1055. Tok->getNextNonComment()->is(tok::semi))) {
  1056. // We merge empty blocks even if the line exceeds the column limit.
  1057. Tok->SpacesRequiredBefore = 0;
  1058. Tok->CanBreakBefore = true;
  1059. join(Line, **(I + 1));
  1060. I += 1;
  1061. } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
  1062. // Check that we still have three lines and they fit into the limit.
  1063. if (I + 2 == E || (*(I + 2))->Type == LT_Invalid ||
  1064. !nextTwoLinesFitInto(I, Limit))
  1065. return;
  1066. // Second, check that the next line does not contain any braces - if it
  1067. // does, readability declines when putting it into a single line.
  1068. if ((*(I + 1))->Last->Type == TT_LineComment || Tok->MustBreakBefore)
  1069. return;
  1070. do {
  1071. if (Tok->isOneOf(tok::l_brace, tok::r_brace))
  1072. return;
  1073. Tok = Tok->Next;
  1074. } while (Tok != NULL);
  1075. // Last, check that the third line contains a single closing brace.
  1076. Tok = (*(I + 2))->First;
  1077. if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
  1078. Tok->MustBreakBefore)
  1079. return;
  1080. join(Line, **(I + 1));
  1081. join(Line, **(I + 2));
  1082. I += 2;
  1083. }
  1084. }
  1085. bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::iterator I,
  1086. unsigned Limit) {
  1087. return 1 + (*(I + 1))->Last->TotalLength + 1 +
  1088. (*(I + 2))->Last->TotalLength <=
  1089. Limit;
  1090. }
  1091. void join(AnnotatedLine &A, const AnnotatedLine &B) {
  1092. assert(!A.Last->Next);
  1093. assert(!B.First->Previous);
  1094. A.Last->Next = B.First;
  1095. B.First->Previous = A.Last;
  1096. unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
  1097. for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
  1098. Tok->TotalLength += LengthA;
  1099. A.Last = Tok;
  1100. }
  1101. }
  1102. bool touchesRanges(const CharSourceRange &Range) {
  1103. for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
  1104. if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
  1105. Ranges[i].getBegin()) &&
  1106. !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
  1107. Range.getBegin()))
  1108. return true;
  1109. }
  1110. return false;
  1111. }
  1112. bool touchesLine(const AnnotatedLine &TheLine) {
  1113. const FormatToken *First = TheLine.First;
  1114. const FormatToken *Last = TheLine.Last;
  1115. CharSourceRange LineRange = CharSourceRange::getCharRange(
  1116. First->WhitespaceRange.getBegin().getLocWithOffset(
  1117. First->LastNewlineOffset),
  1118. Last->getStartOfNonWhitespace().getLocWithOffset(
  1119. Last->TokenText.size() - 1));
  1120. return touchesRanges(LineRange);
  1121. }
  1122. bool touchesPPDirective(SmallVectorImpl<AnnotatedLine *>::iterator I,
  1123. SmallVectorImpl<AnnotatedLine *>::iterator E) {
  1124. for (; I != E; ++I) {
  1125. if ((*I)->First->HasUnescapedNewline)
  1126. return false;
  1127. if (touchesLine(**I))
  1128. return true;
  1129. }
  1130. return false;
  1131. }
  1132. bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
  1133. const FormatToken *First = TheLine.First;
  1134. CharSourceRange LineRange = CharSourceRange::getCharRange(
  1135. First->WhitespaceRange.getBegin(),
  1136. First->WhitespaceRange.getBegin().getLocWithOffset(
  1137. First->LastNewlineOffset));
  1138. return touchesRanges(LineRange);
  1139. }
  1140. virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
  1141. assert(!UnwrappedLines.empty());
  1142. UnwrappedLines.back().push_back(TheLine);
  1143. }
  1144. virtual void finishRun() {
  1145. UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
  1146. }
  1147. /// \brief Add a new line and the required indent before the first Token
  1148. /// of the \c UnwrappedLine if there was no structural parsing error.
  1149. /// Returns the indent level of the \c UnwrappedLine.
  1150. void formatFirstToken(FormatToken &RootToken,
  1151. const AnnotatedLine *PreviousLine, unsigned Indent,
  1152. bool InPPDirective) {
  1153. unsigned Newlines =
  1154. std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
  1155. // Remove empty lines before "}" where applicable.
  1156. if (RootToken.is(tok::r_brace) &&
  1157. (!RootToken.Next ||
  1158. (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
  1159. Newlines = std::min(Newlines, 1u);
  1160. if (Newlines == 0 && !RootToken.IsFirst)
  1161. Newlines = 1;
  1162. // Insert extra new line before access specifiers.
  1163. if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
  1164. RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
  1165. ++Newlines;
  1166. // Remove empty lines after access specifiers.
  1167. if (PreviousLine && PreviousLine->First->isAccessSpecifier())
  1168. Newlines = std::min(1u, Newlines);
  1169. Whitespaces.replaceWhitespace(
  1170. RootToken, Newlines, Indent / Style.IndentWidth, Indent, Indent,
  1171. InPPDirective && !RootToken.HasUnescapedNewline);
  1172. }
  1173. unsigned getColumnLimit(bool InPPDirective) const {
  1174. // In preprocessor directives reserve two chars for trailing " \"
  1175. return Style.ColumnLimit - (InPPDirective ? 2 : 0);
  1176. }
  1177. FormatStyle Style;
  1178. Lexer &Lex;
  1179. SourceManager &SourceMgr;
  1180. WhitespaceManager Whitespaces;
  1181. std::vector<CharSourceRange> Ranges;
  1182. SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
  1183. encoding::Encoding Encoding;
  1184. bool BinPackInconclusiveFunctions;
  1185. };
  1186. } // end anonymous namespace
  1187. tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
  1188. SourceManager &SourceMgr,
  1189. std::vector<CharSourceRange> Ranges) {
  1190. Formatter formatter(Style, Lex, SourceMgr, Ranges);
  1191. return formatter.format();
  1192. }
  1193. tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
  1194. std::vector<tooling::Range> Ranges,
  1195. StringRef FileName) {
  1196. FileManager Files((FileSystemOptions()));
  1197. DiagnosticsEngine Diagnostics(
  1198. IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
  1199. new DiagnosticOptions);
  1200. SourceManager SourceMgr(Diagnostics, Files);
  1201. llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
  1202. const clang::FileEntry *Entry =
  1203. Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
  1204. SourceMgr.overrideFileContents(Entry, Buf);
  1205. FileID ID =
  1206. SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
  1207. Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
  1208. getFormattingLangOpts(Style.Standard));
  1209. SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
  1210. std::vector<CharSourceRange> CharRanges;
  1211. for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
  1212. SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
  1213. SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
  1214. CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
  1215. }
  1216. return reformat(Style, Lex, SourceMgr, CharRanges);
  1217. }
  1218. LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
  1219. LangOptions LangOpts;
  1220. LangOpts.CPlusPlus = 1;
  1221. LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
  1222. LangOpts.LineComment = 1;
  1223. LangOpts.Bool = 1;
  1224. LangOpts.ObjC1 = 1;
  1225. LangOpts.ObjC2 = 1;
  1226. return LangOpts;
  1227. }
  1228. const char *StyleOptionHelpDescription =
  1229. "Coding style, currently supports:\n"
  1230. " LLVM, Google, Chromium, Mozilla, WebKit.\n"
  1231. "Use -style=file to load style configuration from\n"
  1232. ".clang-format file located in one of the parent\n"
  1233. "directories of the source file (or current\n"
  1234. "directory for stdin).\n"
  1235. "Use -style=\"{key: value, ...}\" to set specific\n"
  1236. "parameters, e.g.:\n"
  1237. " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
  1238. FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
  1239. // Fallback style in case the rest of this function can't determine a style.
  1240. StringRef FallbackStyle = "LLVM";
  1241. FormatStyle Style;
  1242. getPredefinedStyle(FallbackStyle, &Style);
  1243. if (StyleName.startswith("{")) {
  1244. // Parse YAML/JSON style from the command line.
  1245. if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) {
  1246. llvm::errs() << "Error parsing -style: " << ec.message()
  1247. << ", using " << FallbackStyle << " style\n";
  1248. }
  1249. return Style;
  1250. }
  1251. if (!StyleName.equals_lower("file")) {
  1252. if (!getPredefinedStyle(StyleName, &Style))
  1253. llvm::errs() << "Invalid value for -style, using " << FallbackStyle
  1254. << " style\n";
  1255. return Style;
  1256. }
  1257. SmallString<128> Path(FileName);
  1258. llvm::sys::fs::make_absolute(Path);
  1259. for (StringRef Directory = Path;
  1260. !Directory.empty();
  1261. Directory = llvm::sys::path::parent_path(Directory)) {
  1262. if (!llvm::sys::fs::is_directory(Directory))
  1263. continue;
  1264. SmallString<128> ConfigFile(Directory);
  1265. llvm::sys::path::append(ConfigFile, ".clang-format");
  1266. DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  1267. bool IsFile = false;
  1268. // Ignore errors from is_regular_file: we only need to know if we can read
  1269. // the file or not.
  1270. llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
  1271. if (!IsFile) {
  1272. // Try _clang-format too, since dotfiles are not commonly used on Windows.
  1273. ConfigFile = Directory;
  1274. llvm::sys::path::append(ConfigFile, "_clang-format");
  1275. DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  1276. llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
  1277. }
  1278. if (IsFile) {
  1279. OwningPtr<llvm::MemoryBuffer> Text;
  1280. if (llvm::error_code ec = llvm::MemoryBuffer::getFile(ConfigFile, Text)) {
  1281. llvm::errs() << ec.message() << "\n";
  1282. continue;
  1283. }
  1284. if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
  1285. llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
  1286. << "\n";
  1287. continue;
  1288. }
  1289. DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
  1290. return Style;
  1291. }
  1292. }
  1293. llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
  1294. << " style\n";
  1295. return Style;
  1296. }
  1297. } // namespace format
  1298. } // namespace clang