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