blob: 227dd523960579901df18b98d4c4200b4fd5b569 [file] [log] [blame]
Daniel Jasper32d28ee2013-01-29 21:01:14 +00001//===--- TokenAnnotator.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 implements a token annotator, i.e. creates
12/// \c AnnotatedTokens out of \c FormatTokens with required extra information.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_FORMAT_TOKEN_ANNOTATOR_H
17#define LLVM_CLANG_FORMAT_TOKEN_ANNOTATOR_H
18
19#include "UnwrappedLineParser.h"
20#include "clang/Basic/OperatorPrecedence.h"
21#include "clang/Format/Format.h"
22#include <string>
23
24namespace clang {
25class Lexer;
26class SourceManager;
27
28namespace format {
29
30enum TokenType {
31 TT_BinaryOperator,
32 TT_BlockComment,
33 TT_CastRParen,
34 TT_ConditionalExpr,
35 TT_CtorInitializerColon,
36 TT_ImplicitStringLiteral,
Daniel Jasper923ebef2013-03-14 13:45:21 +000037 TT_InlineASMColon,
Daniel Jasper6cabab42013-02-14 08:42:54 +000038 TT_InheritanceColon,
Daniel Jasper32d28ee2013-01-29 21:01:14 +000039 TT_LineComment,
Nico Weber051860e2013-02-10 02:08:05 +000040 TT_ObjCArrayLiteral,
Daniel Jasper32d28ee2013-01-29 21:01:14 +000041 TT_ObjCBlockLParen,
42 TT_ObjCDecl,
Nico Weberc2e6d2a2013-02-11 15:32:15 +000043 TT_ObjCForIn,
Daniel Jasper32d28ee2013-01-29 21:01:14 +000044 TT_ObjCMethodExpr,
Nico Weber051860e2013-02-10 02:08:05 +000045 TT_ObjCMethodSpecifier,
Daniel Jasper32d28ee2013-01-29 21:01:14 +000046 TT_ObjCProperty,
Daniel Jasper63d7ced2013-02-05 10:07:47 +000047 TT_ObjCSelectorName,
Daniel Jasper6ea933c2013-05-10 07:59:58 +000048 TT_OverloadedOperator,
Daniel Jasper2b4c9242013-02-11 08:01:18 +000049 TT_OverloadedOperatorLParen,
Daniel Jasper32d28ee2013-01-29 21:01:14 +000050 TT_PointerOrReference,
51 TT_PureVirtualSpecifier,
52 TT_RangeBasedForLoopColon,
53 TT_StartOfName,
54 TT_TemplateCloser,
55 TT_TemplateOpener,
56 TT_TrailingUnaryOperator,
57 TT_UnaryOperator,
58 TT_Unknown
59};
60
61enum LineType {
62 LT_Invalid,
63 LT_Other,
64 LT_BuilderTypeCall,
65 LT_PreprocessorDirective,
66 LT_VirtualFunctionDecl,
67 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
68 LT_ObjCMethodDecl,
69 LT_ObjCProperty // An @property line.
70};
71
72class AnnotatedToken {
73public:
74 explicit AnnotatedToken(const FormatToken &FormatTok)
Daniel Jasper729a7432013-02-11 12:36:37 +000075 : FormatTok(FormatTok), Type(TT_Unknown), SpacesRequiredBefore(0),
Daniel Jasper32d28ee2013-01-29 21:01:14 +000076 CanBreakBefore(false), MustBreakBefore(false),
77 ClosesTemplateDeclaration(false), MatchingParen(NULL),
Daniel Jasper089f78d2013-05-14 10:44:17 +000078 ParameterCount(0), TotalLength(FormatTok.TokenLength),
79 BindingStrength(0), SplitPenalty(0), LongestObjCSelectorName(0),
80 DefinesFunctionType(false), Parent(NULL), FakeRParens(0),
81 LastInChainOfCalls(false), PartOfMultiVariableDeclStmt(false),
82 NoMoreTokensOnLevel(false) {}
Daniel Jasper32d28ee2013-01-29 21:01:14 +000083
84 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
Alexander Kornienkoe74de282013-03-13 14:41:29 +000085
86 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
87 return is(K1) || is(K2);
88 }
89
90 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
91 return is(K1) || is(K2) || is(K3);
92 }
93
94 bool isOneOf(
95 tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
96 tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
97 tok::TokenKind K6 = tok::NUM_TOKENS, tok::TokenKind K7 = tok::NUM_TOKENS,
98 tok::TokenKind K8 = tok::NUM_TOKENS, tok::TokenKind K9 = tok::NUM_TOKENS,
99 tok::TokenKind K10 = tok::NUM_TOKENS,
100 tok::TokenKind K11 = tok::NUM_TOKENS,
101 tok::TokenKind K12 = tok::NUM_TOKENS) const {
102 return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
103 is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
104 }
105
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000106 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
107
108 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
109 return FormatTok.Tok.isObjCAtKeyword(Kind);
110 }
111
Alexander Kornienko94b748f2013-03-27 17:08:02 +0000112 bool isAccessSpecifier(bool ColonRequired = true) const {
113 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
114 (!ColonRequired ||
115 (!Children.empty() && Children[0].is(tok::colon)));
116 }
117
118 bool isObjCAccessSpecifier() const {
119 return is(tok::at) && !Children.empty() &&
120 (Children[0].isObjCAtKeyword(tok::objc_public) ||
121 Children[0].isObjCAtKeyword(tok::objc_protected) ||
122 Children[0].isObjCAtKeyword(tok::objc_package) ||
123 Children[0].isObjCAtKeyword(tok::objc_private));
124 }
125
Daniel Jasperac3223e2013-04-10 09:49:49 +0000126 /// \brief Returns whether \p Tok is ([{ or a template opening <.
127 bool opensScope() const;
128 /// \brief Returns whether \p Tok is )]} or a template opening >.
129 bool closesScope() const;
130
131 bool isUnaryOperator() const;
132 bool isBinaryOperator() const;
133 bool isTrailingComment() const;
134
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000135 FormatToken FormatTok;
136
137 TokenType Type;
138
Daniel Jasper729a7432013-02-11 12:36:37 +0000139 unsigned SpacesRequiredBefore;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000140 bool CanBreakBefore;
141 bool MustBreakBefore;
142
143 bool ClosesTemplateDeclaration;
144
145 AnnotatedToken *MatchingParen;
146
147 /// \brief Number of parameters, if this is "(", "[" or "<".
148 ///
149 /// This is initialized to 1 as we don't need to distinguish functions with
150 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
151 /// the number of commas.
152 unsigned ParameterCount;
153
154 /// \brief The total length of the line up to and including this token.
155 unsigned TotalLength;
156
Daniel Jasper01786732013-02-04 07:21:18 +0000157 // FIXME: Come up with a 'cleaner' concept.
158 /// \brief The binding strength of a token. This is a combined value of
159 /// operator precedence, parenthesis nesting, etc.
160 unsigned BindingStrength;
161
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000162 /// \brief Penalty for inserting a line break before this token.
163 unsigned SplitPenalty;
164
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000165 /// \brief If this is the first ObjC selector name in an ObjC method
166 /// definition or call, this contains the length of the longest name.
167 unsigned LongestObjCSelectorName;
168
Daniel Jasper395228f2013-05-08 14:58:20 +0000169 /// \brief \c true if this is a "(" that starts a function type definition.
170 bool DefinesFunctionType;
171
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000172 std::vector<AnnotatedToken> Children;
173 AnnotatedToken *Parent;
174
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000175 /// \brief Stores the number of required fake parentheses and the
176 /// corresponding operator precedence.
177 ///
178 /// If multiple fake parentheses start at a token, this vector stores them in
179 /// reverse order, i.e. inner fake parenthesis first.
180 SmallVector<prec::Level, 4> FakeLParens;
Daniel Jasper087387a2013-02-08 16:49:27 +0000181 /// \brief Insert this many fake ) after this token for correct indentation.
Daniel Jasper29f123b2013-02-08 15:28:42 +0000182 unsigned FakeRParens;
183
Daniel Jasper24849712013-03-01 16:48:32 +0000184 /// \brief Is this the last "." or "->" in a builder-type call?
185 bool LastInChainOfCalls;
186
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000187 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
188 ///
189 /// Only set if \c Type == \c TT_StartOfName.
190 bool PartOfMultiVariableDeclStmt;
191
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000192 /// \brief Set to \c true for "("-tokens if this is the last token other than
193 /// ")" in the next higher parenthesis level.
194 ///
195 /// If this is \c true, no more formatting decisions have to be made on the
196 /// next higher parenthesis level, enabling optimizations.
197 ///
198 /// Example:
199 /// \code
200 /// aaaaaa(aaaaaa());
201 /// ^ // Set to true for this parenthesis.
202 /// \endcode
203 bool NoMoreTokensOnLevel;
204
Daniel Jasperac3223e2013-04-10 09:49:49 +0000205 /// \brief Returns the previous token ignoring comments.
206 AnnotatedToken *getPreviousNoneComment() const;
207
208 /// \brief Returns the next token ignoring comments.
209 const AnnotatedToken *getNextNoneComment() const;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000210};
211
212class AnnotatedLine {
213public:
214 AnnotatedLine(const UnwrappedLine &Line)
215 : First(Line.Tokens.front()), Level(Line.Level),
216 InPPDirective(Line.InPPDirective),
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000217 MustBeDeclaration(Line.MustBeDeclaration), MightBeFunctionDecl(false),
218 StartsDefinition(false) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000219 assert(!Line.Tokens.empty());
220 AnnotatedToken *Current = &First;
221 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
222 E = Line.Tokens.end();
223 I != E; ++I) {
224 Current->Children.push_back(AnnotatedToken(*I));
225 Current->Children[0].Parent = Current;
226 Current = &Current->Children[0];
227 }
228 Last = Current;
229 }
230 AnnotatedLine(const AnnotatedLine &Other)
231 : First(Other.First), Type(Other.Type), Level(Other.Level),
232 InPPDirective(Other.InPPDirective),
Daniel Jasper3c08a812013-02-24 18:54:32 +0000233 MustBeDeclaration(Other.MustBeDeclaration),
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000234 MightBeFunctionDecl(Other.MightBeFunctionDecl),
235 StartsDefinition(Other.StartsDefinition) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000236 Last = &First;
237 while (!Last->Children.empty()) {
238 Last->Children[0].Parent = Last;
239 Last = &Last->Children[0];
240 }
241 }
242
243 AnnotatedToken First;
244 AnnotatedToken *Last;
245
246 LineType Type;
247 unsigned Level;
248 bool InPPDirective;
249 bool MustBeDeclaration;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000250 bool MightBeFunctionDecl;
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000251 bool StartsDefinition;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000252};
253
254inline prec::Level getPrecedence(const AnnotatedToken &Tok) {
255 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
256}
257
258/// \brief Determines extra information about the tokens comprising an
259/// \c UnwrappedLine.
260class TokenAnnotator {
261public:
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000262 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
263 IdentifierInfo &Ident_in)
264 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Ident_in(Ident_in) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000265 }
266
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000267 void annotate(AnnotatedLine &Line);
268 void calculateFormattingInformation(AnnotatedLine &Line);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000269
270private:
271 /// \brief Calculate the penalty for splitting before \c Tok.
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000272 unsigned splitPenalty(const AnnotatedLine &Line, const AnnotatedToken &Tok);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000273
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000274 bool spaceRequiredBetween(const AnnotatedLine &Line,
275 const AnnotatedToken &Left,
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000276 const AnnotatedToken &Right);
277
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000278 bool spaceRequiredBefore(const AnnotatedLine &Line,
279 const AnnotatedToken &Tok);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000280
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000281 bool canBreakBefore(const AnnotatedLine &Line, const AnnotatedToken &Right);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000282
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000283 void printDebugInfo(const AnnotatedLine &Line);
284
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000285 const FormatStyle &Style;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000286 SourceManager &SourceMgr;
287 Lexer &Lex;
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000288
289 // Contextual keywords:
290 IdentifierInfo &Ident_in;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000291};
292
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000293} // end namespace format
294} // end namespace clang
295
296#endif // LLVM_CLANG_FORMAT_TOKEN_ANNOTATOR_H