blob: fd1bd7e1cf863f1bf5c522766704db26cf31d075 [file] [log] [blame]
Alexander Kornienko3b711552013-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"
20#include "clang/Lex/Lexer.h"
21
22namespace clang {
23namespace format {
24
25enum TokenType {
26 TT_BinaryOperator,
27 TT_BlockComment,
28 TT_CastRParen,
29 TT_ConditionalExpr,
30 TT_CtorInitializerColon,
31 TT_DesignatedInitializerPeriod,
32 TT_ImplicitStringLiteral,
33 TT_InlineASMColon,
34 TT_InheritanceColon,
35 TT_FunctionTypeLParen,
36 TT_LineComment,
37 TT_ObjCArrayLiteral,
38 TT_ObjCBlockLParen,
39 TT_ObjCDecl,
40 TT_ObjCDictLiteral,
41 TT_ObjCForIn,
42 TT_ObjCMethodExpr,
43 TT_ObjCMethodSpecifier,
44 TT_ObjCProperty,
45 TT_ObjCSelectorName,
46 TT_OverloadedOperator,
47 TT_OverloadedOperatorLParen,
48 TT_PointerOrReference,
49 TT_PureVirtualSpecifier,
50 TT_RangeBasedForLoopColon,
51 TT_StartOfName,
52 TT_TemplateCloser,
53 TT_TemplateOpener,
54 TT_TrailingUnaryOperator,
55 TT_UnaryOperator,
56 TT_Unknown
57};
58
59/// \brief A wrapper around a \c Token storing information about the
60/// whitespace characters preceeding it.
61struct FormatToken {
62 FormatToken()
63 : NewlinesBefore(0), HasUnescapedNewline(false), LastNewlineOffset(0),
Alexander Kornienko00895102013-06-05 14:09:10 +000064 ByteCount(0), CodePointCount(0), IsFirst(false),
65 MustBreakBefore(false), Type(TT_Unknown), SpacesRequiredBefore(0),
66 CanBreakBefore(false), ClosesTemplateDeclaration(false),
67 ParameterCount(0), TotalLength(0), UnbreakableTailLength(0),
68 BindingStrength(0), SplitPenalty(0), LongestObjCSelectorName(0),
69 FakeRParens(0), LastInChainOfCalls(false),
Alexander Kornienko3b711552013-06-03 16:45:03 +000070 PartOfMultiVariableDeclStmt(false), MatchingParen(NULL), Previous(NULL),
71 Next(NULL) {}
72
73 /// \brief The \c Token.
74 Token Tok;
75
76 /// \brief The number of newlines immediately before the \c Token.
77 ///
78 /// This can be used to determine what the user wrote in the original code
79 /// and thereby e.g. leave an empty line between two function definitions.
80 unsigned NewlinesBefore;
81
82 /// \brief Whether there is at least one unescaped newline before the \c
83 /// Token.
84 bool HasUnescapedNewline;
85
86 /// \brief The range of the whitespace immediately preceeding the \c Token.
87 SourceRange WhitespaceRange;
88
89 /// \brief The offset just past the last '\n' in this token's leading
90 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
91 unsigned LastNewlineOffset;
92
Alexander Kornienko00895102013-06-05 14:09:10 +000093 /// \brief The number of bytes of the non-whitespace parts of the token. This
94 /// is necessary because we need to handle escaped newlines that are stored
Alexander Kornienko3b711552013-06-03 16:45:03 +000095 /// with the token.
Alexander Kornienko00895102013-06-05 14:09:10 +000096 unsigned ByteCount;
97
98 /// \brief The length of the non-whitespace parts of the token in CodePoints.
99 /// We need this to correctly measure number of columns a token spans.
100 unsigned CodePointCount;
Alexander Kornienko3b711552013-06-03 16:45:03 +0000101
102 /// \brief Indicates that this is the first token.
103 bool IsFirst;
104
105 /// \brief Whether there must be a line break before this token.
106 ///
107 /// This happens for example when a preprocessor directive ended directly
108 /// before the token.
109 bool MustBreakBefore;
110
111 /// \brief Returns actual token start location without leading escaped
112 /// newlines and whitespace.
113 ///
114 /// This can be different to Tok.getLocation(), which includes leading escaped
115 /// newlines.
116 SourceLocation getStartOfNonWhitespace() const {
117 return WhitespaceRange.getEnd();
118 }
119
120 /// \brief The raw text of the token.
121 ///
122 /// Contains the raw token text without leading whitespace and without leading
123 /// escaped newlines.
124 StringRef TokenText;
125
126 TokenType Type;
127
128 unsigned SpacesRequiredBefore;
129 bool CanBreakBefore;
130
131 bool ClosesTemplateDeclaration;
132
133 /// \brief Number of parameters, if this is "(", "[" or "<".
134 ///
135 /// This is initialized to 1 as we don't need to distinguish functions with
136 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
137 /// the number of commas.
138 unsigned ParameterCount;
139
140 /// \brief The total length of the line up to and including this token.
141 unsigned TotalLength;
142
143 /// \brief The length of following tokens until the next natural split point,
144 /// or the next token that can be broken.
145 unsigned UnbreakableTailLength;
146
147 // FIXME: Come up with a 'cleaner' concept.
148 /// \brief The binding strength of a token. This is a combined value of
149 /// operator precedence, parenthesis nesting, etc.
150 unsigned BindingStrength;
151
152 /// \brief Penalty for inserting a line break before this token.
153 unsigned SplitPenalty;
154
155 /// \brief If this is the first ObjC selector name in an ObjC method
156 /// definition or call, this contains the length of the longest name.
157 unsigned LongestObjCSelectorName;
158
159 /// \brief Stores the number of required fake parentheses and the
160 /// corresponding operator precedence.
161 ///
162 /// If multiple fake parentheses start at a token, this vector stores them in
163 /// reverse order, i.e. inner fake parenthesis first.
164 SmallVector<prec::Level, 4> FakeLParens;
165 /// \brief Insert this many fake ) after this token for correct indentation.
166 unsigned FakeRParens;
167
168 /// \brief Is this the last "." or "->" in a builder-type call?
169 bool LastInChainOfCalls;
170
171 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
172 ///
173 /// Only set if \c Type == \c TT_StartOfName.
174 bool PartOfMultiVariableDeclStmt;
175
176 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
177
178 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
179 return is(K1) || is(K2);
180 }
181
182 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
183 return is(K1) || is(K2) || is(K3);
184 }
185
186 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
187 tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
188 tok::TokenKind K6 = tok::NUM_TOKENS,
189 tok::TokenKind K7 = tok::NUM_TOKENS,
190 tok::TokenKind K8 = tok::NUM_TOKENS,
191 tok::TokenKind K9 = tok::NUM_TOKENS,
192 tok::TokenKind K10 = tok::NUM_TOKENS,
193 tok::TokenKind K11 = tok::NUM_TOKENS,
194 tok::TokenKind K12 = tok::NUM_TOKENS) const {
195 return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
196 is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
197 }
198
199 bool isNot(tok::TokenKind Kind) const { return Tok.isNot(Kind); }
200
201 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
202 return Tok.isObjCAtKeyword(Kind);
203 }
204
205 bool isAccessSpecifier(bool ColonRequired = true) const {
206 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
207 (!ColonRequired || (Next && Next->is(tok::colon)));
208 }
209
210 bool isObjCAccessSpecifier() const {
211 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
212 Next->isObjCAtKeyword(tok::objc_protected) ||
213 Next->isObjCAtKeyword(tok::objc_package) ||
214 Next->isObjCAtKeyword(tok::objc_private));
215 }
216
217 /// \brief Returns whether \p Tok is ([{ or a template opening <.
218 bool opensScope() const {
219 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
220 Type == TT_TemplateOpener;
221
222 }
223 /// \brief Returns whether \p Tok is )]} or a template opening >.
224 bool closesScope() const {
225 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
226 Type == TT_TemplateCloser;
227 }
228
229 bool isUnaryOperator() const {
230 switch (Tok.getKind()) {
231 case tok::plus:
232 case tok::plusplus:
233 case tok::minus:
234 case tok::minusminus:
235 case tok::exclaim:
236 case tok::tilde:
237 case tok::kw_sizeof:
238 case tok::kw_alignof:
239 return true;
240 default:
241 return false;
242 }
243 }
244 bool isBinaryOperator() const {
245 // Comma is a binary operator, but does not behave as such wrt. formatting.
246 return getPrecedence() > prec::Comma;
247 }
248 bool isTrailingComment() const {
249 return is(tok::comment) && (!Next || Next->NewlinesBefore > 0);
250 }
251
252 prec::Level getPrecedence() const {
253 return getBinOpPrecedence(Tok.getKind(), true, true);
254 }
255
256 /// \brief Returns the previous token ignoring comments.
257 FormatToken *getPreviousNoneComment() const {
258 FormatToken *Tok = Previous;
259 while (Tok != NULL && Tok->is(tok::comment))
260 Tok = Tok->Previous;
261 return Tok;
262 }
263
264 /// \brief Returns the next token ignoring comments.
265 const FormatToken *getNextNoneComment() const {
266 const FormatToken *Tok = Next;
267 while (Tok != NULL && Tok->is(tok::comment))
268 Tok = Tok->Next;
269 return Tok;
270 }
271
272 FormatToken *MatchingParen;
273
274 FormatToken *Previous;
275 FormatToken *Next;
276
277private:
278 // Disallow copying.
279 FormatToken(const FormatToken &);
280 void operator=(const FormatToken &);
281};
282
283} // namespace format
284} // namespace clang
285
286#endif // LLVM_CLANG_FORMAT_FORMAT_TOKEN_H