blob: 6cfa0d88239a80e508cc026e7586022360a70e4e [file] [log] [blame]
Daniel Jasperf7935112012-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 Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000020#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Manuel Klimek24998102013-01-16 14:55:28 +000026#include "llvm/Support/Debug.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000027#include <string>
28
Manuel Klimek24998102013-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 Jasperf7935112012-12-03 18:12:45 +000032namespace clang {
33namespace format {
34
Daniel Jasperf7935112012-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 Kornienko578fdd82012-12-06 18:03:27 +000042 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000043 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +000044 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000045 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +000046 LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000047 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000048 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000049 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-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 Kornienko578fdd82012-12-06 18:03:27 +000060 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000061 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +000062 GoogleStyle.BinPackParameters = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +000063 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +000064 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000065 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000066 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000067 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000068 return GoogleStyle;
69}
70
Daniel Jasper1b750ed2013-01-14 16:24:39 +000071FormatStyle getChromiumStyle() {
72 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000073 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper17fdaa42013-01-29 15:19:38 +000074 ChromiumStyle.SplitTemplateClosingGreater = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000075 return ChromiumStyle;
76}
77
Daniel Jasperf7935112012-12-03 18:12:45 +000078struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +000079 unsigned PenaltyIndentLevel;
Daniel Jasper2df93312013-01-09 10:16:05 +000080 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +000081};
82
Daniel Jasperaa701fa2013-01-18 08:44:07 +000083/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +000084///
Daniel Jasperaa701fa2013-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 Jasper304a9862013-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 Jasperaa701fa2013-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 Jasperbbc84152013-01-29 11:27:30 +0000111 Comments.back().MaxColumn =
112 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000113 return;
114 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000115 }
Daniel Jasper304a9862013-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 Jasperaa701fa2013-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 Jasperbbc84152013-01-29 11:27:30 +0000134 unsigned Offset =
135 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-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 Klimek0b689fd2013-01-10 18:45:26 +0000191 }
192 }
Daniel Jasperaa701fa2013-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 Jasper7b038a22013-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 Jasperaa701fa2013-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 Klimek0b689fd2013-01-10 18:45:26 +0000209
Daniel Jasperf7935112012-12-03 18:12:45 +0000210class UnwrappedLineFormatter {
211public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000212 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000213 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000214 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000215 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000216 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000217 FirstIndent(FirstIndent), RootToken(RootToken),
218 Whitespaces(Whitespaces) {
Daniel Jasper04468962013-01-18 10:56:38 +0000219 Parameters.PenaltyIndentLevel = 20;
Daniel Jasper2df93312013-01-09 10:16:05 +0000220 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000221 }
222
Manuel Klimek1abf7892013-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 Jaspere9de2602012-12-06 09:56:08 +0000228 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000229 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000230 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000231 State.NextToken = &RootToken;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000232 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
233 !Style.BinPackParameters));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000234 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000235 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000236
Manuel Klimek24998102013-01-16 14:55:28 +0000237 DEBUG({
238 DebugTokenState(*State.NextToken);
239 });
240
Daniel Jaspere9de2602012-12-06 09:56:08 +0000241 // The first token has already been indented and thus consumed.
242 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000243
Daniel Jasper4b866272013-02-01 11:00:45 +0000244 // If everything fits on a single line, just put it there.
245 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
246 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000247 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000248 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000249 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000250 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000251
252 // Find best solution in solution space.
253 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000254 }
255
256private:
Manuel Klimek24998102013-01-16 14:55:28 +0000257 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
258 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000259 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
260 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000261 llvm::errs();
262 }
263
Daniel Jasper337816e2013-01-11 10:22:12 +0000264 struct ParenState {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000265 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking)
Daniel Jaspera836b902013-01-23 16:58:21 +0000266 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperca6623b2013-01-28 12:45:14 +0000267 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000268 AvoidBinPacking(AvoidBinPacking), BreakAfterComma(false),
269 HasMultiParameterLine(false) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000270 }
Daniel Jasper6d822722012-12-24 16:43:00 +0000271
Daniel Jasperf7935112012-12-03 18:12:45 +0000272 /// \brief The position to which a specific parenthesis level needs to be
273 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000274 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000275
Daniel Jaspere9de2602012-12-06 09:56:08 +0000276 /// \brief The position of the last space on each level.
277 ///
278 /// Used e.g. to break like:
279 /// functionCall(Parameter, otherCall(
280 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000281 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000282
Daniel Jaspera836b902013-01-23 16:58:21 +0000283 /// \brief This is the column of the first token after an assignment.
284 unsigned AssignmentColumn;
285
Daniel Jaspere9de2602012-12-06 09:56:08 +0000286 /// \brief The position the first "<<" operator encountered on each level.
287 ///
288 /// Used to align "<<" operators. 0 if no such operator has been encountered
289 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000290 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000291
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000292 /// \brief Whether a newline needs to be inserted before the block's closing
293 /// brace.
294 ///
295 /// We only want to insert a newline before the closing brace if there also
296 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000297 bool BreakBeforeClosingBrace;
298
Daniel Jasperca6623b2013-01-28 12:45:14 +0000299 /// \brief The column of a \c ? in a conditional expression;
300 unsigned QuestionColumn;
301
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000302 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
303 /// lines, in this context.
304 bool AvoidBinPacking;
305
306 /// \brief Break after the next comma (or all the commas in this context if
307 /// \c AvoidBinPacking is \c true).
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000308 bool BreakAfterComma;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000309
310 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000311 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000312
Daniel Jasper337816e2013-01-11 10:22:12 +0000313 bool operator<(const ParenState &Other) const {
314 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000315 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000316 if (LastSpace != Other.LastSpace)
317 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000318 if (AssignmentColumn != Other.AssignmentColumn)
319 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000320 if (FirstLessLess != Other.FirstLessLess)
321 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000322 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
323 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000324 if (QuestionColumn != Other.QuestionColumn)
325 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000326 if (AvoidBinPacking != Other.AvoidBinPacking)
327 return AvoidBinPacking;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000328 if (BreakAfterComma != Other.BreakAfterComma)
329 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000330 if (HasMultiParameterLine != Other.HasMultiParameterLine)
331 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000332 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000333 }
334 };
335
336 /// \brief The current state when indenting a unwrapped line.
337 ///
338 /// As the indenting tries different combinations this is copied by value.
339 struct LineState {
340 /// \brief The number of used columns in the current line.
341 unsigned Column;
342
343 /// \brief The token that needs to be next formatted.
344 const AnnotatedToken *NextToken;
345
Daniel Jasperbbc84152013-01-29 11:27:30 +0000346 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000347 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000348 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000349 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000350
351 /// \brief \c true if this line contains a continued for-loop section.
352 bool LineContainsContinuedForLoopSection;
353
Daniel Jasper337816e2013-01-11 10:22:12 +0000354 /// \brief A stack keeping track of properties applying to parenthesis
355 /// levels.
356 std::vector<ParenState> Stack;
357
358 /// \brief Comparison operator to be able to used \c LineState in \c map.
359 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000360 if (Other.NextToken != NextToken)
361 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000362 if (Other.Column != Column)
363 return Other.Column > Column;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000364 if (Other.VariablePos != VariablePos)
365 return Other.VariablePos < VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000366 if (Other.LineContainsContinuedForLoopSection !=
367 LineContainsContinuedForLoopSection)
368 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000369 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000370 }
371 };
372
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000373 /// \brief Appends the next token to \p State and updates information
374 /// necessary for indentation.
375 ///
376 /// Puts the token on the current line if \p Newline is \c true and adds a
377 /// line break and necessary indentation otherwise.
378 ///
379 /// If \p DryRun is \c false, also creates and stores the required
380 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000381 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000382 const AnnotatedToken &Current = *State.NextToken;
383 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000384 assert(State.Stack.size());
385 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000386
Daniel Jasper4b866272013-02-01 11:00:45 +0000387 if (Current.Type == TT_ImplicitStringLiteral) {
388 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
389 State.NextToken->FormatTok.TokenLength;
390 if (State.NextToken->Children.empty())
391 State.NextToken = NULL;
392 else
393 State.NextToken = &State.NextToken->Children[0];
394 return;
395 }
396
Daniel Jasperf7935112012-12-03 18:12:45 +0000397 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000398 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000399 if (Current.is(tok::r_brace)) {
400 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000401 } else if (Current.is(tok::string_literal) &&
402 Previous.is(tok::string_literal)) {
403 State.Column = State.Column - Previous.FormatTok.TokenLength;
404 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000405 State.Stack[ParenLevel].FirstLessLess != 0) {
406 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000407 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000408 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000409 Current.is(tok::period) || Current.is(tok::arrow) ||
410 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000411 // Indent and extra 4 spaces after if we know the current expression is
412 // continued. Don't do that on the top level, as we already indent 4
413 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000414 State.Column = std::max(State.Stack.back().LastSpace,
415 State.Stack.back().Indent) + 4;
416 } else if (Current.Type == TT_ConditionalExpr) {
417 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000418 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
419 ((RootToken.is(tok::kw_for) && ParenLevel == 1) ||
420 ParenLevel == 0)) {
421 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000422 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
423 Current.Type == TT_StartOfName) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000424 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000425 } else if (Previous.Type == TT_BinaryOperator &&
426 State.Stack.back().AssignmentColumn != 0) {
427 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000428 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000429 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000430 }
431
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000432 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
433 State.Stack.back().BreakAfterComma = false;
434
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000435 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000436 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000437
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000438 if (!DryRun) {
439 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000440 Whitespaces.replaceWhitespace(Current, 1, State.Column,
441 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000442 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000443 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
444 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000445 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000446
Daniel Jasper337816e2013-01-11 10:22:12 +0000447 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000448 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000449 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000450 } else {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000451 if (Current.is(tok::equal) &&
452 (RootToken.is(tok::kw_for) || ParenLevel == 0))
453 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000454
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000455 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
456 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000457 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000458
Daniel Jasperf7935112012-12-03 18:12:45 +0000459 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000460 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000461
Daniel Jasperbcab4302013-01-09 10:40:23 +0000462 // FIXME: Do we need to do this for assignments nested in other
463 // expressions?
464 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000465 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000466 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000467 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000468 if (Current.Type != TT_LineComment &&
469 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
470 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper337816e2013-01-11 10:22:12 +0000471 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000472 if (Previous.is(tok::comma) && Current.Type != TT_LineComment)
Daniel Jasper9278eb92013-01-16 14:59:02 +0000473 State.Stack[ParenLevel].HasMultiParameterLine = true;
474
Daniel Jaspere9de2602012-12-06 09:56:08 +0000475 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000476 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
477 // Treat the condition inside an if as if it was a second function
478 // parameter, i.e. let nested calls have an indent of 4.
479 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000480 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000481 // Top-level spaces are exempt as that mostly leads to better results.
482 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000483 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000484 Previous.Type == TT_ConditionalExpr ||
485 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000486 getPrecedence(Previous) != prec::Assignment)
487 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000488 else if (Previous.ParameterCount > 1 &&
489 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000490 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000491 Previous.Type == TT_TemplateOpener))
492 // If this function has multiple parameters, indent nested calls from
493 // the start of the first parameter.
494 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000495 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000496
497 // If we break after an {, we should also break before the corresponding }.
498 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000499 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000500
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000501 if (State.Stack.back().AvoidBinPacking && Newline) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000502 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000503 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000504 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
505 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000506 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
507 Line.MustBeDeclaration))
Daniel Jaspere941b162013-01-23 10:08:28 +0000508 State.Stack.back().BreakAfterComma = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000509
Daniel Jaspere941b162013-01-23 10:08:28 +0000510 // Any break on this level means that the parent level has been broken
511 // and we need to avoid bin packing there.
512 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
513 State.Stack[i].BreakAfterComma = true;
514 }
515 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000516
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000517 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000518 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000519
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000520 /// \brief Mark the next token as consumed in \p State and modify its stacks
521 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000522 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000523 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000524 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000525
Daniel Jasper337816e2013-01-11 10:22:12 +0000526 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
527 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000528 if (Current.is(tok::question))
529 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000530 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000531 !Current.MatchingParen->MustBreakBefore) {
532 AnnotatedToken *End = Current.MatchingParen;
533 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
534 End = &End->Children[0];
535 }
536 unsigned Length = End->TotalLength - Current.TotalLength + 1;
537 if (Length + State.Column > getColumnLimit())
538 State.Stack.back().BreakAfterComma = true;
539 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000540
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000541 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000542 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000543 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
544 Current.is(tok::l_brace) ||
545 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000546 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000547 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000548 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000549 NewIndent = 2 + State.Stack.back().LastSpace;
550 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000551 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000552 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000553 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000554 }
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000555 State.Stack.push_back(ParenState(NewIndent, State.Stack.back().LastSpace,
556 AvoidBinPacking));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000557 }
558
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000559 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000560 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000561 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
562 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
563 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000564 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000565 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000566
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000567 if (State.NextToken->Children.empty())
568 State.NextToken = NULL;
569 else
570 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000571
572 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000573 }
574
Daniel Jasper2df93312013-01-09 10:16:05 +0000575 unsigned getColumnLimit() {
576 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
577 }
578
Daniel Jasper4b866272013-02-01 11:00:45 +0000579 /// \brief An edge in the solution space starting from the \c LineState and
580 /// inserting a newline dependent on the \c bool.
581 typedef std::pair<bool, const LineState *> Edge;
582
583 /// \brief An item in the prioritized BFS search queue. The \c LineState was
584 /// reached using the \c Edge.
585 typedef std::pair<LineState, Edge> QueueItem;
586
587 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000588 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000589 /// This implements a variant of Dijkstra's algorithm on the graph that spans
590 /// the solution space (\c LineStates are the nodes). The algorithm tries to
591 /// find the shortest path (the one with lowest penalty) from \p InitialState
592 /// to a state where all tokens are placed.
593 unsigned analyzeSolutionSpace(const LineState &InitialState) {
594 // Insert start element into queue.
595 std::multimap<unsigned, QueueItem> Queue;
596 Queue.insert(std::pair<unsigned, QueueItem>(
Daniel Jasper83d4e782013-02-01 11:28:16 +0000597 0, QueueItem(InitialState, Edge(false, (const LineState *) 0))));
Daniel Jasper4b866272013-02-01 11:00:45 +0000598 std::map<LineState, Edge> Seen;
599
600 // While not empty, take first element and follow edges.
601 while (!Queue.empty()) {
602 unsigned Penalty = Queue.begin()->first;
603 QueueItem Item = Queue.begin()->second;
604 if (Item.first.NextToken == NULL)
605 break;
606 Queue.erase(Queue.begin());
607
608 if (Seen.find(Item.first) != Seen.end())
609 continue; // State already examined with lower penalty.
610
611 const LineState &SavedState = Seen.insert(std::pair<LineState, Edge>(
612 Item.first,
613 Edge(Item.second.first, Item.second.second))).first->first;
614
615 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ false, Queue);
616 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ true, Queue);
617 }
618
619 if (Queue.empty())
620 // We were unable to find a solution, do nothing.
621 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000622 return 0;
623
Daniel Jasper4b866272013-02-01 11:00:45 +0000624 // Reconstruct the solution.
625 // FIXME: Add debugging output.
626 Edge *CurrentEdge = &Queue.begin()->second.second;
627 while (CurrentEdge->second != NULL) {
628 LineState CurrentState = *CurrentEdge->second;
629 addTokenToState(CurrentEdge->first, false, CurrentState);
630 CurrentEdge = &Seen[*CurrentEdge->second];
631 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000632
Daniel Jasper4b866272013-02-01 11:00:45 +0000633 // Return the column after the last token of the solution.
634 return Queue.begin()->second.first.Column;
635 }
636
637 /// \brief Add the following state to the analysis queue \p Queue.
638 ///
639 /// Assume the current state is \p OldState and has been reached with a
640 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
641 void addNextStateToQueue(const LineState &OldState, unsigned Penalty,
642 bool NewLine,
643 std::multimap<unsigned, QueueItem> &Queue) {
644 if (NewLine && !canBreak(OldState))
645 return;
646 if (!NewLine && mustBreak(OldState))
647 return;
648 LineState State(OldState);
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000649 if (NewLine)
Daniel Jasper4b866272013-02-01 11:00:45 +0000650 Penalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
651 State.NextToken->SplitPenalty;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000652 addTokenToState(NewLine, true, State);
Daniel Jasper2df93312013-01-09 10:16:05 +0000653 if (State.Column > getColumnLimit()) {
654 unsigned ExcessCharacters = State.Column - getColumnLimit();
Daniel Jasper4b866272013-02-01 11:00:45 +0000655 Penalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000656 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000657 Queue.insert(std::pair<unsigned, QueueItem>(
658 Penalty, QueueItem(State, Edge(NewLine, &OldState))));
659 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000660
Daniel Jasper4b866272013-02-01 11:00:45 +0000661 /// \brief Returns \c true, if a line break after \p State is allowed.
662 bool canBreak(const LineState &State) {
663 if (!State.NextToken->CanBreakBefore &&
664 !(State.NextToken->is(tok::r_brace) &&
665 State.Stack.back().BreakBeforeClosingBrace))
666 return false;
667 // Trying to insert a parameter on a new line if there are already more than
668 // one parameter on the current line is bin packing.
669 if (State.NextToken->Parent->is(tok::comma) &&
670 State.Stack.back().HasMultiParameterLine &&
671 State.Stack.back().AvoidBinPacking)
672 return false;
673 return true;
674 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000675
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000676
Daniel Jasper4b866272013-02-01 11:00:45 +0000677 /// \brief Returns \c true, if a line break after \p State is mandatory.
678 bool mustBreak(const LineState &State) {
679 if (State.NextToken->MustBreakBefore)
680 return true;
681 if (State.NextToken->is(tok::r_brace) &&
682 State.Stack.back().BreakBeforeClosingBrace)
683 return true;
684 if (State.NextToken->Parent->is(tok::semi) &&
685 State.LineContainsContinuedForLoopSection)
686 return true;
687 if (State.NextToken->Parent->is(tok::comma) &&
688 State.Stack.back().BreakAfterComma &&
689 State.NextToken->Type != TT_LineComment)
690 return true;
691 if ((State.NextToken->Type == TT_CtorInitializerColon ||
692 (State.NextToken->Parent->ClosesTemplateDeclaration &&
693 State.Stack.size() == 1)))
694 return true;
695 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000696 }
697
Daniel Jasperf7935112012-12-03 18:12:45 +0000698 FormatStyle Style;
699 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000700 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000701 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000702 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000703 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000704
705 OptimizationParameters Parameters;
706};
707
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000708class LexerBasedFormatTokenSource : public FormatTokenSource {
709public:
710 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000711 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000712 IdentTable(Lex.getLangOpts()) {
713 Lex.SetKeepWhitespaceMode(true);
714 }
715
716 virtual FormatToken getNextToken() {
717 if (GreaterStashed) {
718 FormatTok.NewlinesBefore = 0;
719 FormatTok.WhiteSpaceStart =
720 FormatTok.Tok.getLocation().getLocWithOffset(1);
721 FormatTok.WhiteSpaceLength = 0;
722 GreaterStashed = false;
723 return FormatTok;
724 }
725
726 FormatTok = FormatToken();
727 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000728 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000729 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000730 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
731 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000732
733 // Consume and record whitespace until we find a significant token.
734 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000735 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasperbbc84152013-01-29 11:27:30 +0000736 FormatTok.HasUnescapedNewline =
737 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000738 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
739
740 if (FormatTok.Tok.is(tok::eof))
741 return FormatTok;
742 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000743 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000744 }
Manuel Klimekef920692013-01-07 07:56:50 +0000745
746 // Now FormatTok is the next non-whitespace token.
747 FormatTok.TokenLength = Text.size();
748
Manuel Klimek1abf7892013-01-04 23:34:14 +0000749 // In case the token starts with escaped newlines, we want to
750 // take them into account as whitespace - this pattern is quite frequent
751 // in macro definitions.
752 // FIXME: What do we want to do with other escaped spaces, and escaped
753 // spaces or newlines in the middle of tokens?
754 // FIXME: Add a more explicit test.
755 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000756 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000757 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000758 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000759 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000760 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000761 }
762
763 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000764 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000765 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000766 FormatTok.Tok.setKind(Info.getTokenID());
767 }
768
769 if (FormatTok.Tok.is(tok::greatergreater)) {
770 FormatTok.Tok.setKind(tok::greater);
771 GreaterStashed = true;
772 }
773
774 return FormatTok;
775 }
776
777private:
778 FormatToken FormatTok;
779 bool GreaterStashed;
780 Lexer &Lex;
781 SourceManager &SourceMgr;
782 IdentifierTable IdentTable;
783
784 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000785 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000786 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
787 Tok.getLength());
788 }
789};
790
Daniel Jasperf7935112012-12-03 18:12:45 +0000791class Formatter : public UnwrappedLineConsumer {
792public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000793 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
794 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000795 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000796 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000797 Whitespaces(SourceMgr), Ranges(Ranges) {
798 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000799
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000800 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000801
Daniel Jasperf7935112012-12-03 18:12:45 +0000802 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000803 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000804 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000805 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000806 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000807 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
808 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
809 Annotator.annotate();
810 }
811 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
812 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000813 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000814 const AnnotatedLine &TheLine = *I;
815 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000816 unsigned Indent =
817 formatFirstToken(TheLine.First, TheLine.Level,
818 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000819 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000820 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000821 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000822 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000823 PreviousEndOfLineColumn = Formatter.format();
824 } else {
825 // If we did not reformat this unwrapped line, the column at the end of
826 // the last token is unchanged - thus, we can calculate the end of the
827 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000828 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000829 SourceMgr.getSpellingColumnNumber(
830 TheLine.Last->FormatTok.Tok.getLocation()) +
831 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000832 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000833 }
834 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000835 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +0000836 }
837
838private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000839 /// \brief Tries to merge lines into one.
840 ///
841 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
842 /// if possible; note that \c I will be incremented when lines are merged.
843 ///
844 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000845 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000846 std::vector<AnnotatedLine>::iterator &I,
847 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000848 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
849
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000850 // We can never merge stuff if there are trailing line comments.
851 if (I->Last->Type == TT_LineComment)
852 return;
853
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000854 // Check whether the UnwrappedLine can be put onto a single line. If
855 // so, this is bound to be the optimal solution (by definition) and we
856 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000857 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000858 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000859 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000860
Daniel Jasperd41ee2d2013-01-21 14:18:28 +0000861 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000862 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000863
Daniel Jasper25837aa2013-01-14 14:14:23 +0000864 if (I->Last->is(tok::l_brace)) {
865 tryMergeSimpleBlock(I, E, Limit);
866 } else if (I->First.is(tok::kw_if)) {
867 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +0000868 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
869 I->First.FormatTok.IsFirst)) {
870 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000871 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000872 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000873 }
874
Daniel Jasper39825ea2013-01-14 15:40:57 +0000875 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
876 std::vector<AnnotatedLine>::iterator E,
877 unsigned Limit) {
878 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +0000879 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
880 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000881 if (I + 2 != E && (I + 2)->InPPDirective &&
882 !(I + 2)->First.FormatTok.HasUnescapedNewline)
883 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000884 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000885 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000886 join(Line, *(++I));
887 }
888
Daniel Jasper25837aa2013-01-14 14:14:23 +0000889 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
890 std::vector<AnnotatedLine>::iterator E,
891 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000892 if (!Style.AllowShortIfStatementsOnASingleLine)
893 return;
Manuel Klimekda087612013-01-18 14:46:43 +0000894 if ((I + 1)->InPPDirective != I->InPPDirective ||
895 ((I + 1)->InPPDirective &&
896 (I + 1)->First.FormatTok.HasUnescapedNewline))
897 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000898 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000899 if (Line.Last->isNot(tok::r_paren))
900 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000901 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +0000902 return;
903 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
904 return;
905 // Only inline simple if's (no nested if or else).
906 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
907 return;
908 join(Line, *(++I));
909 }
910
911 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +0000912 std::vector<AnnotatedLine>::iterator E,
913 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000914 // First, check that the current line allows merging. This is the case if
915 // we're not in a control flow statement and the last token is an opening
916 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +0000917 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000918 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000919 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
920 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
921 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
922 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +0000923 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000924 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
925 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000926 if (!AllowedTokens)
927 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000928
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000929 AnnotatedToken *Tok = &(I + 1)->First;
930 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
931 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
932 Tok->SpaceRequiredBefore = false;
933 join(Line, *(I + 1));
934 I += 1;
935 } else {
936 // Check that we still have three lines and they fit into the limit.
937 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
938 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +0000939 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000940
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000941 // Second, check that the next line does not contain any braces - if it
942 // does, readability declines when putting it into a single line.
943 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
944 return;
945 do {
946 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
947 return;
948 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
949 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000950
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000951 // Last, check that the third line contains a single closing brace.
952 Tok = &(I + 2)->First;
953 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
954 Tok->MustBreakBefore)
955 return;
956
957 join(Line, *(I + 1));
958 join(Line, *(I + 2));
959 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000960 }
Daniel Jasper25837aa2013-01-14 14:14:23 +0000961 }
962
963 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
964 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000965 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
966 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000967 }
968
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000969 void join(AnnotatedLine &A, const AnnotatedLine &B) {
970 A.Last->Children.push_back(B.First);
971 while (!A.Last->Children.empty()) {
972 A.Last->Children[0].Parent = A.Last;
973 A.Last = &A.Last->Children[0];
974 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000975 }
976
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000977 bool touchesRanges(const AnnotatedLine &TheLine) {
978 const FormatToken *First = &TheLine.First.FormatTok;
979 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +0000980 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +0000981 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +0000982 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000983 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
984 Ranges[i].getBegin()) &&
985 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
986 LineRange.getBegin()))
987 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000988 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000989 return false;
990 }
991
992 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000993 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +0000994 }
995
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000996 /// \brief Add a new line and the required indent before the first Token
997 /// of the \c UnwrappedLine if there was no structural parsing error.
998 /// Returns the indent level of the \c UnwrappedLine.
999 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1000 bool InPPDirective,
1001 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001002 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001003 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1004 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1005
Daniel Jasperbbc84152013-01-29 11:27:30 +00001006 unsigned Newlines =
1007 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001008 if (Newlines == 0 && !Tok.IsFirst)
1009 Newlines = 1;
1010 unsigned Indent = Level * 2;
1011
1012 bool IsAccessModifier = false;
1013 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1014 RootToken.is(tok::kw_private))
1015 IsAccessModifier = true;
1016 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1017 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1018 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1019 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1020 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1021 IsAccessModifier = true;
1022
1023 if (IsAccessModifier &&
1024 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1025 Indent += Style.AccessModifierOffset;
1026 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001027 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001028 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001029 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1030 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001031 }
1032 return Indent;
1033 }
1034
Alexander Kornienko116ba682013-01-14 11:34:14 +00001035 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001036 FormatStyle Style;
1037 Lexer &Lex;
1038 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001039 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001040 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001041 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001042 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001043};
1044
Daniel Jasperbbc84152013-01-29 11:27:30 +00001045tooling::Replacements
1046reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1047 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001048 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001049 OwningPtr<DiagnosticConsumer> DiagPrinter;
1050 if (DiagClient == 0) {
1051 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1052 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1053 DiagClient = DiagPrinter.get();
1054 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001055 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001056 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001057 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001058 Diagnostics.setSourceManager(&SourceMgr);
1059 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001060 return formatter.format();
1061}
1062
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001063LangOptions getFormattingLangOpts() {
1064 LangOptions LangOpts;
1065 LangOpts.CPlusPlus = 1;
1066 LangOpts.CPlusPlus11 = 1;
1067 LangOpts.Bool = 1;
1068 LangOpts.ObjC1 = 1;
1069 LangOpts.ObjC2 = 1;
1070 return LangOpts;
1071}
1072
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001073} // namespace format
1074} // namespace clang