blob: e4342dd1317789533ac9a55df8b93905e6520b7b [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),
92 LongestObjCSelectorName(0), FakeRParens(0), LastInChainOfCalls(false),
Alexander Kornienko4b672072013-06-03 16:45:03 +000093 PartOfMultiVariableDeclStmt(false), MatchingParen(NULL), Previous(NULL),
94 Next(NULL) {}
95
96 /// \brief The \c Token.
97 Token Tok;
98
99 /// \brief The number of newlines immediately before the \c Token.
100 ///
101 /// This can be used to determine what the user wrote in the original code
102 /// and thereby e.g. leave an empty line between two function definitions.
103 unsigned NewlinesBefore;
104
105 /// \brief Whether there is at least one unescaped newline before the \c
106 /// Token.
107 bool HasUnescapedNewline;
108
109 /// \brief The range of the whitespace immediately preceeding the \c Token.
110 SourceRange WhitespaceRange;
111
112 /// \brief The offset just past the last '\n' in this token's leading
113 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
114 unsigned LastNewlineOffset;
115
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000116 /// \brief The length of the non-whitespace parts of the token in CodePoints.
117 /// We need this to correctly measure number of columns a token spans.
118 unsigned CodePointCount;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000119
Alexander Kornienko632abb92013-09-02 13:58:14 +0000120 /// \brief Contains the number of code points in the first line of a
121 /// multi-line string literal or comment. Zero if there's no newline in the
122 /// token.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000123 unsigned FirstLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000124
125 /// \brief Contains the number of code points in the last line of a
126 /// multi-line string literal or comment. Can be zero for line comments.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000127 unsigned LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000128
129 /// \brief Returns \c true if the token text contains newlines (escaped or
130 /// not).
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000131 bool isMultiline() const { return FirstLineColumnWidth != 0; }
Alexander Kornienko632abb92013-09-02 13:58:14 +0000132
Alexander Kornienko4b672072013-06-03 16:45:03 +0000133 /// \brief Indicates that this is the first token.
134 bool IsFirst;
135
136 /// \brief Whether there must be a line break before this token.
137 ///
138 /// This happens for example when a preprocessor directive ended directly
139 /// before the token.
140 bool MustBreakBefore;
141
142 /// \brief Returns actual token start location without leading escaped
143 /// newlines and whitespace.
144 ///
145 /// This can be different to Tok.getLocation(), which includes leading escaped
146 /// newlines.
147 SourceLocation getStartOfNonWhitespace() const {
148 return WhitespaceRange.getEnd();
149 }
150
151 /// \brief The raw text of the token.
152 ///
153 /// Contains the raw token text without leading whitespace and without leading
154 /// escaped newlines.
155 StringRef TokenText;
156
Daniel Jasper8369aa52013-07-16 20:28:33 +0000157 /// \brief Set to \c true if this token is an unterminated literal.
158 bool IsUnterminatedLiteral;
159
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000160 /// \brief Contains the kind of block if this token is a brace.
161 BraceBlockKind BlockKind;
162
Alexander Kornienko4b672072013-06-03 16:45:03 +0000163 TokenType Type;
164
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000165 /// \brief The number of spaces that should be inserted before this token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000166 unsigned SpacesRequiredBefore;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000167
168 /// \brief \c true if it is allowed to break before this token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000169 bool CanBreakBefore;
170
171 bool ClosesTemplateDeclaration;
172
173 /// \brief Number of parameters, if this is "(", "[" or "<".
174 ///
175 /// This is initialized to 1 as we don't need to distinguish functions with
176 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
177 /// the number of commas.
178 unsigned ParameterCount;
179
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000180 /// \brief A token can have a special role that can carry extra information
181 /// about the token's formatting.
182 llvm::OwningPtr<TokenRole> Role;
183
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000184 /// \brief If this is an opening parenthesis, how are the parameters packed?
185 ParameterPackingKind PackingKind;
186
Manuel Klimek31c85922013-08-29 15:21:40 +0000187 /// \brief The total length of the unwrapped line up to and including this
188 /// token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000189 unsigned TotalLength;
190
Manuel Klimek31c85922013-08-29 15:21:40 +0000191 /// \brief The original column of this token, including expanded tabs.
192 /// The configured IndentWidth is used as tab width. Only tabs in whitespace
193 /// are expanded.
194 /// FIXME: This is currently only used on the first token of an unwrapped
195 /// line, and the implementation is not correct for other tokens (see the
196 /// FIXMEs in FormatTokenLexer::getNextToken()).
197 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
224 /// \brief Is this the last "." or "->" in a builder-type call?
225 bool LastInChainOfCalls;
226
227 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
228 ///
229 /// Only set if \c Type == \c TT_StartOfName.
230 bool PartOfMultiVariableDeclStmt;
231
232 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
233
234 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
235 return is(K1) || is(K2);
236 }
237
238 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
239 return is(K1) || is(K2) || is(K3);
240 }
241
242 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
243 tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
244 tok::TokenKind K6 = tok::NUM_TOKENS,
245 tok::TokenKind K7 = tok::NUM_TOKENS,
246 tok::TokenKind K8 = tok::NUM_TOKENS,
247 tok::TokenKind K9 = tok::NUM_TOKENS,
248 tok::TokenKind K10 = tok::NUM_TOKENS,
249 tok::TokenKind K11 = tok::NUM_TOKENS,
250 tok::TokenKind K12 = tok::NUM_TOKENS) const {
251 return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
252 is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
253 }
254
255 bool isNot(tok::TokenKind Kind) const { return Tok.isNot(Kind); }
256
257 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
258 return Tok.isObjCAtKeyword(Kind);
259 }
260
261 bool isAccessSpecifier(bool ColonRequired = true) const {
262 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
263 (!ColonRequired || (Next && Next->is(tok::colon)));
264 }
265
266 bool isObjCAccessSpecifier() const {
267 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
268 Next->isObjCAtKeyword(tok::objc_protected) ||
269 Next->isObjCAtKeyword(tok::objc_package) ||
270 Next->isObjCAtKeyword(tok::objc_private));
271 }
272
273 /// \brief Returns whether \p Tok is ([{ or a template opening <.
274 bool opensScope() const {
275 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
276 Type == TT_TemplateOpener;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000277 }
Nico Weber0f987a62013-06-25 19:25:12 +0000278 /// \brief Returns whether \p Tok is )]} or a template closing >.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000279 bool closesScope() const {
280 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
281 Type == TT_TemplateCloser;
282 }
283
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000284 /// \brief Returns \c true if this is a "." or "->" accessing a member.
285 bool isMemberAccess() const {
286 return isOneOf(tok::arrow, tok::period) &&
287 Type != TT_DesignatedInitializerPeriod;
288 }
289
Alexander Kornienko4b672072013-06-03 16:45:03 +0000290 bool isUnaryOperator() const {
291 switch (Tok.getKind()) {
292 case tok::plus:
293 case tok::plusplus:
294 case tok::minus:
295 case tok::minusminus:
296 case tok::exclaim:
297 case tok::tilde:
298 case tok::kw_sizeof:
299 case tok::kw_alignof:
300 return true;
301 default:
302 return false;
303 }
304 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000305
Alexander Kornienko4b672072013-06-03 16:45:03 +0000306 bool isBinaryOperator() const {
307 // Comma is a binary operator, but does not behave as such wrt. formatting.
308 return getPrecedence() > prec::Comma;
309 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000310
Alexander Kornienko4b672072013-06-03 16:45:03 +0000311 bool isTrailingComment() const {
312 return is(tok::comment) && (!Next || Next->NewlinesBefore > 0);
313 }
314
315 prec::Level getPrecedence() const {
316 return getBinOpPrecedence(Tok.getKind(), true, true);
317 }
318
319 /// \brief Returns the previous token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000320 FormatToken *getPreviousNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000321 FormatToken *Tok = Previous;
322 while (Tok != NULL && Tok->is(tok::comment))
323 Tok = Tok->Previous;
324 return Tok;
325 }
326
327 /// \brief Returns the next token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000328 const FormatToken *getNextNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000329 const FormatToken *Tok = Next;
330 while (Tok != NULL && Tok->is(tok::comment))
331 Tok = Tok->Next;
332 return Tok;
333 }
334
335 FormatToken *MatchingParen;
336
337 FormatToken *Previous;
338 FormatToken *Next;
339
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000340 SmallVector<AnnotatedLine *, 1> Children;
341
Alexander Kornienko4b672072013-06-03 16:45:03 +0000342private:
343 // Disallow copying.
Craig Topper411294d2013-07-01 04:07:34 +0000344 FormatToken(const FormatToken &) LLVM_DELETED_FUNCTION;
345 void operator=(const FormatToken &) LLVM_DELETED_FUNCTION;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000346};
347
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000348class ContinuationIndenter;
349struct LineState;
350
351class TokenRole {
352public:
353 TokenRole(const FormatStyle &Style) : Style(Style) {}
354 virtual ~TokenRole();
355
356 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
357 /// this function precomputes required information for formatting.
358 virtual void precomputeFormattingInfos(const FormatToken *Token);
359
360 /// \brief Apply the special formatting that the given role demands.
361 ///
362 /// Continues formatting from \p State leaving indentation to \p Indenter and
363 /// returns the total penalty that this formatting incurs.
364 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
365 bool DryRun) {
366 return 0;
367 }
368
369 /// \brief Notifies the \c Role that a comma was found.
370 virtual void CommaFound(const FormatToken *Token) {}
371
372protected:
373 const FormatStyle &Style;
374};
375
376class CommaSeparatedList : public TokenRole {
377public:
378 CommaSeparatedList(const FormatStyle &Style) : TokenRole(Style) {}
379
380 virtual void precomputeFormattingInfos(const FormatToken *Token);
381
382 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
383 bool DryRun);
384
385 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
386 virtual void CommaFound(const FormatToken *Token) { Commas.push_back(Token); }
387
388private:
389 /// \brief A struct that holds information on how to format a given list with
390 /// a specific number of columns.
391 struct ColumnFormat {
392 /// \brief The number of columns to use.
393 unsigned Columns;
394
395 /// \brief The total width in characters.
396 unsigned TotalWidth;
397
398 /// \brief The number of lines required for this format.
399 unsigned LineCount;
400
401 /// \brief The size of each column in characters.
402 SmallVector<unsigned, 8> ColumnSizes;
403 };
404
405 /// \brief Calculate which \c ColumnFormat fits best into
406 /// \p RemainingCharacters.
407 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
408
409 /// \brief The ordered \c FormatTokens making up the commas of this list.
410 SmallVector<const FormatToken *, 8> Commas;
411
412 /// \brief The length of each of the list's items in characters including the
413 /// trailing comma.
414 SmallVector<unsigned, 8> ItemLengths;
415
416 /// \brief Precomputed formats that can be used for this list.
417 SmallVector<ColumnFormat, 4> Formats;
418};
419
Alexander Kornienko4b672072013-06-03 16:45:03 +0000420} // namespace format
421} // namespace clang
422
423#endif // LLVM_CLANG_FORMAT_FORMAT_TOKEN_H