blob: 12621027cc586fccb46d6142523017e25d234285 [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 {
28 TT_BinaryOperator,
Alexander Kornienko60d1b042013-10-10 13:36:20 +000029 TT_BitFieldColon,
Alexander Kornienko4b672072013-06-03 16:45:03 +000030 TT_BlockComment,
31 TT_CastRParen,
32 TT_ConditionalExpr,
33 TT_CtorInitializerColon,
Daniel Jaspere33d4af2013-07-26 16:56:36 +000034 TT_CtorInitializerComma,
Alexander Kornienko4b672072013-06-03 16:45:03 +000035 TT_DesignatedInitializerPeriod,
36 TT_ImplicitStringLiteral,
37 TT_InlineASMColon,
38 TT_InheritanceColon,
39 TT_FunctionTypeLParen,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000040 TT_LambdaLSquare,
Alexander Kornienko4b672072013-06-03 16:45:03 +000041 TT_LineComment,
42 TT_ObjCArrayLiteral,
43 TT_ObjCBlockLParen,
44 TT_ObjCDecl,
45 TT_ObjCDictLiteral,
46 TT_ObjCForIn,
47 TT_ObjCMethodExpr,
48 TT_ObjCMethodSpecifier,
49 TT_ObjCProperty,
50 TT_ObjCSelectorName,
51 TT_OverloadedOperator,
52 TT_OverloadedOperatorLParen,
53 TT_PointerOrReference,
54 TT_PureVirtualSpecifier,
55 TT_RangeBasedForLoopColon,
56 TT_StartOfName,
57 TT_TemplateCloser,
58 TT_TemplateOpener,
Daniel Jasper6cdec7c2013-07-09 14:36:48 +000059 TT_TrailingReturnArrow,
Alexander Kornienko4b672072013-06-03 16:45:03 +000060 TT_TrailingUnaryOperator,
61 TT_UnaryOperator,
62 TT_Unknown
63};
64
Daniel Jasperb1f74a82013-07-09 09:06:29 +000065// Represents what type of block a set of braces open.
66enum BraceBlockKind {
67 BK_Unknown,
68 BK_Block,
69 BK_BracedInit
70};
71
Daniel Jasperb10cbc42013-07-10 14:02:49 +000072// The packing kind of a function's parameters.
73enum ParameterPackingKind {
74 PPK_BinPacked,
75 PPK_OnePerLine,
76 PPK_Inconclusive
77};
78
Manuel Klimek71814b42013-10-11 21:25:45 +000079enum FormatDecision {
80 FD_Unformatted,
81 FD_Continue,
82 FD_Break
83};
84
Daniel Jasper8de9ed02013-08-22 15:00:41 +000085class TokenRole;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000086class AnnotatedLine;
Daniel Jasper8de9ed02013-08-22 15:00:41 +000087
Alexander Kornienko4b672072013-06-03 16:45:03 +000088/// \brief A wrapper around a \c Token storing information about the
89/// whitespace characters preceeding it.
90struct FormatToken {
91 FormatToken()
Alexander Kornienko632abb92013-09-02 13:58:14 +000092 : NewlinesBefore(0), HasUnescapedNewline(false), LastNewlineOffset(0),
Alexander Kornienko39856b72013-09-10 09:38:25 +000093 ColumnWidth(0), LastLineColumnWidth(0), IsMultiline(false),
Alexander Kornienko632abb92013-09-02 13:58:14 +000094 IsFirst(false), MustBreakBefore(false), IsUnterminatedLiteral(false),
Alexander Kornienkod7b837e2013-08-29 17:32:57 +000095 BlockKind(BK_Unknown), Type(TT_Unknown), SpacesRequiredBefore(0),
96 CanBreakBefore(false), ClosesTemplateDeclaration(false),
97 ParameterCount(0), PackingKind(PPK_Inconclusive), TotalLength(0),
98 UnbreakableTailLength(0), BindingStrength(0), SplitPenalty(0),
Daniel Jasper562ecd42013-09-06 08:08:14 +000099 LongestObjCSelectorName(0), FakeRParens(0),
100 StartsBinaryExpression(false), EndsBinaryExpression(false),
101 LastInChainOfCalls(false), PartOfMultiVariableDeclStmt(false),
Manuel Klimek71814b42013-10-11 21:25:45 +0000102 MatchingParen(NULL), Previous(NULL), Next(NULL),
103 Decision(FD_Unformatted), Finalized(false) {}
Alexander Kornienko4b672072013-06-03 16:45:03 +0000104
105 /// \brief The \c Token.
106 Token Tok;
107
108 /// \brief The number of newlines immediately before the \c Token.
109 ///
110 /// This can be used to determine what the user wrote in the original code
111 /// and thereby e.g. leave an empty line between two function definitions.
112 unsigned NewlinesBefore;
113
114 /// \brief Whether there is at least one unescaped newline before the \c
115 /// Token.
116 bool HasUnescapedNewline;
117
118 /// \brief The range of the whitespace immediately preceeding the \c Token.
119 SourceRange WhitespaceRange;
120
121 /// \brief The offset just past the last '\n' in this token's leading
122 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
123 unsigned LastNewlineOffset;
124
Alexander Kornienko39856b72013-09-10 09:38:25 +0000125 /// \brief The width of the non-whitespace parts of the token (or its first
126 /// line for multi-line tokens) in columns.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000127 /// We need this to correctly measure number of columns a token spans.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000128 unsigned ColumnWidth;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000129
Alexander Kornienko39856b72013-09-10 09:38:25 +0000130 /// \brief Contains the width in columns of the last line of a multi-line
Alexander Kornienko632abb92013-09-02 13:58:14 +0000131 /// token.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000132 unsigned LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000133
Alexander Kornienko39856b72013-09-10 09:38:25 +0000134 /// \brief Whether the token text contains newlines (escaped or not).
135 bool IsMultiline;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000136
Alexander Kornienko4b672072013-06-03 16:45:03 +0000137 /// \brief Indicates that this is the first token.
138 bool IsFirst;
139
140 /// \brief Whether there must be a line break before this token.
141 ///
142 /// This happens for example when a preprocessor directive ended directly
143 /// before the token.
144 bool MustBreakBefore;
145
146 /// \brief Returns actual token start location without leading escaped
147 /// newlines and whitespace.
148 ///
149 /// This can be different to Tok.getLocation(), which includes leading escaped
150 /// newlines.
151 SourceLocation getStartOfNonWhitespace() const {
152 return WhitespaceRange.getEnd();
153 }
154
155 /// \brief The raw text of the token.
156 ///
157 /// Contains the raw token text without leading whitespace and without leading
158 /// escaped newlines.
159 StringRef TokenText;
160
Daniel Jasper8369aa52013-07-16 20:28:33 +0000161 /// \brief Set to \c true if this token is an unterminated literal.
162 bool IsUnterminatedLiteral;
163
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000164 /// \brief Contains the kind of block if this token is a brace.
165 BraceBlockKind BlockKind;
166
Alexander Kornienko4b672072013-06-03 16:45:03 +0000167 TokenType Type;
168
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000169 /// \brief The number of spaces that should be inserted before this token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000170 unsigned SpacesRequiredBefore;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000171
172 /// \brief \c true if it is allowed to break before this token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000173 bool CanBreakBefore;
174
175 bool ClosesTemplateDeclaration;
176
177 /// \brief Number of parameters, if this is "(", "[" or "<".
178 ///
179 /// This is initialized to 1 as we don't need to distinguish functions with
180 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
181 /// the number of commas.
182 unsigned ParameterCount;
183
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000184 /// \brief A token can have a special role that can carry extra information
185 /// about the token's formatting.
186 llvm::OwningPtr<TokenRole> Role;
187
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000188 /// \brief If this is an opening parenthesis, how are the parameters packed?
189 ParameterPackingKind PackingKind;
190
Manuel Klimek31c85922013-08-29 15:21:40 +0000191 /// \brief The total length of the unwrapped line up to and including this
192 /// token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000193 unsigned TotalLength;
194
Alexander Kornienko39856b72013-09-10 09:38:25 +0000195 /// \brief The original 0-based column of this token, including expanded tabs.
196 /// The configured TabWidth is used as tab width.
Manuel Klimek31c85922013-08-29 15:21:40 +0000197 unsigned OriginalColumn;
198
Alexander Kornienko4b672072013-06-03 16:45:03 +0000199 /// \brief The length of following tokens until the next natural split point,
200 /// or the next token that can be broken.
201 unsigned UnbreakableTailLength;
202
203 // FIXME: Come up with a 'cleaner' concept.
204 /// \brief The binding strength of a token. This is a combined value of
205 /// operator precedence, parenthesis nesting, etc.
206 unsigned BindingStrength;
207
208 /// \brief Penalty for inserting a line break before this token.
209 unsigned SplitPenalty;
210
211 /// \brief If this is the first ObjC selector name in an ObjC method
212 /// definition or call, this contains the length of the longest name.
213 unsigned LongestObjCSelectorName;
214
215 /// \brief Stores the number of required fake parentheses and the
216 /// corresponding operator precedence.
217 ///
218 /// If multiple fake parentheses start at a token, this vector stores them in
219 /// reverse order, i.e. inner fake parenthesis first.
220 SmallVector<prec::Level, 4> FakeLParens;
221 /// \brief Insert this many fake ) after this token for correct indentation.
222 unsigned FakeRParens;
223
Daniel Jasper562ecd42013-09-06 08:08:14 +0000224 /// \brief \c true if this token starts a binary expression, i.e. has at least
225 /// one fake l_paren with a precedence greater than prec::Unknown.
226 bool StartsBinaryExpression;
227 /// \brief \c true if this token ends a binary expression.
228 bool EndsBinaryExpression;
229
Alexander Kornienko4b672072013-06-03 16:45:03 +0000230 /// \brief Is this the last "." or "->" in a builder-type call?
231 bool LastInChainOfCalls;
232
233 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
234 ///
235 /// Only set if \c Type == \c TT_StartOfName.
236 bool PartOfMultiVariableDeclStmt;
237
238 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
239
240 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
241 return is(K1) || is(K2);
242 }
243
244 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
245 return is(K1) || is(K2) || is(K3);
246 }
247
248 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
249 tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
250 tok::TokenKind K6 = tok::NUM_TOKENS,
251 tok::TokenKind K7 = tok::NUM_TOKENS,
252 tok::TokenKind K8 = tok::NUM_TOKENS,
253 tok::TokenKind K9 = tok::NUM_TOKENS,
254 tok::TokenKind K10 = tok::NUM_TOKENS,
255 tok::TokenKind K11 = tok::NUM_TOKENS,
256 tok::TokenKind K12 = tok::NUM_TOKENS) const {
257 return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
258 is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
259 }
260
261 bool isNot(tok::TokenKind Kind) const { return Tok.isNot(Kind); }
262
263 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
264 return Tok.isObjCAtKeyword(Kind);
265 }
266
267 bool isAccessSpecifier(bool ColonRequired = true) const {
268 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
269 (!ColonRequired || (Next && Next->is(tok::colon)));
270 }
271
272 bool isObjCAccessSpecifier() const {
273 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
274 Next->isObjCAtKeyword(tok::objc_protected) ||
275 Next->isObjCAtKeyword(tok::objc_package) ||
276 Next->isObjCAtKeyword(tok::objc_private));
277 }
278
279 /// \brief Returns whether \p Tok is ([{ or a template opening <.
280 bool opensScope() const {
281 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
282 Type == TT_TemplateOpener;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000283 }
Nico Weber0f987a62013-06-25 19:25:12 +0000284 /// \brief Returns whether \p Tok is )]} or a template closing >.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000285 bool closesScope() const {
286 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
287 Type == TT_TemplateCloser;
288 }
289
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000290 /// \brief Returns \c true if this is a "." or "->" accessing a member.
291 bool isMemberAccess() const {
292 return isOneOf(tok::arrow, tok::period) &&
293 Type != TT_DesignatedInitializerPeriod;
294 }
295
Alexander Kornienko4b672072013-06-03 16:45:03 +0000296 bool isUnaryOperator() const {
297 switch (Tok.getKind()) {
298 case tok::plus:
299 case tok::plusplus:
300 case tok::minus:
301 case tok::minusminus:
302 case tok::exclaim:
303 case tok::tilde:
304 case tok::kw_sizeof:
305 case tok::kw_alignof:
306 return true;
307 default:
308 return false;
309 }
310 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000311
Alexander Kornienko4b672072013-06-03 16:45:03 +0000312 bool isBinaryOperator() const {
313 // Comma is a binary operator, but does not behave as such wrt. formatting.
314 return getPrecedence() > prec::Comma;
315 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000316
Alexander Kornienko4b672072013-06-03 16:45:03 +0000317 bool isTrailingComment() const {
318 return is(tok::comment) && (!Next || Next->NewlinesBefore > 0);
319 }
320
321 prec::Level getPrecedence() const {
322 return getBinOpPrecedence(Tok.getKind(), true, true);
323 }
324
325 /// \brief Returns the previous token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000326 FormatToken *getPreviousNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000327 FormatToken *Tok = Previous;
328 while (Tok != NULL && Tok->is(tok::comment))
329 Tok = Tok->Previous;
330 return Tok;
331 }
332
333 /// \brief Returns the next token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000334 const FormatToken *getNextNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000335 const FormatToken *Tok = Next;
336 while (Tok != NULL && Tok->is(tok::comment))
337 Tok = Tok->Next;
338 return Tok;
339 }
340
341 FormatToken *MatchingParen;
342
343 FormatToken *Previous;
344 FormatToken *Next;
345
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000346 SmallVector<AnnotatedLine *, 1> Children;
347
Manuel Klimek71814b42013-10-11 21:25:45 +0000348 /// \brief Stores the formatting decision for the token once it was made.
349 FormatDecision Decision;
350
351 /// \brief If \c true, this token has been fully formatted (indented and
352 /// potentially re-formatted inside), and we do not allow further formatting
353 /// changes.
354 bool Finalized;
355
Alexander Kornienko4b672072013-06-03 16:45:03 +0000356private:
357 // Disallow copying.
Craig Topper411294d2013-07-01 04:07:34 +0000358 FormatToken(const FormatToken &) LLVM_DELETED_FUNCTION;
359 void operator=(const FormatToken &) LLVM_DELETED_FUNCTION;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000360};
361
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000362class ContinuationIndenter;
363struct LineState;
364
365class TokenRole {
366public:
367 TokenRole(const FormatStyle &Style) : Style(Style) {}
368 virtual ~TokenRole();
369
370 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
371 /// this function precomputes required information for formatting.
372 virtual void precomputeFormattingInfos(const FormatToken *Token);
373
374 /// \brief Apply the special formatting that the given role demands.
375 ///
376 /// Continues formatting from \p State leaving indentation to \p Indenter and
377 /// returns the total penalty that this formatting incurs.
378 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
379 bool DryRun) {
380 return 0;
381 }
382
383 /// \brief Notifies the \c Role that a comma was found.
384 virtual void CommaFound(const FormatToken *Token) {}
385
386protected:
387 const FormatStyle &Style;
388};
389
390class CommaSeparatedList : public TokenRole {
391public:
392 CommaSeparatedList(const FormatStyle &Style) : TokenRole(Style) {}
393
394 virtual void precomputeFormattingInfos(const FormatToken *Token);
395
396 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
397 bool DryRun);
398
399 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
400 virtual void CommaFound(const FormatToken *Token) { Commas.push_back(Token); }
401
402private:
403 /// \brief A struct that holds information on how to format a given list with
404 /// a specific number of columns.
405 struct ColumnFormat {
406 /// \brief The number of columns to use.
407 unsigned Columns;
408
409 /// \brief The total width in characters.
410 unsigned TotalWidth;
411
412 /// \brief The number of lines required for this format.
413 unsigned LineCount;
414
415 /// \brief The size of each column in characters.
416 SmallVector<unsigned, 8> ColumnSizes;
417 };
418
419 /// \brief Calculate which \c ColumnFormat fits best into
420 /// \p RemainingCharacters.
421 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
422
423 /// \brief The ordered \c FormatTokens making up the commas of this list.
424 SmallVector<const FormatToken *, 8> Commas;
425
426 /// \brief The length of each of the list's items in characters including the
427 /// trailing comma.
428 SmallVector<unsigned, 8> ItemLengths;
429
430 /// \brief Precomputed formats that can be used for this list.
431 SmallVector<ColumnFormat, 4> Formats;
432};
433
Alexander Kornienko4b672072013-06-03 16:45:03 +0000434} // namespace format
435} // namespace clang
436
437#endif // LLVM_CLANG_FORMAT_FORMAT_TOKEN_H