blob: 08ea8e97de5db9996123bb54c9850efc139ff4ca [file] [log] [blame]
Daniel Jasperbac016b2012-12-03 18:12:45 +00001//===--- 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///
Daniel Jasperbac016b2012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimekca547db2013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper32d28ee2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000020#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000026#include "llvm/Support/Debug.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000027#include <string>
28
Manuel Klimekca547db2013-01-16 14:55:28 +000029// Uncomment to get debug output from tests:
30// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
31
Daniel Jasperbac016b2012-12-03 18:12:45 +000032namespace clang {
33namespace format {
34
Daniel Jasperbac016b2012-12-03 18:12:45 +000035FormatStyle getLLVMStyle() {
36 FormatStyle LLVMStyle;
37 LLVMStyle.ColumnLimit = 80;
38 LLVMStyle.MaxEmptyLinesToKeep = 1;
39 LLVMStyle.PointerAndReferenceBindToType = false;
40 LLVMStyle.AccessModifierOffset = -2;
41 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +000042 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000043 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper0df6acd2013-01-16 14:59:02 +000044 LLVMStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000045 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd75ff642013-01-28 15:40:20 +000046 LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000047 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000048 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000049 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000050 return LLVMStyle;
51}
52
53FormatStyle getGoogleStyle() {
54 FormatStyle GoogleStyle;
55 GoogleStyle.ColumnLimit = 80;
56 GoogleStyle.MaxEmptyLinesToKeep = 1;
57 GoogleStyle.PointerAndReferenceBindToType = true;
58 GoogleStyle.AccessModifierOffset = -1;
59 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +000060 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000061 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper0df6acd2013-01-16 14:59:02 +000062 GoogleStyle.BinPackParameters = false;
Daniel Jasperf1579602013-01-29 16:03:49 +000063 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd75ff642013-01-28 15:40:20 +000064 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000065 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperdf3736a2013-01-16 15:44:34 +000066 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000067 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000068 return GoogleStyle;
69}
70
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000071FormatStyle getChromiumStyle() {
72 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +000073 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperf40fb4b2013-01-29 15:19:38 +000074 ChromiumStyle.SplitTemplateClosingGreater = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000075 return ChromiumStyle;
76}
77
Daniel Jasperbac016b2012-12-03 18:12:45 +000078struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +000079 unsigned PenaltyIndentLevel;
Daniel Jasperceb99ab2013-01-09 10:16:05 +000080 unsigned PenaltyExcessCharacter;
Daniel Jasperbac016b2012-12-03 18:12:45 +000081};
82
Daniel Jasperdcc2a622013-01-18 08:44:07 +000083/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek3f8c7f32013-01-10 18:45:26 +000084///
Daniel Jasperdcc2a622013-01-18 08:44:07 +000085/// This includes special handling for certain constructs, e.g. the alignment of
86/// trailing line comments.
87class WhitespaceManager {
88public:
89 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
90
91 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
92 /// each \c AnnotatedToken.
93 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
94 unsigned Spaces, unsigned WhitespaceStartColumn,
95 const FormatStyle &Style) {
Daniel Jasper821627e2013-01-21 22:49:20 +000096 // 2+ newlines mean an empty line separating logic scopes.
97 if (NewLines >= 2)
98 alignComments();
99
100 // Align line comments if they are trailing or if they continue other
101 // trailing comments.
102 if (Tok.Type == TT_LineComment &&
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000103 (Tok.Parent != NULL || !Comments.empty())) {
104 if (Style.ColumnLimit >=
105 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
106 Comments.push_back(StoredComment());
107 Comments.back().Tok = Tok.FormatTok;
108 Comments.back().Spaces = Spaces;
109 Comments.back().NewLines = NewLines;
110 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000111 Comments.back().MaxColumn =
112 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000113 return;
114 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000115 }
Daniel Jasper821627e2013-01-21 22:49:20 +0000116
117 // If this line does not have a trailing comment, align the stored comments.
118 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
119 alignComments();
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000120 storeReplacement(Tok.FormatTok,
121 std::string(NewLines, '\n') + std::string(Spaces, ' '));
122 }
123
124 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
125 /// backslashes to escape newlines inside a preprocessor directive.
126 ///
127 /// This function and \c replaceWhitespace have the same behavior if
128 /// \c Newlines == 0.
129 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
130 unsigned Spaces, unsigned WhitespaceStartColumn,
131 const FormatStyle &Style) {
132 std::string NewLineText;
133 if (NewLines > 0) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000134 unsigned Offset =
135 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000136 for (unsigned i = 0; i < NewLines; ++i) {
137 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
138 NewLineText += "\\\n";
139 Offset = 0;
140 }
141 }
142 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
143 }
144
145 /// \brief Returns all the \c Replacements created during formatting.
146 const tooling::Replacements &generateReplacements() {
147 alignComments();
148 return Replaces;
149 }
150
151private:
152 /// \brief Structure to store a comment for later layout and alignment.
153 struct StoredComment {
154 FormatToken Tok;
155 unsigned MinColumn;
156 unsigned MaxColumn;
157 unsigned NewLines;
158 unsigned Spaces;
159 };
160 SmallVector<StoredComment, 16> Comments;
161 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
162
163 /// \brief Try to align all stashed comments.
164 void alignComments() {
165 unsigned MinColumn = 0;
166 unsigned MaxColumn = UINT_MAX;
167 comment_iterator Start = Comments.begin();
168 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
169 ++I) {
170 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
171 alignComments(Start, I, MinColumn);
172 MinColumn = I->MinColumn;
173 MaxColumn = I->MaxColumn;
174 Start = I;
175 } else {
176 MinColumn = std::max(MinColumn, I->MinColumn);
177 MaxColumn = std::min(MaxColumn, I->MaxColumn);
178 }
179 }
180 alignComments(Start, Comments.end(), MinColumn);
181 Comments.clear();
182 }
183
184 /// \brief Put all the comments between \p I and \p E into \p Column.
185 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
186 while (I != E) {
187 unsigned Spaces = I->Spaces + Column - I->MinColumn;
188 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
189 std::string(Spaces, ' '));
190 ++I;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000191 }
192 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000193
194 /// \brief Stores \p Text as the replacement for the whitespace in front of
195 /// \p Tok.
196 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasperafcbd852013-01-30 09:46:12 +0000197 // Don't create a replacement, if it does not change anything.
198 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
199 Tok.WhiteSpaceLength) == Text)
200 return;
201
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000202 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
203 Tok.WhiteSpaceLength, Text));
204 }
205
206 SourceManager &SourceMgr;
207 tooling::Replacements Replaces;
208};
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000209
Daniel Jasperbac016b2012-12-03 18:12:45 +0000210class UnwrappedLineFormatter {
211public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000212 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000213 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000214 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000215 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000216 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000217 FirstIndent(FirstIndent), RootToken(RootToken),
218 Whitespaces(Whitespaces) {
Daniel Jasperc79afda2013-01-18 10:56:38 +0000219 Parameters.PenaltyIndentLevel = 20;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000220 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000221 }
222
Manuel Klimekd4397b92013-01-04 23:34:14 +0000223 /// \brief Formats an \c UnwrappedLine.
224 ///
225 /// \returns The column after the last token in the last line of the
226 /// \c UnwrappedLine.
227 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000228 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000229 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000230 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000231 State.NextToken = &RootToken;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000232 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasper2e603772013-01-29 11:21:01 +0000233 State.VariablePos = 0;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000234 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000235
Manuel Klimekca547db2013-01-16 14:55:28 +0000236 DEBUG({
237 DebugTokenState(*State.NextToken);
238 });
239
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000240 // The first token has already been indented and thus consumed.
241 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000242
243 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000244 while (State.NextToken != NULL) {
Daniel Jasper7d1185d2013-01-18 09:19:33 +0000245 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
246 // Calculating the column is important for aligning trailing comments.
247 // FIXME: This does not seem to happen in conjunction with escaped
248 // newlines. If it does, fix!
249 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
250 State.NextToken->FormatTok.TokenLength;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000251 State.NextToken = State.NextToken->Children.empty()
252 ? NULL : &State.NextToken->Children[0];
Daniel Jasper7d1185d2013-01-18 09:19:33 +0000253 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000254 addTokenToState(false, false, State);
255 } else {
256 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
257 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimekca547db2013-01-16 14:55:28 +0000258 DEBUG({
259 if (Break < NoBreak)
260 llvm::errs() << "\n";
261 else
262 llvm::errs() << " ";
263 llvm::errs() << "<";
264 DebugPenalty(Break, Break < NoBreak);
265 llvm::errs() << "/";
266 DebugPenalty(NoBreak, !(Break < NoBreak));
267 llvm::errs() << "> ";
268 DebugTokenState(*State.NextToken);
269 });
Daniel Jasper1321eb52012-12-18 21:05:13 +0000270 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000271 if (State.NextToken != NULL &&
272 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
273 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000274 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000275 State.Stack.back().BreakAfterComma = true;
276 }
Daniel Jasper1321eb52012-12-18 21:05:13 +0000277 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000278 }
Manuel Klimekca547db2013-01-16 14:55:28 +0000279 DEBUG(llvm::errs() << "\n");
Manuel Klimekd4397b92013-01-04 23:34:14 +0000280 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000281 }
282
283private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000284 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
285 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000286 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
287 Tok.getLength());
Manuel Klimekca547db2013-01-16 14:55:28 +0000288 llvm::errs();
289 }
290
291 void DebugPenalty(unsigned Penalty, bool Winner) {
292 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
293 if (Penalty == UINT_MAX)
294 llvm::errs() << "MAX";
295 else
296 llvm::errs() << Penalty;
297 llvm::errs().resetColor();
298 }
299
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000300 struct ParenState {
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000301 ParenState(unsigned Indent, unsigned LastSpace)
Daniel Jasperf39c8852013-01-23 16:58:21 +0000302 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000303 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000304 BreakAfterComma(false), HasMultiParameterLine(false) {
305 }
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000306
Daniel Jasperbac016b2012-12-03 18:12:45 +0000307 /// \brief The position to which a specific parenthesis level needs to be
308 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000309 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000310
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000311 /// \brief The position of the last space on each level.
312 ///
313 /// Used e.g. to break like:
314 /// functionCall(Parameter, otherCall(
315 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000316 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000317
Daniel Jasperf39c8852013-01-23 16:58:21 +0000318 /// \brief This is the column of the first token after an assignment.
319 unsigned AssignmentColumn;
320
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000321 /// \brief The position the first "<<" operator encountered on each level.
322 ///
323 /// Used to align "<<" operators. 0 if no such operator has been encountered
324 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000325 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000326
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000327 /// \brief Whether a newline needs to be inserted before the block's closing
328 /// brace.
329 ///
330 /// We only want to insert a newline before the closing brace if there also
331 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000332 bool BreakBeforeClosingBrace;
333
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000334 /// \brief The column of a \c ? in a conditional expression;
335 unsigned QuestionColumn;
336
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000337 bool BreakAfterComma;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000338 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000339
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000340 bool operator<(const ParenState &Other) const {
341 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000342 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000343 if (LastSpace != Other.LastSpace)
344 return LastSpace < Other.LastSpace;
Daniel Jasperf39c8852013-01-23 16:58:21 +0000345 if (AssignmentColumn != Other.AssignmentColumn)
346 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000347 if (FirstLessLess != Other.FirstLessLess)
348 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000349 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
350 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000351 if (QuestionColumn != Other.QuestionColumn)
352 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperb3123142013-01-12 07:36:22 +0000353 if (BreakAfterComma != Other.BreakAfterComma)
354 return BreakAfterComma;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000355 if (HasMultiParameterLine != Other.HasMultiParameterLine)
356 return HasMultiParameterLine;
Daniel Jasperb3123142013-01-12 07:36:22 +0000357 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000358 }
359 };
360
361 /// \brief The current state when indenting a unwrapped line.
362 ///
363 /// As the indenting tries different combinations this is copied by value.
364 struct LineState {
365 /// \brief The number of used columns in the current line.
366 unsigned Column;
367
368 /// \brief The token that needs to be next formatted.
369 const AnnotatedToken *NextToken;
370
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000371 /// \brief The column of the first variable name in a variable declaration.
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000372 ///
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000373 /// Used to align further variables if necessary.
Daniel Jasper2e603772013-01-29 11:21:01 +0000374 unsigned VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000375
376 /// \brief \c true if this line contains a continued for-loop section.
377 bool LineContainsContinuedForLoopSection;
378
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000379 /// \brief A stack keeping track of properties applying to parenthesis
380 /// levels.
381 std::vector<ParenState> Stack;
382
383 /// \brief Comparison operator to be able to used \c LineState in \c map.
384 bool operator<(const LineState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000385 if (Other.NextToken != NextToken)
386 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000387 if (Other.Column != Column)
388 return Other.Column > Column;
Daniel Jasper2e603772013-01-29 11:21:01 +0000389 if (Other.VariablePos != VariablePos)
390 return Other.VariablePos < VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000391 if (Other.LineContainsContinuedForLoopSection !=
392 LineContainsContinuedForLoopSection)
393 return LineContainsContinuedForLoopSection;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000394 return Other.Stack < Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000395 }
396 };
397
Daniel Jasper20409152012-12-04 14:54:30 +0000398 /// \brief Appends the next token to \p State and updates information
399 /// necessary for indentation.
400 ///
401 /// Puts the token on the current line if \p Newline is \c true and adds a
402 /// line break and necessary indentation otherwise.
403 ///
404 /// If \p DryRun is \c false, also creates and stores the required
405 /// \c Replacement.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000406 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000407 const AnnotatedToken &Current = *State.NextToken;
408 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000409 assert(State.Stack.size());
410 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000411
412 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000413 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000414 if (Current.is(tok::r_brace)) {
415 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000416 } else if (Current.is(tok::string_literal) &&
417 Previous.is(tok::string_literal)) {
418 State.Column = State.Column - Previous.FormatTok.TokenLength;
419 } else if (Current.is(tok::lessless) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000420 State.Stack[ParenLevel].FirstLessLess != 0) {
421 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000422 } else if (ParenLevel != 0 &&
Daniel Jasper5f2173e2013-01-28 07:43:15 +0000423 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000424 Current.is(tok::period) || Current.is(tok::arrow) ||
425 Current.is(tok::question))) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000426 // Indent and extra 4 spaces after if we know the current expression is
427 // continued. Don't do that on the top level, as we already indent 4
428 // there.
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000429 State.Column = std::max(State.Stack.back().LastSpace,
430 State.Stack.back().Indent) + 4;
431 } else if (Current.Type == TT_ConditionalExpr) {
432 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper2e603772013-01-29 11:21:01 +0000433 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
434 ((RootToken.is(tok::kw_for) && ParenLevel == 1) ||
435 ParenLevel == 0)) {
436 State.Column = State.VariablePos;
Daniel Jasper83f25ba2013-01-28 15:16:31 +0000437 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
438 Current.Type == TT_StartOfName) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000439 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperf39c8852013-01-23 16:58:21 +0000440 } else if (Previous.Type == TT_BinaryOperator &&
441 State.Stack.back().AssignmentColumn != 0) {
442 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000443 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000444 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000445 }
446
Daniel Jasper26f7e782013-01-08 14:56:18 +0000447 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000448 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000449
Manuel Klimek060143e2013-01-02 18:33:23 +0000450 if (!DryRun) {
451 if (!Line.InPPDirective)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000452 Whitespaces.replaceWhitespace(Current, 1, State.Column,
453 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000454 else
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000455 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
456 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000457 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000458
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000459 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000460 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000461 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000462 } else {
Daniel Jasper2e603772013-01-29 11:21:01 +0000463 if (Current.is(tok::equal) &&
464 (RootToken.is(tok::kw_for) || ParenLevel == 0))
465 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000466
Daniel Jasper26f7e782013-01-08 14:56:18 +0000467 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
468 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000469 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000470
Daniel Jasperbac016b2012-12-03 18:12:45 +0000471 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000472 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000473
Daniel Jasper3fc0bb72013-01-09 10:40:23 +0000474 // FIXME: Do we need to do this for assignments nested in other
475 // expressions?
476 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper9cda8002013-01-07 13:08:40 +0000477 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper9c837d02013-01-09 07:06:56 +0000478 Previous.is(tok::kw_return)))
Daniel Jasperf39c8852013-01-23 16:58:21 +0000479 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperd4f2c2e2013-01-29 19:41:55 +0000480 if (Current.Type != TT_LineComment &&
481 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
482 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000483 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperd4f2c2e2013-01-29 19:41:55 +0000484 if (Previous.is(tok::comma) && Current.Type != TT_LineComment)
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000485 State.Stack[ParenLevel].HasMultiParameterLine = true;
486
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000487 State.Column += Spaces;
Daniel Jaspere438bac2013-01-23 20:41:06 +0000488 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
489 // Treat the condition inside an if as if it was a second function
490 // parameter, i.e. let nested calls have an indent of 4.
491 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper3499dda2013-01-25 15:43:32 +0000492 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jaspere438bac2013-01-23 20:41:06 +0000493 // Top-level spaces are exempt as that mostly leads to better results.
494 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000495 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000496 Previous.Type == TT_ConditionalExpr ||
497 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000498 getPrecedence(Previous) != prec::Assignment)
499 State.Stack.back().LastSpace = State.Column;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000500 else if (Previous.ParameterCount > 1 &&
501 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
502 Previous.Type == TT_TemplateOpener))
503 // If this function has multiple parameters, indent nested calls from
504 // the start of the first parameter.
505 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000506 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000507
508 // If we break after an {, we should also break before the corresponding }.
509 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000510 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000511
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000512 if (!Style.BinPackParameters && Newline) {
513 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf1579602013-01-29 16:03:49 +0000514 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000515 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
516 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf1579602013-01-29 16:03:49 +0000517 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
518 Line.MustBeDeclaration))
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000519 State.Stack.back().BreakAfterComma = true;
Daniel Jasper2e603772013-01-29 11:21:01 +0000520
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000521 // Any break on this level means that the parent level has been broken
522 // and we need to avoid bin packing there.
523 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
524 State.Stack[i].BreakAfterComma = true;
525 }
526 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000527
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000528 moveStateToNextToken(State);
Daniel Jasper20409152012-12-04 14:54:30 +0000529 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000530
Daniel Jasper20409152012-12-04 14:54:30 +0000531 /// \brief Mark the next token as consumed in \p State and modify its stacks
532 /// accordingly.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000533 void moveStateToNextToken(LineState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000534 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000535 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000536
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000537 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
538 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000539 if (Current.is(tok::question))
540 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000541
Daniel Jaspercf225b62012-12-24 13:43:52 +0000542 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000543 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000544 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
545 Current.is(tok::l_brace) ||
546 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000547 unsigned NewIndent;
Manuel Klimek2851c162013-01-10 14:36:46 +0000548 if (Current.is(tok::l_brace)) {
549 // FIXME: This does not work with nested static initializers.
550 // Implement a better handling for static initializers and similar
551 // constructs.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000552 NewIndent = Line.Level * 2 + 2;
Manuel Klimek2851c162013-01-10 14:36:46 +0000553 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000554 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek2851c162013-01-10 14:36:46 +0000555 }
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000556 State.Stack.push_back(ParenState(NewIndent,
557 State.Stack.back().LastSpace));
Daniel Jasper20409152012-12-04 14:54:30 +0000558 }
559
Daniel Jaspercf225b62012-12-24 13:43:52 +0000560 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000561 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000562 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
563 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
564 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000565 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000566 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000567
Daniel Jasper26f7e782013-01-08 14:56:18 +0000568 if (State.NextToken->Children.empty())
569 State.NextToken = NULL;
570 else
571 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000572
573 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000574 }
575
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000576 unsigned getColumnLimit() {
577 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
578 }
579
Daniel Jasperbac016b2012-12-03 18:12:45 +0000580 /// \brief Calculate the number of lines needed to format the remaining part
581 /// of the unwrapped line.
582 ///
583 /// Assumes the formatting so far has led to
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000584 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperbac016b2012-12-03 18:12:45 +0000585 /// added after the previous token.
586 ///
587 /// \param StopAt is used for optimization. If we can determine that we'll
588 /// definitely need at least \p StopAt additional lines, we already know of a
589 /// better solution.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000590 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000591 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000592 if (State.NextToken == NULL)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000593 return 0;
594
Daniel Jasper26f7e782013-01-08 14:56:18 +0000595 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000596 return UINT_MAX;
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000597 if (NewLine && !State.NextToken->CanBreakBefore &&
598 !(State.NextToken->is(tok::r_brace) &&
599 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000600 return UINT_MAX;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000601 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000602 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000603 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000604 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000605 State.LineContainsContinuedForLoopSection)
606 return UINT_MAX;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000607 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasperd4f2c2e2013-01-29 19:41:55 +0000608 State.NextToken->Type != TT_LineComment &&
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000609 State.Stack.back().BreakAfterComma)
610 return UINT_MAX;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000611 // Trying to insert a parameter on a new line if there are already more than
612 // one parameter on the current line is bin packing.
613 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
614 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
615 return UINT_MAX;
Daniel Jasperc79afda2013-01-18 10:56:38 +0000616 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
617 (State.NextToken->Parent->ClosesTemplateDeclaration &&
618 State.Stack.size() == 1)))
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000619 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000620
Daniel Jasper33182dd2012-12-05 14:57:28 +0000621 unsigned CurrentPenalty = 0;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000622 if (NewLine)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000623 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasperadc6aba2013-01-29 15:03:01 +0000624 State.NextToken->SplitPenalty;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000625
Daniel Jasper20409152012-12-04 14:54:30 +0000626 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000627
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000628 // Exceeding column limit is bad, assign penalty.
629 if (State.Column > getColumnLimit()) {
630 unsigned ExcessCharacters = State.Column - getColumnLimit();
631 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
632 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000633
Daniel Jasperbac016b2012-12-03 18:12:45 +0000634 if (StopAt <= CurrentPenalty)
635 return UINT_MAX;
636 StopAt -= CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000637 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000638 if (I != Memory.end()) {
639 // If this state has already been examined, we can safely return the
640 // previous result if we
641 // - have not hit the optimatization (and thus returned UINT_MAX) OR
642 // - are now computing for a smaller or equal StopAt.
643 unsigned SavedResult = I->second.first;
644 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000645 if (SavedResult != UINT_MAX)
646 return SavedResult + CurrentPenalty;
647 else if (StopAt <= SavedStopAt)
648 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000649 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000650
651 unsigned NoBreak = calcPenalty(State, false, StopAt);
652 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
653 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000654
655 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
656 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000657 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000658
659 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000660 }
661
Daniel Jasperbac016b2012-12-03 18:12:45 +0000662 FormatStyle Style;
663 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000664 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000665 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000666 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000667 WhitespaceManager &Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000668
Daniel Jasper33182dd2012-12-05 14:57:28 +0000669 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000670 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000671 StateMap Memory;
672
Daniel Jasperbac016b2012-12-03 18:12:45 +0000673 OptimizationParameters Parameters;
674};
675
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000676class LexerBasedFormatTokenSource : public FormatTokenSource {
677public:
678 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000679 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000680 IdentTable(Lex.getLangOpts()) {
681 Lex.SetKeepWhitespaceMode(true);
682 }
683
684 virtual FormatToken getNextToken() {
685 if (GreaterStashed) {
686 FormatTok.NewlinesBefore = 0;
687 FormatTok.WhiteSpaceStart =
688 FormatTok.Tok.getLocation().getLocWithOffset(1);
689 FormatTok.WhiteSpaceLength = 0;
690 GreaterStashed = false;
691 return FormatTok;
692 }
693
694 FormatTok = FormatToken();
695 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000696 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000697 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000698 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
699 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000700
701 // Consume and record whitespace until we find a significant token.
702 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +0000703 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000704 FormatTok.HasUnescapedNewline =
705 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000706 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
707
708 if (FormatTok.Tok.is(tok::eof))
709 return FormatTok;
710 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000711 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000712 }
Manuel Klimek95419382013-01-07 07:56:50 +0000713
714 // Now FormatTok is the next non-whitespace token.
715 FormatTok.TokenLength = Text.size();
716
Manuel Klimekd4397b92013-01-04 23:34:14 +0000717 // In case the token starts with escaped newlines, we want to
718 // take them into account as whitespace - this pattern is quite frequent
719 // in macro definitions.
720 // FIXME: What do we want to do with other escaped spaces, and escaped
721 // spaces or newlines in the middle of tokens?
722 // FIXME: Add a more explicit test.
723 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +0000724 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +0000725 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +0000726 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +0000727 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000728 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000729 }
730
731 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +0000732 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000733 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000734 FormatTok.Tok.setKind(Info.getTokenID());
735 }
736
737 if (FormatTok.Tok.is(tok::greatergreater)) {
738 FormatTok.Tok.setKind(tok::greater);
739 GreaterStashed = true;
740 }
741
742 return FormatTok;
743 }
744
745private:
746 FormatToken FormatTok;
747 bool GreaterStashed;
748 Lexer &Lex;
749 SourceManager &SourceMgr;
750 IdentifierTable IdentTable;
751
752 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +0000753 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000754 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
755 Tok.getLength());
756 }
757};
758
Daniel Jasperbac016b2012-12-03 18:12:45 +0000759class Formatter : public UnwrappedLineConsumer {
760public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000761 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
762 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000763 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +0000764 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000765 Whitespaces(SourceMgr), Ranges(Ranges) {
766 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000767
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000768 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000769
Daniel Jasperbac016b2012-12-03 18:12:45 +0000770 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000771 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +0000772 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000773 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +0000774 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper995e8202013-01-14 13:08:07 +0000775 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
776 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
777 Annotator.annotate();
778 }
779 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
780 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000781 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +0000782 const AnnotatedLine &TheLine = *I;
783 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000784 unsigned Indent =
785 formatFirstToken(TheLine.First, TheLine.Level,
786 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000787 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasper995e8202013-01-14 13:08:07 +0000788 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000789 TheLine.First, Whitespaces,
Daniel Jasper995e8202013-01-14 13:08:07 +0000790 StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000791 PreviousEndOfLineColumn = Formatter.format();
792 } else {
793 // If we did not reformat this unwrapped line, the column at the end of
794 // the last token is unchanged - thus, we can calculate the end of the
795 // last token, and return the result.
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000796 PreviousEndOfLineColumn =
Daniel Jasper995e8202013-01-14 13:08:07 +0000797 SourceMgr.getSpellingColumnNumber(
798 TheLine.Last->FormatTok.Tok.getLocation()) +
799 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000800 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000801 }
802 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000803 return Whitespaces.generateReplacements();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000804 }
805
806private:
Manuel Klimek517e8942013-01-11 17:54:10 +0000807 /// \brief Tries to merge lines into one.
808 ///
809 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
810 /// if possible; note that \c I will be incremented when lines are merged.
811 ///
812 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000813 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +0000814 std::vector<AnnotatedLine>::iterator &I,
815 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimek517e8942013-01-11 17:54:10 +0000816 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
817
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000818 // We can never merge stuff if there are trailing line comments.
819 if (I->Last->Type == TT_LineComment)
820 return;
821
Manuel Klimek517e8942013-01-11 17:54:10 +0000822 // Check whether the UnwrappedLine can be put onto a single line. If
823 // so, this is bound to be the optimal solution (by definition) and we
824 // don't need to analyze the entire solution space.
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000825 if (I->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000826 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000827 Limit -= I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +0000828
Daniel Jasper9c8c40e2013-01-21 14:18:28 +0000829 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000830 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000831
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000832 if (I->Last->is(tok::l_brace)) {
833 tryMergeSimpleBlock(I, E, Limit);
834 } else if (I->First.is(tok::kw_if)) {
835 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000836 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
837 I->First.FormatTok.IsFirst)) {
838 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000839 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000840 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000841 }
842
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000843 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
844 std::vector<AnnotatedLine>::iterator E,
845 unsigned Limit) {
846 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +0000847 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
848 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000849 if (I + 2 != E && (I + 2)->InPPDirective &&
850 !(I + 2)->First.FormatTok.HasUnescapedNewline)
851 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000852 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000853 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000854 join(Line, *(++I));
855 }
856
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000857 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
858 std::vector<AnnotatedLine>::iterator E,
859 unsigned Limit) {
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000860 if (!Style.AllowShortIfStatementsOnASingleLine)
861 return;
Manuel Klimek4c128122013-01-18 14:46:43 +0000862 if ((I + 1)->InPPDirective != I->InPPDirective ||
863 ((I + 1)->InPPDirective &&
864 (I + 1)->First.FormatTok.HasUnescapedNewline))
865 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000866 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +0000867 if (Line.Last->isNot(tok::r_paren))
868 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000869 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000870 return;
871 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
872 return;
873 // Only inline simple if's (no nested if or else).
874 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
875 return;
876 join(Line, *(++I));
877 }
878
879 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000880 std::vector<AnnotatedLine>::iterator E,
881 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +0000882 // First, check that the current line allows merging. This is the case if
883 // we're not in a control flow statement and the last token is an opening
884 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000885 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +0000886 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +0000887 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
888 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
889 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
890 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +0000891 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +0000892 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
893 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000894 if (!AllowedTokens)
895 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000896
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000897 AnnotatedToken *Tok = &(I + 1)->First;
898 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
899 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
900 Tok->SpaceRequiredBefore = false;
901 join(Line, *(I + 1));
902 I += 1;
903 } else {
904 // Check that we still have three lines and they fit into the limit.
905 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
906 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000907 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000908
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000909 // Second, check that the next line does not contain any braces - if it
910 // does, readability declines when putting it into a single line.
911 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
912 return;
913 do {
914 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
915 return;
916 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
917 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +0000918
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000919 // Last, check that the third line contains a single closing brace.
920 Tok = &(I + 2)->First;
921 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
922 Tok->MustBreakBefore)
923 return;
924
925 join(Line, *(I + 1));
926 join(Line, *(I + 2));
927 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +0000928 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000929 }
930
931 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
932 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000933 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
934 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +0000935 }
936
Daniel Jasper995e8202013-01-14 13:08:07 +0000937 void join(AnnotatedLine &A, const AnnotatedLine &B) {
938 A.Last->Children.push_back(B.First);
939 while (!A.Last->Children.empty()) {
940 A.Last->Children[0].Parent = A.Last;
941 A.Last = &A.Last->Children[0];
942 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000943 }
944
Daniel Jasper995e8202013-01-14 13:08:07 +0000945 bool touchesRanges(const AnnotatedLine &TheLine) {
946 const FormatToken *First = &TheLine.First.FormatTok;
947 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +0000948 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000949 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +0000950 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000951 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
952 Ranges[i].getBegin()) &&
953 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
954 LineRange.getBegin()))
955 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000956 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000957 return false;
958 }
959
960 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000961 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000962 }
963
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000964 /// \brief Add a new line and the required indent before the first Token
965 /// of the \c UnwrappedLine if there was no structural parsing error.
966 /// Returns the indent level of the \c UnwrappedLine.
967 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
968 bool InPPDirective,
969 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000970 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000971 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
972 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
973
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000974 unsigned Newlines =
975 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000976 if (Newlines == 0 && !Tok.IsFirst)
977 Newlines = 1;
978 unsigned Indent = Level * 2;
979
980 bool IsAccessModifier = false;
981 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
982 RootToken.is(tok::kw_private))
983 IsAccessModifier = true;
984 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
985 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
986 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
987 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
988 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
989 IsAccessModifier = true;
990
991 if (IsAccessModifier &&
992 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
993 Indent += Style.AccessModifierOffset;
994 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000995 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000996 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000997 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
998 PreviousEndOfLineColumn, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000999 }
1000 return Indent;
1001 }
1002
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001003 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001004 FormatStyle Style;
1005 Lexer &Lex;
1006 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001007 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001008 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001009 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001010 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001011};
1012
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001013tooling::Replacements
1014reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1015 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001016 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001017 OwningPtr<DiagnosticConsumer> DiagPrinter;
1018 if (DiagClient == 0) {
1019 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1020 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1021 DiagClient = DiagPrinter.get();
1022 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001023 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001024 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001025 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001026 Diagnostics.setSourceManager(&SourceMgr);
1027 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001028 return formatter.format();
1029}
1030
Daniel Jasper46ef8522013-01-10 13:08:12 +00001031LangOptions getFormattingLangOpts() {
1032 LangOptions LangOpts;
1033 LangOpts.CPlusPlus = 1;
1034 LangOpts.CPlusPlus11 = 1;
1035 LangOpts.Bool = 1;
1036 LangOpts.ObjC1 = 1;
1037 LangOpts.ObjC2 = 1;
1038 return LangOpts;
1039}
1040
Daniel Jaspercd162382013-01-07 13:26:07 +00001041} // namespace format
1042} // namespace clang