blob: 60265509db9bfbf18d62708866cdc0bb8080a5c5 [file] [log] [blame]
Alexander Kornienko4b672072013-06-03 16:45:03 +00001//===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===//
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 contains the declaration of the FormatToken, a wrapper
12/// around Token with additional information related to formatting.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_FORMAT_FORMAT_TOKEN_H
17#define LLVM_CLANG_FORMAT_FORMAT_TOKEN_H
18
19#include "clang/Basic/OperatorPrecedence.h"
Daniel Jasper8de9ed02013-08-22 15:00:41 +000020#include "clang/Format/Format.h"
Alexander Kornienko4b672072013-06-03 16:45:03 +000021#include "clang/Lex/Lexer.h"
Daniel Jasper8de9ed02013-08-22 15:00:41 +000022#include "llvm/ADT/OwningPtr.h"
Alexander Kornienko4b672072013-06-03 16:45:03 +000023
24namespace clang {
25namespace format {
26
27enum TokenType {
Daniel Jasper1db6c382013-10-22 15:30:28 +000028 TT_ArrayInitializerLSquare,
29 TT_ArraySubscriptLSquare,
Alexander Kornienko4b672072013-06-03 16:45:03 +000030 TT_BinaryOperator,
Alexander Kornienko60d1b042013-10-10 13:36:20 +000031 TT_BitFieldColon,
Alexander Kornienko4b672072013-06-03 16:45:03 +000032 TT_BlockComment,
33 TT_CastRParen,
34 TT_ConditionalExpr,
35 TT_CtorInitializerColon,
Daniel Jaspere33d4af2013-07-26 16:56:36 +000036 TT_CtorInitializerComma,
Alexander Kornienko4b672072013-06-03 16:45:03 +000037 TT_DesignatedInitializerPeriod,
Daniel Jasperb596fb22013-10-24 10:31:50 +000038 TT_DictLiteral,
Alexander Kornienko4b672072013-06-03 16:45:03 +000039 TT_ImplicitStringLiteral,
40 TT_InlineASMColon,
41 TT_InheritanceColon,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +000042 TT_FunctionLBrace,
Alexander Kornienko4b672072013-06-03 16:45:03 +000043 TT_FunctionTypeLParen,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000044 TT_LambdaLSquare,
Alexander Kornienko4b672072013-06-03 16:45:03 +000045 TT_LineComment,
Alexander Kornienko4b672072013-06-03 16:45:03 +000046 TT_ObjCBlockLParen,
47 TT_ObjCDecl,
Alexander Kornienko4b672072013-06-03 16:45:03 +000048 TT_ObjCForIn,
49 TT_ObjCMethodExpr,
50 TT_ObjCMethodSpecifier,
51 TT_ObjCProperty,
52 TT_ObjCSelectorName,
53 TT_OverloadedOperator,
54 TT_OverloadedOperatorLParen,
55 TT_PointerOrReference,
56 TT_PureVirtualSpecifier,
57 TT_RangeBasedForLoopColon,
58 TT_StartOfName,
59 TT_TemplateCloser,
60 TT_TemplateOpener,
Daniel Jasper43e6a282013-12-16 15:01:54 +000061 TT_TrailingAnnotation,
Daniel Jasper6cdec7c2013-07-09 14:36:48 +000062 TT_TrailingReturnArrow,
Alexander Kornienko4b672072013-06-03 16:45:03 +000063 TT_TrailingUnaryOperator,
64 TT_UnaryOperator,
65 TT_Unknown
66};
67
Daniel Jasperb1f74a82013-07-09 09:06:29 +000068// Represents what type of block a set of braces open.
69enum BraceBlockKind {
70 BK_Unknown,
71 BK_Block,
72 BK_BracedInit
73};
74
Daniel Jasperb10cbc42013-07-10 14:02:49 +000075// The packing kind of a function's parameters.
76enum ParameterPackingKind {
77 PPK_BinPacked,
78 PPK_OnePerLine,
79 PPK_Inconclusive
80};
81
Manuel Klimek71814b42013-10-11 21:25:45 +000082enum FormatDecision {
83 FD_Unformatted,
84 FD_Continue,
85 FD_Break
86};
87
Daniel Jasper8de9ed02013-08-22 15:00:41 +000088class TokenRole;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000089class AnnotatedLine;
Daniel Jasper8de9ed02013-08-22 15:00:41 +000090
Alexander Kornienko4b672072013-06-03 16:45:03 +000091/// \brief A wrapper around a \c Token storing information about the
Alp Tokerf6a24ce2013-12-05 16:25:25 +000092/// whitespace characters preceding it.
Alexander Kornienko4b672072013-06-03 16:45:03 +000093struct FormatToken {
94 FormatToken()
Alexander Kornienko632abb92013-09-02 13:58:14 +000095 : NewlinesBefore(0), HasUnescapedNewline(false), LastNewlineOffset(0),
Alexander Kornienko39856b72013-09-10 09:38:25 +000096 ColumnWidth(0), LastLineColumnWidth(0), IsMultiline(false),
Alexander Kornienko632abb92013-09-02 13:58:14 +000097 IsFirst(false), MustBreakBefore(false), IsUnterminatedLiteral(false),
Alexander Kornienkod7b837e2013-08-29 17:32:57 +000098 BlockKind(BK_Unknown), Type(TT_Unknown), SpacesRequiredBefore(0),
99 CanBreakBefore(false), ClosesTemplateDeclaration(false),
100 ParameterCount(0), PackingKind(PPK_Inconclusive), TotalLength(0),
Daniel Jasper63af7c42013-12-09 14:40:19 +0000101 UnbreakableTailLength(0), BindingStrength(0), NestingLevel(0),
102 SplitPenalty(0), LongestObjCSelectorName(0), FakeRParens(0),
Daniel Jasper562ecd42013-09-06 08:08:14 +0000103 StartsBinaryExpression(false), EndsBinaryExpression(false),
104 LastInChainOfCalls(false), PartOfMultiVariableDeclStmt(false),
Manuel Klimek71814b42013-10-11 21:25:45 +0000105 MatchingParen(NULL), Previous(NULL), Next(NULL),
106 Decision(FD_Unformatted), Finalized(false) {}
Alexander Kornienko4b672072013-06-03 16:45:03 +0000107
108 /// \brief The \c Token.
109 Token Tok;
110
111 /// \brief The number of newlines immediately before the \c Token.
112 ///
113 /// This can be used to determine what the user wrote in the original code
114 /// and thereby e.g. leave an empty line between two function definitions.
115 unsigned NewlinesBefore;
116
117 /// \brief Whether there is at least one unescaped newline before the \c
118 /// Token.
119 bool HasUnescapedNewline;
120
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000121 /// \brief The range of the whitespace immediately preceding the \c Token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000122 SourceRange WhitespaceRange;
123
124 /// \brief The offset just past the last '\n' in this token's leading
125 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
126 unsigned LastNewlineOffset;
127
Alexander Kornienko39856b72013-09-10 09:38:25 +0000128 /// \brief The width of the non-whitespace parts of the token (or its first
129 /// line for multi-line tokens) in columns.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000130 /// We need this to correctly measure number of columns a token spans.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000131 unsigned ColumnWidth;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000132
Alexander Kornienko39856b72013-09-10 09:38:25 +0000133 /// \brief Contains the width in columns of the last line of a multi-line
Alexander Kornienko632abb92013-09-02 13:58:14 +0000134 /// token.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000135 unsigned LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000136
Alexander Kornienko39856b72013-09-10 09:38:25 +0000137 /// \brief Whether the token text contains newlines (escaped or not).
138 bool IsMultiline;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000139
Alexander Kornienko4b672072013-06-03 16:45:03 +0000140 /// \brief Indicates that this is the first token.
141 bool IsFirst;
142
143 /// \brief Whether there must be a line break before this token.
144 ///
145 /// This happens for example when a preprocessor directive ended directly
146 /// before the token.
147 bool MustBreakBefore;
148
149 /// \brief Returns actual token start location without leading escaped
150 /// newlines and whitespace.
151 ///
152 /// This can be different to Tok.getLocation(), which includes leading escaped
153 /// newlines.
154 SourceLocation getStartOfNonWhitespace() const {
155 return WhitespaceRange.getEnd();
156 }
157
158 /// \brief The raw text of the token.
159 ///
160 /// Contains the raw token text without leading whitespace and without leading
161 /// escaped newlines.
162 StringRef TokenText;
163
Daniel Jasper8369aa52013-07-16 20:28:33 +0000164 /// \brief Set to \c true if this token is an unterminated literal.
165 bool IsUnterminatedLiteral;
166
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000167 /// \brief Contains the kind of block if this token is a brace.
168 BraceBlockKind BlockKind;
169
Alexander Kornienko4b672072013-06-03 16:45:03 +0000170 TokenType Type;
171
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000172 /// \brief The number of spaces that should be inserted before this token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000173 unsigned SpacesRequiredBefore;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000174
175 /// \brief \c true if it is allowed to break before this token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000176 bool CanBreakBefore;
177
178 bool ClosesTemplateDeclaration;
179
180 /// \brief Number of parameters, if this is "(", "[" or "<".
181 ///
182 /// This is initialized to 1 as we don't need to distinguish functions with
183 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
184 /// the number of commas.
185 unsigned ParameterCount;
186
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000187 /// \brief A token can have a special role that can carry extra information
188 /// about the token's formatting.
189 llvm::OwningPtr<TokenRole> Role;
190
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000191 /// \brief If this is an opening parenthesis, how are the parameters packed?
192 ParameterPackingKind PackingKind;
193
Manuel Klimek31c85922013-08-29 15:21:40 +0000194 /// \brief The total length of the unwrapped line up to and including this
195 /// token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000196 unsigned TotalLength;
197
Alexander Kornienko39856b72013-09-10 09:38:25 +0000198 /// \brief The original 0-based column of this token, including expanded tabs.
199 /// The configured TabWidth is used as tab width.
Manuel Klimek31c85922013-08-29 15:21:40 +0000200 unsigned OriginalColumn;
201
Alexander Kornienko4b672072013-06-03 16:45:03 +0000202 /// \brief The length of following tokens until the next natural split point,
203 /// or the next token that can be broken.
204 unsigned UnbreakableTailLength;
205
206 // FIXME: Come up with a 'cleaner' concept.
207 /// \brief The binding strength of a token. This is a combined value of
208 /// operator precedence, parenthesis nesting, etc.
209 unsigned BindingStrength;
210
Daniel Jasper63af7c42013-12-09 14:40:19 +0000211 /// \brief The nesting level of this token, i.e. the number of surrounding (),
212 /// [], {} or <>.
213 unsigned NestingLevel;
214
Alexander Kornienko4b672072013-06-03 16:45:03 +0000215 /// \brief Penalty for inserting a line break before this token.
216 unsigned SplitPenalty;
217
218 /// \brief If this is the first ObjC selector name in an ObjC method
219 /// definition or call, this contains the length of the longest name.
220 unsigned LongestObjCSelectorName;
221
222 /// \brief Stores the number of required fake parentheses and the
223 /// corresponding operator precedence.
224 ///
225 /// If multiple fake parentheses start at a token, this vector stores them in
226 /// reverse order, i.e. inner fake parenthesis first.
227 SmallVector<prec::Level, 4> FakeLParens;
228 /// \brief Insert this many fake ) after this token for correct indentation.
229 unsigned FakeRParens;
230
Daniel Jasper562ecd42013-09-06 08:08:14 +0000231 /// \brief \c true if this token starts a binary expression, i.e. has at least
232 /// one fake l_paren with a precedence greater than prec::Unknown.
233 bool StartsBinaryExpression;
234 /// \brief \c true if this token ends a binary expression.
235 bool EndsBinaryExpression;
236
Alexander Kornienko4b672072013-06-03 16:45:03 +0000237 /// \brief Is this the last "." or "->" in a builder-type call?
238 bool LastInChainOfCalls;
239
240 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
241 ///
242 /// Only set if \c Type == \c TT_StartOfName.
243 bool PartOfMultiVariableDeclStmt;
244
245 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
246
247 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
248 return is(K1) || is(K2);
249 }
250
251 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
252 return is(K1) || is(K2) || is(K3);
253 }
254
255 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
256 tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
257 tok::TokenKind K6 = tok::NUM_TOKENS,
258 tok::TokenKind K7 = tok::NUM_TOKENS,
259 tok::TokenKind K8 = tok::NUM_TOKENS,
260 tok::TokenKind K9 = tok::NUM_TOKENS,
261 tok::TokenKind K10 = tok::NUM_TOKENS,
262 tok::TokenKind K11 = tok::NUM_TOKENS,
263 tok::TokenKind K12 = tok::NUM_TOKENS) const {
264 return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
265 is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
266 }
267
268 bool isNot(tok::TokenKind Kind) const { return Tok.isNot(Kind); }
269
270 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
271 return Tok.isObjCAtKeyword(Kind);
272 }
273
274 bool isAccessSpecifier(bool ColonRequired = true) const {
275 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
276 (!ColonRequired || (Next && Next->is(tok::colon)));
277 }
278
279 bool isObjCAccessSpecifier() const {
280 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
281 Next->isObjCAtKeyword(tok::objc_protected) ||
282 Next->isObjCAtKeyword(tok::objc_package) ||
283 Next->isObjCAtKeyword(tok::objc_private));
284 }
285
286 /// \brief Returns whether \p Tok is ([{ or a template opening <.
287 bool opensScope() const {
288 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
289 Type == TT_TemplateOpener;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000290 }
Nico Weber0f987a62013-06-25 19:25:12 +0000291 /// \brief Returns whether \p Tok is )]} or a template closing >.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000292 bool closesScope() const {
293 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
294 Type == TT_TemplateCloser;
295 }
296
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000297 /// \brief Returns \c true if this is a "." or "->" accessing a member.
298 bool isMemberAccess() const {
299 return isOneOf(tok::arrow, tok::period) &&
300 Type != TT_DesignatedInitializerPeriod;
301 }
302
Alexander Kornienko4b672072013-06-03 16:45:03 +0000303 bool isUnaryOperator() const {
304 switch (Tok.getKind()) {
305 case tok::plus:
306 case tok::plusplus:
307 case tok::minus:
308 case tok::minusminus:
309 case tok::exclaim:
310 case tok::tilde:
311 case tok::kw_sizeof:
312 case tok::kw_alignof:
313 return true;
314 default:
315 return false;
316 }
317 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000318
Alexander Kornienko4b672072013-06-03 16:45:03 +0000319 bool isBinaryOperator() const {
320 // Comma is a binary operator, but does not behave as such wrt. formatting.
321 return getPrecedence() > prec::Comma;
322 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000323
Alexander Kornienko4b672072013-06-03 16:45:03 +0000324 bool isTrailingComment() const {
325 return is(tok::comment) && (!Next || Next->NewlinesBefore > 0);
326 }
327
328 prec::Level getPrecedence() const {
329 return getBinOpPrecedence(Tok.getKind(), true, true);
330 }
331
332 /// \brief Returns the previous token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000333 FormatToken *getPreviousNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000334 FormatToken *Tok = Previous;
335 while (Tok != NULL && Tok->is(tok::comment))
336 Tok = Tok->Previous;
337 return Tok;
338 }
339
340 /// \brief Returns the next token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000341 const FormatToken *getNextNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000342 const FormatToken *Tok = Next;
343 while (Tok != NULL && Tok->is(tok::comment))
344 Tok = Tok->Next;
345 return Tok;
346 }
347
Daniel Jasperb8f61682013-10-22 15:45:58 +0000348 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
349 /// list that should be indented with a block indent.
350 bool opensBlockTypeList(const FormatStyle &Style) const {
351 return Type == TT_ArrayInitializerLSquare ||
352 (is(tok::l_brace) &&
Daniel Jasperb596fb22013-10-24 10:31:50 +0000353 (BlockKind == BK_Block || Type == TT_DictLiteral ||
Daniel Jasperb8f61682013-10-22 15:45:58 +0000354 !Style.Cpp11BracedListStyle));
355 }
356
357 /// \brief Same as opensBlockTypeList, but for the closing token.
Daniel Jasper1db6c382013-10-22 15:30:28 +0000358 bool closesBlockTypeList(const FormatStyle &Style) const {
Daniel Jasperb8f61682013-10-22 15:45:58 +0000359 return MatchingParen && MatchingParen->opensBlockTypeList(Style);
Daniel Jasper1db6c382013-10-22 15:30:28 +0000360 }
361
Alexander Kornienko4b672072013-06-03 16:45:03 +0000362 FormatToken *MatchingParen;
363
364 FormatToken *Previous;
365 FormatToken *Next;
366
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000367 SmallVector<AnnotatedLine *, 1> Children;
368
Manuel Klimek71814b42013-10-11 21:25:45 +0000369 /// \brief Stores the formatting decision for the token once it was made.
370 FormatDecision Decision;
371
372 /// \brief If \c true, this token has been fully formatted (indented and
373 /// potentially re-formatted inside), and we do not allow further formatting
374 /// changes.
375 bool Finalized;
376
Alexander Kornienko4b672072013-06-03 16:45:03 +0000377private:
378 // Disallow copying.
Craig Topper411294d2013-07-01 04:07:34 +0000379 FormatToken(const FormatToken &) LLVM_DELETED_FUNCTION;
380 void operator=(const FormatToken &) LLVM_DELETED_FUNCTION;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000381};
382
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000383class ContinuationIndenter;
384struct LineState;
385
386class TokenRole {
387public:
388 TokenRole(const FormatStyle &Style) : Style(Style) {}
389 virtual ~TokenRole();
390
391 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
392 /// this function precomputes required information for formatting.
393 virtual void precomputeFormattingInfos(const FormatToken *Token);
394
395 /// \brief Apply the special formatting that the given role demands.
396 ///
397 /// Continues formatting from \p State leaving indentation to \p Indenter and
398 /// returns the total penalty that this formatting incurs.
399 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
400 bool DryRun) {
401 return 0;
402 }
403
404 /// \brief Notifies the \c Role that a comma was found.
405 virtual void CommaFound(const FormatToken *Token) {}
406
407protected:
408 const FormatStyle &Style;
409};
410
411class CommaSeparatedList : public TokenRole {
412public:
413 CommaSeparatedList(const FormatStyle &Style) : TokenRole(Style) {}
414
415 virtual void precomputeFormattingInfos(const FormatToken *Token);
416
417 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
418 bool DryRun);
419
420 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
421 virtual void CommaFound(const FormatToken *Token) { Commas.push_back(Token); }
422
423private:
424 /// \brief A struct that holds information on how to format a given list with
425 /// a specific number of columns.
426 struct ColumnFormat {
427 /// \brief The number of columns to use.
428 unsigned Columns;
429
430 /// \brief The total width in characters.
431 unsigned TotalWidth;
432
433 /// \brief The number of lines required for this format.
434 unsigned LineCount;
435
436 /// \brief The size of each column in characters.
437 SmallVector<unsigned, 8> ColumnSizes;
438 };
439
440 /// \brief Calculate which \c ColumnFormat fits best into
441 /// \p RemainingCharacters.
442 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
443
444 /// \brief The ordered \c FormatTokens making up the commas of this list.
445 SmallVector<const FormatToken *, 8> Commas;
446
447 /// \brief The length of each of the list's items in characters including the
448 /// trailing comma.
449 SmallVector<unsigned, 8> ItemLengths;
450
451 /// \brief Precomputed formats that can be used for this list.
452 SmallVector<ColumnFormat, 4> Formats;
453};
454
Alexander Kornienko4b672072013-06-03 16:45:03 +0000455} // namespace format
456} // namespace clang
457
458#endif // LLVM_CLANG_FORMAT_FORMAT_TOKEN_H