blob: a2080b5b6f3028c02122aeb30d80694549483e45 [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 Jasper2b4c9242013-02-11 08:01:18 +000048 TT_OverloadedOperatorLParen,
Daniel Jasper32d28ee2013-01-29 21:01:14 +000049 TT_PointerOrReference,
50 TT_PureVirtualSpecifier,
51 TT_RangeBasedForLoopColon,
52 TT_StartOfName,
53 TT_TemplateCloser,
54 TT_TemplateOpener,
55 TT_TrailingUnaryOperator,
56 TT_UnaryOperator,
57 TT_Unknown
58};
59
60enum LineType {
61 LT_Invalid,
62 LT_Other,
63 LT_BuilderTypeCall,
64 LT_PreprocessorDirective,
65 LT_VirtualFunctionDecl,
66 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
67 LT_ObjCMethodDecl,
68 LT_ObjCProperty // An @property line.
69};
70
71class AnnotatedToken {
72public:
73 explicit AnnotatedToken(const FormatToken &FormatTok)
Daniel Jasper729a7432013-02-11 12:36:37 +000074 : FormatTok(FormatTok), Type(TT_Unknown), SpacesRequiredBefore(0),
Daniel Jasper32d28ee2013-01-29 21:01:14 +000075 CanBreakBefore(false), MustBreakBefore(false),
76 ClosesTemplateDeclaration(false), MatchingParen(NULL),
Daniel Jasper9fc56f22013-02-14 15:01:34 +000077 ParameterCount(0), BindingStrength(0), SplitPenalty(0),
Daniel Jasper395228f2013-05-08 14:58:20 +000078 LongestObjCSelectorName(0), DefinesFunctionType(false), Parent(NULL),
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +000079 FakeRParens(0), LastInChainOfCalls(false),
Daniel Jasperfca24bc2013-04-25 13:31:51 +000080 PartOfMultiVariableDeclStmt(false), NoMoreTokensOnLevel(false) {}
Daniel Jasper32d28ee2013-01-29 21:01:14 +000081
82 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
Alexander Kornienkoe74de282013-03-13 14:41:29 +000083
84 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
85 return is(K1) || is(K2);
86 }
87
88 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
89 return is(K1) || is(K2) || is(K3);
90 }
91
92 bool isOneOf(
93 tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
94 tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
95 tok::TokenKind K6 = tok::NUM_TOKENS, tok::TokenKind K7 = tok::NUM_TOKENS,
96 tok::TokenKind K8 = tok::NUM_TOKENS, tok::TokenKind K9 = tok::NUM_TOKENS,
97 tok::TokenKind K10 = tok::NUM_TOKENS,
98 tok::TokenKind K11 = tok::NUM_TOKENS,
99 tok::TokenKind K12 = tok::NUM_TOKENS) const {
100 return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
101 is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
102 }
103
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000104 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
105
106 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
107 return FormatTok.Tok.isObjCAtKeyword(Kind);
108 }
109
Alexander Kornienko94b748f2013-03-27 17:08:02 +0000110 bool isAccessSpecifier(bool ColonRequired = true) const {
111 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
112 (!ColonRequired ||
113 (!Children.empty() && Children[0].is(tok::colon)));
114 }
115
116 bool isObjCAccessSpecifier() const {
117 return is(tok::at) && !Children.empty() &&
118 (Children[0].isObjCAtKeyword(tok::objc_public) ||
119 Children[0].isObjCAtKeyword(tok::objc_protected) ||
120 Children[0].isObjCAtKeyword(tok::objc_package) ||
121 Children[0].isObjCAtKeyword(tok::objc_private));
122 }
123
Daniel Jasperac3223e2013-04-10 09:49:49 +0000124 /// \brief Returns whether \p Tok is ([{ or a template opening <.
125 bool opensScope() const;
126 /// \brief Returns whether \p Tok is )]} or a template opening >.
127 bool closesScope() const;
128
129 bool isUnaryOperator() const;
130 bool isBinaryOperator() const;
131 bool isTrailingComment() const;
132
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000133 FormatToken FormatTok;
134
135 TokenType Type;
136
Daniel Jasper729a7432013-02-11 12:36:37 +0000137 unsigned SpacesRequiredBefore;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000138 bool CanBreakBefore;
139 bool MustBreakBefore;
140
141 bool ClosesTemplateDeclaration;
142
143 AnnotatedToken *MatchingParen;
144
145 /// \brief Number of parameters, if this is "(", "[" or "<".
146 ///
147 /// This is initialized to 1 as we don't need to distinguish functions with
148 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
149 /// the number of commas.
150 unsigned ParameterCount;
151
152 /// \brief The total length of the line up to and including this token.
153 unsigned TotalLength;
154
Daniel Jasper01786732013-02-04 07:21:18 +0000155 // FIXME: Come up with a 'cleaner' concept.
156 /// \brief The binding strength of a token. This is a combined value of
157 /// operator precedence, parenthesis nesting, etc.
158 unsigned BindingStrength;
159
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000160 /// \brief Penalty for inserting a line break before this token.
161 unsigned SplitPenalty;
162
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000163 /// \brief If this is the first ObjC selector name in an ObjC method
164 /// definition or call, this contains the length of the longest name.
165 unsigned LongestObjCSelectorName;
166
Daniel Jasper395228f2013-05-08 14:58:20 +0000167 /// \brief \c true if this is a "(" that starts a function type definition.
168 bool DefinesFunctionType;
169
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000170 std::vector<AnnotatedToken> Children;
171 AnnotatedToken *Parent;
172
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000173 /// \brief Stores the number of required fake parentheses and the
174 /// corresponding operator precedence.
175 ///
176 /// If multiple fake parentheses start at a token, this vector stores them in
177 /// reverse order, i.e. inner fake parenthesis first.
178 SmallVector<prec::Level, 4> FakeLParens;
Daniel Jasper087387a2013-02-08 16:49:27 +0000179 /// \brief Insert this many fake ) after this token for correct indentation.
Daniel Jasper29f123b2013-02-08 15:28:42 +0000180 unsigned FakeRParens;
181
Daniel Jasper24849712013-03-01 16:48:32 +0000182 /// \brief Is this the last "." or "->" in a builder-type call?
183 bool LastInChainOfCalls;
184
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000185 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
186 ///
187 /// Only set if \c Type == \c TT_StartOfName.
188 bool PartOfMultiVariableDeclStmt;
189
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000190 /// \brief Set to \c true for "("-tokens if this is the last token other than
191 /// ")" in the next higher parenthesis level.
192 ///
193 /// If this is \c true, no more formatting decisions have to be made on the
194 /// next higher parenthesis level, enabling optimizations.
195 ///
196 /// Example:
197 /// \code
198 /// aaaaaa(aaaaaa());
199 /// ^ // Set to true for this parenthesis.
200 /// \endcode
201 bool NoMoreTokensOnLevel;
202
Daniel Jasperac3223e2013-04-10 09:49:49 +0000203 /// \brief Returns the previous token ignoring comments.
204 AnnotatedToken *getPreviousNoneComment() const;
205
206 /// \brief Returns the next token ignoring comments.
207 const AnnotatedToken *getNextNoneComment() const;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000208};
209
210class AnnotatedLine {
211public:
212 AnnotatedLine(const UnwrappedLine &Line)
213 : First(Line.Tokens.front()), Level(Line.Level),
214 InPPDirective(Line.InPPDirective),
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000215 MustBeDeclaration(Line.MustBeDeclaration), MightBeFunctionDecl(false),
216 StartsDefinition(false) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000217 assert(!Line.Tokens.empty());
218 AnnotatedToken *Current = &First;
219 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
220 E = Line.Tokens.end();
221 I != E; ++I) {
222 Current->Children.push_back(AnnotatedToken(*I));
223 Current->Children[0].Parent = Current;
224 Current = &Current->Children[0];
225 }
226 Last = Current;
227 }
228 AnnotatedLine(const AnnotatedLine &Other)
229 : First(Other.First), Type(Other.Type), Level(Other.Level),
230 InPPDirective(Other.InPPDirective),
Daniel Jasper3c08a812013-02-24 18:54:32 +0000231 MustBeDeclaration(Other.MustBeDeclaration),
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000232 MightBeFunctionDecl(Other.MightBeFunctionDecl),
233 StartsDefinition(Other.StartsDefinition) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000234 Last = &First;
235 while (!Last->Children.empty()) {
236 Last->Children[0].Parent = Last;
237 Last = &Last->Children[0];
238 }
239 }
240
241 AnnotatedToken First;
242 AnnotatedToken *Last;
243
244 LineType Type;
245 unsigned Level;
246 bool InPPDirective;
247 bool MustBeDeclaration;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000248 bool MightBeFunctionDecl;
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000249 bool StartsDefinition;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000250};
251
252inline prec::Level getPrecedence(const AnnotatedToken &Tok) {
253 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
254}
255
256/// \brief Determines extra information about the tokens comprising an
257/// \c UnwrappedLine.
258class TokenAnnotator {
259public:
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000260 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
261 IdentifierInfo &Ident_in)
262 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Ident_in(Ident_in) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000263 }
264
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000265 void annotate(AnnotatedLine &Line);
266 void calculateFormattingInformation(AnnotatedLine &Line);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000267
268private:
269 /// \brief Calculate the penalty for splitting before \c Tok.
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000270 unsigned splitPenalty(const AnnotatedLine &Line, const AnnotatedToken &Tok);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000271
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000272 bool spaceRequiredBetween(const AnnotatedLine &Line,
273 const AnnotatedToken &Left,
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000274 const AnnotatedToken &Right);
275
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000276 bool spaceRequiredBefore(const AnnotatedLine &Line,
277 const AnnotatedToken &Tok);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000278
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000279 bool canBreakBefore(const AnnotatedLine &Line, const AnnotatedToken &Right);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000280
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000281 void printDebugInfo(const AnnotatedLine &Line);
282
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000283 const FormatStyle &Style;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000284 SourceManager &SourceMgr;
285 Lexer &Lex;
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000286
287 // Contextual keywords:
288 IdentifierInfo &Ident_in;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000289};
290
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000291} // end namespace format
292} // end namespace clang
293
294#endif // LLVM_CLANG_FORMAT_TOKEN_ANNOTATOR_H