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