blob: 5ea30159a2a0d3b8b484800776c23055886393fe [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 Jasper9fc56f22013-02-14 15:01:34 +000078 ParameterCount(0), BindingStrength(0), SplitPenalty(0),
Daniel Jasper395228f2013-05-08 14:58:20 +000079 LongestObjCSelectorName(0), DefinesFunctionType(false), Parent(NULL),
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +000080 FakeRParens(0), LastInChainOfCalls(false),
Daniel Jasperfca24bc2013-04-25 13:31:51 +000081 PartOfMultiVariableDeclStmt(false), NoMoreTokensOnLevel(false) {}
Daniel Jasper32d28ee2013-01-29 21:01:14 +000082
83 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
Alexander Kornienkoe74de282013-03-13 14:41:29 +000084
85 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
86 return is(K1) || is(K2);
87 }
88
89 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
90 return is(K1) || is(K2) || is(K3);
91 }
92
93 bool isOneOf(
94 tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
95 tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
96 tok::TokenKind K6 = tok::NUM_TOKENS, tok::TokenKind K7 = tok::NUM_TOKENS,
97 tok::TokenKind K8 = tok::NUM_TOKENS, tok::TokenKind K9 = tok::NUM_TOKENS,
98 tok::TokenKind K10 = tok::NUM_TOKENS,
99 tok::TokenKind K11 = tok::NUM_TOKENS,
100 tok::TokenKind K12 = tok::NUM_TOKENS) const {
101 return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
102 is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
103 }
104
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000105 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
106
107 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
108 return FormatTok.Tok.isObjCAtKeyword(Kind);
109 }
110
Alexander Kornienko94b748f2013-03-27 17:08:02 +0000111 bool isAccessSpecifier(bool ColonRequired = true) const {
112 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
113 (!ColonRequired ||
114 (!Children.empty() && Children[0].is(tok::colon)));
115 }
116
117 bool isObjCAccessSpecifier() const {
118 return is(tok::at) && !Children.empty() &&
119 (Children[0].isObjCAtKeyword(tok::objc_public) ||
120 Children[0].isObjCAtKeyword(tok::objc_protected) ||
121 Children[0].isObjCAtKeyword(tok::objc_package) ||
122 Children[0].isObjCAtKeyword(tok::objc_private));
123 }
124
Daniel Jasperac3223e2013-04-10 09:49:49 +0000125 /// \brief Returns whether \p Tok is ([{ or a template opening <.
126 bool opensScope() const;
127 /// \brief Returns whether \p Tok is )]} or a template opening >.
128 bool closesScope() const;
129
130 bool isUnaryOperator() const;
131 bool isBinaryOperator() const;
132 bool isTrailingComment() const;
133
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000134 FormatToken FormatTok;
135
136 TokenType Type;
137
Daniel Jasper729a7432013-02-11 12:36:37 +0000138 unsigned SpacesRequiredBefore;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000139 bool CanBreakBefore;
140 bool MustBreakBefore;
141
142 bool ClosesTemplateDeclaration;
143
144 AnnotatedToken *MatchingParen;
145
146 /// \brief Number of parameters, if this is "(", "[" or "<".
147 ///
148 /// This is initialized to 1 as we don't need to distinguish functions with
149 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
150 /// the number of commas.
151 unsigned ParameterCount;
152
153 /// \brief The total length of the line up to and including this token.
154 unsigned TotalLength;
155
Daniel Jasper01786732013-02-04 07:21:18 +0000156 // FIXME: Come up with a 'cleaner' concept.
157 /// \brief The binding strength of a token. This is a combined value of
158 /// operator precedence, parenthesis nesting, etc.
159 unsigned BindingStrength;
160
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000161 /// \brief Penalty for inserting a line break before this token.
162 unsigned SplitPenalty;
163
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000164 /// \brief If this is the first ObjC selector name in an ObjC method
165 /// definition or call, this contains the length of the longest name.
166 unsigned LongestObjCSelectorName;
167
Daniel Jasper395228f2013-05-08 14:58:20 +0000168 /// \brief \c true if this is a "(" that starts a function type definition.
169 bool DefinesFunctionType;
170
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000171 std::vector<AnnotatedToken> Children;
172 AnnotatedToken *Parent;
173
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000174 /// \brief Stores the number of required fake parentheses and the
175 /// corresponding operator precedence.
176 ///
177 /// If multiple fake parentheses start at a token, this vector stores them in
178 /// reverse order, i.e. inner fake parenthesis first.
179 SmallVector<prec::Level, 4> FakeLParens;
Daniel Jasper087387a2013-02-08 16:49:27 +0000180 /// \brief Insert this many fake ) after this token for correct indentation.
Daniel Jasper29f123b2013-02-08 15:28:42 +0000181 unsigned FakeRParens;
182
Daniel Jasper24849712013-03-01 16:48:32 +0000183 /// \brief Is this the last "." or "->" in a builder-type call?
184 bool LastInChainOfCalls;
185
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000186 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
187 ///
188 /// Only set if \c Type == \c TT_StartOfName.
189 bool PartOfMultiVariableDeclStmt;
190
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000191 /// \brief Set to \c true for "("-tokens if this is the last token other than
192 /// ")" in the next higher parenthesis level.
193 ///
194 /// If this is \c true, no more formatting decisions have to be made on the
195 /// next higher parenthesis level, enabling optimizations.
196 ///
197 /// Example:
198 /// \code
199 /// aaaaaa(aaaaaa());
200 /// ^ // Set to true for this parenthesis.
201 /// \endcode
202 bool NoMoreTokensOnLevel;
203
Daniel Jasperac3223e2013-04-10 09:49:49 +0000204 /// \brief Returns the previous token ignoring comments.
205 AnnotatedToken *getPreviousNoneComment() const;
206
207 /// \brief Returns the next token ignoring comments.
208 const AnnotatedToken *getNextNoneComment() const;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000209};
210
211class AnnotatedLine {
212public:
213 AnnotatedLine(const UnwrappedLine &Line)
214 : First(Line.Tokens.front()), Level(Line.Level),
215 InPPDirective(Line.InPPDirective),
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000216 MustBeDeclaration(Line.MustBeDeclaration), MightBeFunctionDecl(false),
217 StartsDefinition(false) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000218 assert(!Line.Tokens.empty());
219 AnnotatedToken *Current = &First;
220 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
221 E = Line.Tokens.end();
222 I != E; ++I) {
223 Current->Children.push_back(AnnotatedToken(*I));
224 Current->Children[0].Parent = Current;
225 Current = &Current->Children[0];
226 }
227 Last = Current;
228 }
229 AnnotatedLine(const AnnotatedLine &Other)
230 : First(Other.First), Type(Other.Type), Level(Other.Level),
231 InPPDirective(Other.InPPDirective),
Daniel Jasper3c08a812013-02-24 18:54:32 +0000232 MustBeDeclaration(Other.MustBeDeclaration),
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000233 MightBeFunctionDecl(Other.MightBeFunctionDecl),
234 StartsDefinition(Other.StartsDefinition) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000235 Last = &First;
236 while (!Last->Children.empty()) {
237 Last->Children[0].Parent = Last;
238 Last = &Last->Children[0];
239 }
240 }
241
242 AnnotatedToken First;
243 AnnotatedToken *Last;
244
245 LineType Type;
246 unsigned Level;
247 bool InPPDirective;
248 bool MustBeDeclaration;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000249 bool MightBeFunctionDecl;
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000250 bool StartsDefinition;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000251};
252
253inline prec::Level getPrecedence(const AnnotatedToken &Tok) {
254 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
255}
256
257/// \brief Determines extra information about the tokens comprising an
258/// \c UnwrappedLine.
259class TokenAnnotator {
260public:
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000261 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
262 IdentifierInfo &Ident_in)
263 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Ident_in(Ident_in) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000264 }
265
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000266 void annotate(AnnotatedLine &Line);
267 void calculateFormattingInformation(AnnotatedLine &Line);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000268
269private:
270 /// \brief Calculate the penalty for splitting before \c Tok.
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000271 unsigned splitPenalty(const AnnotatedLine &Line, const AnnotatedToken &Tok);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000272
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000273 bool spaceRequiredBetween(const AnnotatedLine &Line,
274 const AnnotatedToken &Left,
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000275 const AnnotatedToken &Right);
276
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000277 bool spaceRequiredBefore(const AnnotatedLine &Line,
278 const AnnotatedToken &Tok);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000279
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000280 bool canBreakBefore(const AnnotatedLine &Line, const AnnotatedToken &Right);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000281
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000282 void printDebugInfo(const AnnotatedLine &Line);
283
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000284 const FormatStyle &Style;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000285 SourceManager &SourceMgr;
286 Lexer &Lex;
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000287
288 // Contextual keywords:
289 IdentifierInfo &Ident_in;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000290};
291
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000292} // end namespace format
293} // end namespace clang
294
295#endif // LLVM_CLANG_FORMAT_TOKEN_ANNOTATOR_H