blob: a8d54ef264002e27cd277af116a07a5bf589c342 [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 Jasper6cdec7c2013-07-09 14:36:48 +000061 TT_TrailingReturnArrow,
Alexander Kornienko4b672072013-06-03 16:45:03 +000062 TT_TrailingUnaryOperator,
63 TT_UnaryOperator,
64 TT_Unknown
65};
66
Daniel Jasperb1f74a82013-07-09 09:06:29 +000067// Represents what type of block a set of braces open.
68enum BraceBlockKind {
69 BK_Unknown,
70 BK_Block,
71 BK_BracedInit
72};
73
Daniel Jasperb10cbc42013-07-10 14:02:49 +000074// The packing kind of a function's parameters.
75enum ParameterPackingKind {
76 PPK_BinPacked,
77 PPK_OnePerLine,
78 PPK_Inconclusive
79};
80
Manuel Klimek71814b42013-10-11 21:25:45 +000081enum FormatDecision {
82 FD_Unformatted,
83 FD_Continue,
84 FD_Break
85};
86
Daniel Jasper8de9ed02013-08-22 15:00:41 +000087class TokenRole;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000088class AnnotatedLine;
Daniel Jasper8de9ed02013-08-22 15:00:41 +000089
Alexander Kornienko4b672072013-06-03 16:45:03 +000090/// \brief A wrapper around a \c Token storing information about the
Alp Tokerf6a24ce2013-12-05 16:25:25 +000091/// whitespace characters preceding it.
Alexander Kornienko4b672072013-06-03 16:45:03 +000092struct FormatToken {
93 FormatToken()
Alexander Kornienko632abb92013-09-02 13:58:14 +000094 : NewlinesBefore(0), HasUnescapedNewline(false), LastNewlineOffset(0),
Alexander Kornienko39856b72013-09-10 09:38:25 +000095 ColumnWidth(0), LastLineColumnWidth(0), IsMultiline(false),
Alexander Kornienko632abb92013-09-02 13:58:14 +000096 IsFirst(false), MustBreakBefore(false), IsUnterminatedLiteral(false),
Alexander Kornienkod7b837e2013-08-29 17:32:57 +000097 BlockKind(BK_Unknown), Type(TT_Unknown), SpacesRequiredBefore(0),
98 CanBreakBefore(false), ClosesTemplateDeclaration(false),
99 ParameterCount(0), PackingKind(PPK_Inconclusive), TotalLength(0),
100 UnbreakableTailLength(0), BindingStrength(0), SplitPenalty(0),
Daniel Jasper562ecd42013-09-06 08:08:14 +0000101 LongestObjCSelectorName(0), FakeRParens(0),
102 StartsBinaryExpression(false), EndsBinaryExpression(false),
103 LastInChainOfCalls(false), PartOfMultiVariableDeclStmt(false),
Manuel Klimek71814b42013-10-11 21:25:45 +0000104 MatchingParen(NULL), Previous(NULL), Next(NULL),
105 Decision(FD_Unformatted), Finalized(false) {}
Alexander Kornienko4b672072013-06-03 16:45:03 +0000106
107 /// \brief The \c Token.
108 Token Tok;
109
110 /// \brief The number of newlines immediately before the \c Token.
111 ///
112 /// This can be used to determine what the user wrote in the original code
113 /// and thereby e.g. leave an empty line between two function definitions.
114 unsigned NewlinesBefore;
115
116 /// \brief Whether there is at least one unescaped newline before the \c
117 /// Token.
118 bool HasUnescapedNewline;
119
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000120 /// \brief The range of the whitespace immediately preceding the \c Token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000121 SourceRange WhitespaceRange;
122
123 /// \brief The offset just past the last '\n' in this token's leading
124 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
125 unsigned LastNewlineOffset;
126
Alexander Kornienko39856b72013-09-10 09:38:25 +0000127 /// \brief The width of the non-whitespace parts of the token (or its first
128 /// line for multi-line tokens) in columns.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000129 /// We need this to correctly measure number of columns a token spans.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000130 unsigned ColumnWidth;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000131
Alexander Kornienko39856b72013-09-10 09:38:25 +0000132 /// \brief Contains the width in columns of the last line of a multi-line
Alexander Kornienko632abb92013-09-02 13:58:14 +0000133 /// token.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000134 unsigned LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000135
Alexander Kornienko39856b72013-09-10 09:38:25 +0000136 /// \brief Whether the token text contains newlines (escaped or not).
137 bool IsMultiline;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000138
Alexander Kornienko4b672072013-06-03 16:45:03 +0000139 /// \brief Indicates that this is the first token.
140 bool IsFirst;
141
142 /// \brief Whether there must be a line break before this token.
143 ///
144 /// This happens for example when a preprocessor directive ended directly
145 /// before the token.
146 bool MustBreakBefore;
147
148 /// \brief Returns actual token start location without leading escaped
149 /// newlines and whitespace.
150 ///
151 /// This can be different to Tok.getLocation(), which includes leading escaped
152 /// newlines.
153 SourceLocation getStartOfNonWhitespace() const {
154 return WhitespaceRange.getEnd();
155 }
156
157 /// \brief The raw text of the token.
158 ///
159 /// Contains the raw token text without leading whitespace and without leading
160 /// escaped newlines.
161 StringRef TokenText;
162
Daniel Jasper8369aa52013-07-16 20:28:33 +0000163 /// \brief Set to \c true if this token is an unterminated literal.
164 bool IsUnterminatedLiteral;
165
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000166 /// \brief Contains the kind of block if this token is a brace.
167 BraceBlockKind BlockKind;
168
Alexander Kornienko4b672072013-06-03 16:45:03 +0000169 TokenType Type;
170
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000171 /// \brief The number of spaces that should be inserted before this token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000172 unsigned SpacesRequiredBefore;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000173
174 /// \brief \c true if it is allowed to break before this token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000175 bool CanBreakBefore;
176
177 bool ClosesTemplateDeclaration;
178
179 /// \brief Number of parameters, if this is "(", "[" or "<".
180 ///
181 /// This is initialized to 1 as we don't need to distinguish functions with
182 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
183 /// the number of commas.
184 unsigned ParameterCount;
185
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000186 /// \brief A token can have a special role that can carry extra information
187 /// about the token's formatting.
188 llvm::OwningPtr<TokenRole> Role;
189
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000190 /// \brief If this is an opening parenthesis, how are the parameters packed?
191 ParameterPackingKind PackingKind;
192
Manuel Klimek31c85922013-08-29 15:21:40 +0000193 /// \brief The total length of the unwrapped line up to and including this
194 /// token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000195 unsigned TotalLength;
196
Alexander Kornienko39856b72013-09-10 09:38:25 +0000197 /// \brief The original 0-based column of this token, including expanded tabs.
198 /// The configured TabWidth is used as tab width.
Manuel Klimek31c85922013-08-29 15:21:40 +0000199 unsigned OriginalColumn;
200
Alexander Kornienko4b672072013-06-03 16:45:03 +0000201 /// \brief The length of following tokens until the next natural split point,
202 /// or the next token that can be broken.
203 unsigned UnbreakableTailLength;
204
205 // FIXME: Come up with a 'cleaner' concept.
206 /// \brief The binding strength of a token. This is a combined value of
207 /// operator precedence, parenthesis nesting, etc.
208 unsigned BindingStrength;
209
210 /// \brief Penalty for inserting a line break before this token.
211 unsigned SplitPenalty;
212
213 /// \brief If this is the first ObjC selector name in an ObjC method
214 /// definition or call, this contains the length of the longest name.
215 unsigned LongestObjCSelectorName;
216
217 /// \brief Stores the number of required fake parentheses and the
218 /// corresponding operator precedence.
219 ///
220 /// If multiple fake parentheses start at a token, this vector stores them in
221 /// reverse order, i.e. inner fake parenthesis first.
222 SmallVector<prec::Level, 4> FakeLParens;
223 /// \brief Insert this many fake ) after this token for correct indentation.
224 unsigned FakeRParens;
225
Daniel Jasper562ecd42013-09-06 08:08:14 +0000226 /// \brief \c true if this token starts a binary expression, i.e. has at least
227 /// one fake l_paren with a precedence greater than prec::Unknown.
228 bool StartsBinaryExpression;
229 /// \brief \c true if this token ends a binary expression.
230 bool EndsBinaryExpression;
231
Alexander Kornienko4b672072013-06-03 16:45:03 +0000232 /// \brief Is this the last "." or "->" in a builder-type call?
233 bool LastInChainOfCalls;
234
235 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
236 ///
237 /// Only set if \c Type == \c TT_StartOfName.
238 bool PartOfMultiVariableDeclStmt;
239
240 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
241
242 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
243 return is(K1) || is(K2);
244 }
245
246 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
247 return is(K1) || is(K2) || is(K3);
248 }
249
250 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
251 tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
252 tok::TokenKind K6 = tok::NUM_TOKENS,
253 tok::TokenKind K7 = tok::NUM_TOKENS,
254 tok::TokenKind K8 = tok::NUM_TOKENS,
255 tok::TokenKind K9 = tok::NUM_TOKENS,
256 tok::TokenKind K10 = tok::NUM_TOKENS,
257 tok::TokenKind K11 = tok::NUM_TOKENS,
258 tok::TokenKind K12 = tok::NUM_TOKENS) const {
259 return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
260 is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
261 }
262
263 bool isNot(tok::TokenKind Kind) const { return Tok.isNot(Kind); }
264
265 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
266 return Tok.isObjCAtKeyword(Kind);
267 }
268
269 bool isAccessSpecifier(bool ColonRequired = true) const {
270 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
271 (!ColonRequired || (Next && Next->is(tok::colon)));
272 }
273
274 bool isObjCAccessSpecifier() const {
275 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
276 Next->isObjCAtKeyword(tok::objc_protected) ||
277 Next->isObjCAtKeyword(tok::objc_package) ||
278 Next->isObjCAtKeyword(tok::objc_private));
279 }
280
281 /// \brief Returns whether \p Tok is ([{ or a template opening <.
282 bool opensScope() const {
283 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
284 Type == TT_TemplateOpener;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000285 }
Nico Weber0f987a62013-06-25 19:25:12 +0000286 /// \brief Returns whether \p Tok is )]} or a template closing >.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000287 bool closesScope() const {
288 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
289 Type == TT_TemplateCloser;
290 }
291
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000292 /// \brief Returns \c true if this is a "." or "->" accessing a member.
293 bool isMemberAccess() const {
294 return isOneOf(tok::arrow, tok::period) &&
295 Type != TT_DesignatedInitializerPeriod;
296 }
297
Alexander Kornienko4b672072013-06-03 16:45:03 +0000298 bool isUnaryOperator() const {
299 switch (Tok.getKind()) {
300 case tok::plus:
301 case tok::plusplus:
302 case tok::minus:
303 case tok::minusminus:
304 case tok::exclaim:
305 case tok::tilde:
306 case tok::kw_sizeof:
307 case tok::kw_alignof:
308 return true;
309 default:
310 return false;
311 }
312 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000313
Alexander Kornienko4b672072013-06-03 16:45:03 +0000314 bool isBinaryOperator() const {
315 // Comma is a binary operator, but does not behave as such wrt. formatting.
316 return getPrecedence() > prec::Comma;
317 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000318
Alexander Kornienko4b672072013-06-03 16:45:03 +0000319 bool isTrailingComment() const {
320 return is(tok::comment) && (!Next || Next->NewlinesBefore > 0);
321 }
322
323 prec::Level getPrecedence() const {
324 return getBinOpPrecedence(Tok.getKind(), true, true);
325 }
326
327 /// \brief Returns the previous token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000328 FormatToken *getPreviousNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000329 FormatToken *Tok = Previous;
330 while (Tok != NULL && Tok->is(tok::comment))
331 Tok = Tok->Previous;
332 return Tok;
333 }
334
335 /// \brief Returns the next token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000336 const FormatToken *getNextNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000337 const FormatToken *Tok = Next;
338 while (Tok != NULL && Tok->is(tok::comment))
339 Tok = Tok->Next;
340 return Tok;
341 }
342
Daniel Jasperb8f61682013-10-22 15:45:58 +0000343 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
344 /// list that should be indented with a block indent.
345 bool opensBlockTypeList(const FormatStyle &Style) const {
346 return Type == TT_ArrayInitializerLSquare ||
347 (is(tok::l_brace) &&
Daniel Jasperb596fb22013-10-24 10:31:50 +0000348 (BlockKind == BK_Block || Type == TT_DictLiteral ||
Daniel Jasperb8f61682013-10-22 15:45:58 +0000349 !Style.Cpp11BracedListStyle));
350 }
351
352 /// \brief Same as opensBlockTypeList, but for the closing token.
Daniel Jasper1db6c382013-10-22 15:30:28 +0000353 bool closesBlockTypeList(const FormatStyle &Style) const {
Daniel Jasperb8f61682013-10-22 15:45:58 +0000354 return MatchingParen && MatchingParen->opensBlockTypeList(Style);
Daniel Jasper1db6c382013-10-22 15:30:28 +0000355 }
356
Alexander Kornienko4b672072013-06-03 16:45:03 +0000357 FormatToken *MatchingParen;
358
359 FormatToken *Previous;
360 FormatToken *Next;
361
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000362 SmallVector<AnnotatedLine *, 1> Children;
363
Manuel Klimek71814b42013-10-11 21:25:45 +0000364 /// \brief Stores the formatting decision for the token once it was made.
365 FormatDecision Decision;
366
367 /// \brief If \c true, this token has been fully formatted (indented and
368 /// potentially re-formatted inside), and we do not allow further formatting
369 /// changes.
370 bool Finalized;
371
Alexander Kornienko4b672072013-06-03 16:45:03 +0000372private:
373 // Disallow copying.
Craig Topper411294d2013-07-01 04:07:34 +0000374 FormatToken(const FormatToken &) LLVM_DELETED_FUNCTION;
375 void operator=(const FormatToken &) LLVM_DELETED_FUNCTION;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000376};
377
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000378class ContinuationIndenter;
379struct LineState;
380
381class TokenRole {
382public:
383 TokenRole(const FormatStyle &Style) : Style(Style) {}
384 virtual ~TokenRole();
385
386 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
387 /// this function precomputes required information for formatting.
388 virtual void precomputeFormattingInfos(const FormatToken *Token);
389
390 /// \brief Apply the special formatting that the given role demands.
391 ///
392 /// Continues formatting from \p State leaving indentation to \p Indenter and
393 /// returns the total penalty that this formatting incurs.
394 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
395 bool DryRun) {
396 return 0;
397 }
398
399 /// \brief Notifies the \c Role that a comma was found.
400 virtual void CommaFound(const FormatToken *Token) {}
401
402protected:
403 const FormatStyle &Style;
404};
405
406class CommaSeparatedList : public TokenRole {
407public:
408 CommaSeparatedList(const FormatStyle &Style) : TokenRole(Style) {}
409
410 virtual void precomputeFormattingInfos(const FormatToken *Token);
411
412 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
413 bool DryRun);
414
415 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
416 virtual void CommaFound(const FormatToken *Token) { Commas.push_back(Token); }
417
418private:
419 /// \brief A struct that holds information on how to format a given list with
420 /// a specific number of columns.
421 struct ColumnFormat {
422 /// \brief The number of columns to use.
423 unsigned Columns;
424
425 /// \brief The total width in characters.
426 unsigned TotalWidth;
427
428 /// \brief The number of lines required for this format.
429 unsigned LineCount;
430
431 /// \brief The size of each column in characters.
432 SmallVector<unsigned, 8> ColumnSizes;
433 };
434
435 /// \brief Calculate which \c ColumnFormat fits best into
436 /// \p RemainingCharacters.
437 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
438
439 /// \brief The ordered \c FormatTokens making up the commas of this list.
440 SmallVector<const FormatToken *, 8> Commas;
441
442 /// \brief The length of each of the list's items in characters including the
443 /// trailing comma.
444 SmallVector<unsigned, 8> ItemLengths;
445
446 /// \brief Precomputed formats that can be used for this list.
447 SmallVector<ColumnFormat, 4> Formats;
448};
449
Alexander Kornienko4b672072013-06-03 16:45:03 +0000450} // namespace format
451} // namespace clang
452
453#endif // LLVM_CLANG_FORMAT_FORMAT_TOKEN_H