blob: c72730e30c374bae7eda8e24d838d08f6e137593 [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),
Manuel Klimeke573c3f2013-05-22 12:51:29 +000079 UnbreakableTailLength(0), BindingStrength(0), SplitPenalty(0),
80 LongestObjCSelectorName(0), DefinesFunctionType(false), Parent(NULL),
81 FakeRParens(0), LastInChainOfCalls(false),
82 PartOfMultiVariableDeclStmt(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
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000157 /// \brief The length of following tokens until the next natural split point,
158 /// or the next token that can be broken.
159 unsigned UnbreakableTailLength;
160
Daniel Jasper01786732013-02-04 07:21:18 +0000161 // FIXME: Come up with a 'cleaner' concept.
162 /// \brief The binding strength of a token. This is a combined value of
163 /// operator precedence, parenthesis nesting, etc.
164 unsigned BindingStrength;
165
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000166 /// \brief Penalty for inserting a line break before this token.
167 unsigned SplitPenalty;
168
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000169 /// \brief If this is the first ObjC selector name in an ObjC method
170 /// definition or call, this contains the length of the longest name.
171 unsigned LongestObjCSelectorName;
172
Daniel Jasper395228f2013-05-08 14:58:20 +0000173 /// \brief \c true if this is a "(" that starts a function type definition.
174 bool DefinesFunctionType;
175
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000176 std::vector<AnnotatedToken> Children;
177 AnnotatedToken *Parent;
178
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000179 /// \brief Stores the number of required fake parentheses and the
180 /// corresponding operator precedence.
181 ///
182 /// If multiple fake parentheses start at a token, this vector stores them in
183 /// reverse order, i.e. inner fake parenthesis first.
184 SmallVector<prec::Level, 4> FakeLParens;
Daniel Jasper087387a2013-02-08 16:49:27 +0000185 /// \brief Insert this many fake ) after this token for correct indentation.
Daniel Jasper29f123b2013-02-08 15:28:42 +0000186 unsigned FakeRParens;
187
Daniel Jasper24849712013-03-01 16:48:32 +0000188 /// \brief Is this the last "." or "->" in a builder-type call?
189 bool LastInChainOfCalls;
190
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000191 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
192 ///
193 /// Only set if \c Type == \c TT_StartOfName.
194 bool PartOfMultiVariableDeclStmt;
195
Daniel Jasperac3223e2013-04-10 09:49:49 +0000196 /// \brief Returns the previous token ignoring comments.
197 AnnotatedToken *getPreviousNoneComment() const;
198
199 /// \brief Returns the next token ignoring comments.
200 const AnnotatedToken *getNextNoneComment() const;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000201};
202
203class AnnotatedLine {
204public:
205 AnnotatedLine(const UnwrappedLine &Line)
206 : First(Line.Tokens.front()), Level(Line.Level),
207 InPPDirective(Line.InPPDirective),
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000208 MustBeDeclaration(Line.MustBeDeclaration), MightBeFunctionDecl(false),
209 StartsDefinition(false) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000210 assert(!Line.Tokens.empty());
211 AnnotatedToken *Current = &First;
212 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
213 E = Line.Tokens.end();
214 I != E; ++I) {
215 Current->Children.push_back(AnnotatedToken(*I));
216 Current->Children[0].Parent = Current;
217 Current = &Current->Children[0];
218 }
219 Last = Current;
220 }
221 AnnotatedLine(const AnnotatedLine &Other)
222 : First(Other.First), Type(Other.Type), Level(Other.Level),
223 InPPDirective(Other.InPPDirective),
Daniel Jasper3c08a812013-02-24 18:54:32 +0000224 MustBeDeclaration(Other.MustBeDeclaration),
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000225 MightBeFunctionDecl(Other.MightBeFunctionDecl),
226 StartsDefinition(Other.StartsDefinition) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000227 Last = &First;
228 while (!Last->Children.empty()) {
229 Last->Children[0].Parent = Last;
230 Last = &Last->Children[0];
231 }
232 }
233
234 AnnotatedToken First;
235 AnnotatedToken *Last;
236
237 LineType Type;
238 unsigned Level;
239 bool InPPDirective;
240 bool MustBeDeclaration;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000241 bool MightBeFunctionDecl;
Daniel Jasper53e72cd2013-05-06 08:27:33 +0000242 bool StartsDefinition;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000243};
244
245inline prec::Level getPrecedence(const AnnotatedToken &Tok) {
246 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
247}
248
249/// \brief Determines extra information about the tokens comprising an
250/// \c UnwrappedLine.
251class TokenAnnotator {
252public:
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000253 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
254 IdentifierInfo &Ident_in)
255 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Ident_in(Ident_in) {
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000256 }
257
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000258 void annotate(AnnotatedLine &Line);
259 void calculateFormattingInformation(AnnotatedLine &Line);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000260
261private:
262 /// \brief Calculate the penalty for splitting before \c Tok.
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000263 unsigned splitPenalty(const AnnotatedLine &Line, const AnnotatedToken &Tok);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000264
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000265 bool spaceRequiredBetween(const AnnotatedLine &Line,
266 const AnnotatedToken &Left,
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000267 const AnnotatedToken &Right);
268
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000269 bool spaceRequiredBefore(const AnnotatedLine &Line,
270 const AnnotatedToken &Tok);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000271
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000272 bool canBreakBefore(const AnnotatedLine &Line, const AnnotatedToken &Right);
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000273
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000274 void printDebugInfo(const AnnotatedLine &Line);
275
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000276 void calculateUnbreakableTailLengths(AnnotatedLine &Line);
277
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000278 const FormatStyle &Style;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000279 SourceManager &SourceMgr;
280 Lexer &Lex;
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000281
282 // Contextual keywords:
283 IdentifierInfo &Ident_in;
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000284};
285
Daniel Jasper32d28ee2013-01-29 21:01:14 +0000286} // end namespace format
287} // end namespace clang
288
289#endif // LLVM_CLANG_FORMAT_TOKEN_ANNOTATOR_H