1//===--- TokenAnnotator.h - Format C++ code ---------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements a token annotator, i.e. creates
11/// \c AnnotatedTokens out of \c FormatTokens with required extra information.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_LIB_FORMAT_TOKENANNOTATOR_H
16#define LLVM_CLANG_LIB_FORMAT_TOKENANNOTATOR_H
17
18#include "UnwrappedLineParser.h"
19
20namespace clang {
21namespace format {
22
23enum LineType {
24 LT_Invalid,
25 // Contains public/private/protected followed by TT_InheritanceColon.
26 LT_AccessModifier,
27 LT_ImportStatement,
28 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
29 LT_ObjCMethodDecl,
30 LT_ObjCProperty, // An @property line.
31 LT_Other,
32 LT_PreprocessorDirective,
33 LT_VirtualFunctionDecl,
34 LT_ArrayOfStructInitializer,
35 LT_CommentAbovePPDirective,
36 LT_RequiresExpression,
37 LT_SimpleRequirement,
38};
39
40enum ScopeType {
41 // Contained in class declaration/definition.
42 ST_Class,
43 // Contained in enum declaration/definition.
44 ST_Enum,
45 // Contained in compound requirement.
46 ST_CompoundRequirement,
47 // Contained in other blocks (function, lambda, loop, if/else, child, etc).
48 ST_Other,
49};
50
51class AnnotatedLine {
52public:
53 AnnotatedLine(const UnwrappedLine &Line)
54 : First(Line.Tokens.front().Tok), Type(LT_Other), Level(Line.Level),
55 PPLevel(Line.PPLevel),
56 MatchingOpeningBlockLineIndex(Line.MatchingOpeningBlockLineIndex),
57 MatchingClosingBlockLineIndex(Line.MatchingClosingBlockLineIndex),
58 InPPDirective(Line.InPPDirective),
59 InPragmaDirective(Line.InPragmaDirective),
60 InMacroBody(Line.InMacroBody), InMacroExpansion(Line.InMacroExpansion),
61 IsModuleOrImportDecl(Line.IsModuleOrImportDecl),
62 MustBeDeclaration(Line.MustBeDeclaration), MightBeFunctionDecl(false),
63 IsMultiVariableDeclStmt(false), Affected(false),
64 LeadingEmptyLinesAffected(false), ChildrenAffected(false),
65 ReturnTypeWrapped(false), IsContinuation(Line.IsContinuation),
66 FirstStartColumn(Line.FirstStartColumn) {
67 assert(!Line.Tokens.empty());
68
69 // Calculate Next and Previous for all tokens. Note that we must overwrite
70 // Next and Previous for every token, as previous formatting runs might have
71 // left them in a different state.
72 First->Previous = nullptr;
73 if (First->MacroParent)
74 ContainsMacroCall = true;
75 FormatToken *Current = First;
76 addChildren(Node: Line.Tokens.front(), Current);
77 for (const UnwrappedLineNode &Node : llvm::drop_begin(RangeOrContainer: Line.Tokens)) {
78 if (Node.Tok->MacroParent)
79 ContainsMacroCall = true;
80 Current->Next = Node.Tok;
81 Node.Tok->Previous = Current;
82 Current = Current->Next;
83 addChildren(Node, Current);
84 // FIXME: if we add children, previous will point to the token before
85 // the children; changing this requires significant changes across
86 // clang-format.
87 }
88 Last = Current;
89 Last->Next = nullptr;
90 }
91
92 void addChildren(const UnwrappedLineNode &Node, FormatToken *Current) {
93 Current->Children.clear();
94 for (const auto &Child : Node.Children) {
95 Children.push_back(Elt: new AnnotatedLine(Child));
96 if (Children.back()->ContainsMacroCall)
97 ContainsMacroCall = true;
98 Current->Children.push_back(Elt: Children.back());
99 }
100 }
101
102 size_t size() const {
103 size_t Size = 1;
104 for (const auto *Child : Children)
105 Size += Child->size();
106 return Size;
107 }
108
109 ~AnnotatedLine() {
110 for (AnnotatedLine *Child : Children)
111 delete Child;
112 FormatToken *Current = First;
113 while (Current) {
114 Current->Children.clear();
115 Current->Role.reset();
116 Current = Current->Next;
117 }
118 }
119
120 bool isComment() const {
121 return First && First->is(Kind: tok::comment) && !First->getNextNonComment();
122 }
123
124 /// \c true if this line starts with the given tokens in order, ignoring
125 /// comments.
126 template <typename... Ts> bool startsWith(Ts... Tokens) const {
127 return First && First->startsSequence(Tokens...);
128 }
129
130 /// \c true if this line ends with the given tokens in reversed order,
131 /// ignoring comments.
132 /// For example, given tokens [T1, T2, T3, ...], the function returns true if
133 /// this line is like "... T3 T2 T1".
134 template <typename... Ts> bool endsWith(Ts... Tokens) const {
135 return Last && Last->endsSequence(Tokens...);
136 }
137
138 /// \c true if this line looks like a function definition instead of a
139 /// function declaration. Asserts MightBeFunctionDecl.
140 bool mightBeFunctionDefinition() const {
141 assert(MightBeFunctionDecl);
142 // Try to determine if the end of a stream of tokens is either the
143 // Definition or the Declaration for a function. It does this by looking for
144 // the ';' in foo(); and using that it ends with a ; to know this is the
145 // Definition, however the line could end with
146 // foo(); /* comment */
147 // or
148 // foo(); // comment
149 // or
150 // foo() // comment
151 // endsWith() ignores the comment.
152 return !endsWith(Tokens: tok::semi);
153 }
154
155 /// \c true if this line starts a namespace definition.
156 bool startsWithNamespace() const {
157 return startsWith(Tokens: tok::kw_namespace) || startsWith(Tokens: TT_NamespaceMacro) ||
158 startsWith(Tokens: tok::kw_inline, Tokens: tok::kw_namespace) ||
159 startsWith(Tokens: tok::kw_export, Tokens: tok::kw_namespace);
160 }
161
162 FormatToken *getFirstNonComment() const {
163 assert(First);
164 return First->is(Kind: tok::comment) ? First->getNextNonComment() : First;
165 }
166
167 FormatToken *getLastNonComment() const {
168 assert(Last);
169 return Last->is(Kind: tok::comment) ? Last->getPreviousNonComment() : Last;
170 }
171
172 FormatToken *First;
173 FormatToken *Last;
174
175 SmallVector<AnnotatedLine *, 0> Children;
176
177 LineType Type;
178 unsigned Level;
179 unsigned PPLevel;
180 size_t MatchingOpeningBlockLineIndex;
181 size_t MatchingClosingBlockLineIndex;
182 bool InPPDirective;
183 bool InPragmaDirective;
184 bool InMacroBody;
185 bool InMacroExpansion;
186 bool IsModuleOrImportDecl;
187 bool MustBeDeclaration;
188 bool MightBeFunctionDecl;
189 bool IsMultiVariableDeclStmt;
190
191 /// \c True if this line contains a macro call for which an expansion exists.
192 bool ContainsMacroCall = false;
193
194 /// \c True if calculateFormattingInformation() has been called on this line.
195 bool Computed = false;
196
197 /// \c True if this line should be formatted, i.e. intersects directly or
198 /// indirectly with one of the input ranges.
199 bool Affected;
200
201 /// \c True if the leading empty lines of this line intersect with one of the
202 /// input ranges.
203 bool LeadingEmptyLinesAffected;
204
205 /// \c True if one of this line's children intersects with an input range.
206 bool ChildrenAffected;
207
208 /// \c True if breaking after last attribute group in function return type.
209 bool ReturnTypeWrapped;
210
211 /// \c True if this line should be indented by ContinuationIndent in addition
212 /// to the normal indention level.
213 bool IsContinuation;
214
215 unsigned FirstStartColumn;
216
217private:
218 // Disallow copying.
219 AnnotatedLine(const AnnotatedLine &) = delete;
220 void operator=(const AnnotatedLine &) = delete;
221};
222
223/// Determines extra information about the tokens comprising an
224/// \c UnwrappedLine.
225class TokenAnnotator {
226public:
227 TokenAnnotator(const FormatStyle &Style, const AdditionalKeywords &Keywords)
228 : Style(Style), IsCpp(Style.isCpp()),
229 LangOpts(getFormattingLangOpts(Style)), Keywords(Keywords) {}
230
231 /// Adapts the indent levels of comment lines to the indent of the
232 /// subsequent line.
233 // FIXME: Can/should this be done in the UnwrappedLineParser?
234 void setCommentLineLevels(SmallVectorImpl<AnnotatedLine *> &Lines) const;
235
236 void annotate(AnnotatedLine &Line);
237 void calculateFormattingInformation(AnnotatedLine &Line) const;
238
239private:
240 /// Calculate the penalty for splitting before \c Tok.
241 unsigned splitPenalty(const AnnotatedLine &Line, const FormatToken &Tok,
242 bool InFunctionDecl) const;
243
244 bool spaceRequiredBeforeParens(const FormatToken &Right) const;
245
246 bool spaceRequiredBetween(const AnnotatedLine &Line, const FormatToken &Left,
247 const FormatToken &Right) const;
248
249 bool spaceRequiredBefore(const AnnotatedLine &Line,
250 const FormatToken &Right) const;
251
252 bool mustBreakBefore(AnnotatedLine &Line, const FormatToken &Right) const;
253
254 bool canBreakBefore(const AnnotatedLine &Line,
255 const FormatToken &Right) const;
256
257 bool mustBreakForReturnType(const AnnotatedLine &Line) const;
258
259 bool mustBreakBeforeReturnType(const AnnotatedLine &Line) const;
260
261 void printDebugInfo(const AnnotatedLine &Line) const;
262
263 void calculateUnbreakableTailLengths(AnnotatedLine &Line) const;
264
265 void calculateArrayInitializerColumnList(AnnotatedLine &Line) const;
266
267 FormatToken *calculateInitializerColumnList(AnnotatedLine &Line,
268 FormatToken *CurrentToken,
269 unsigned Depth) const;
270 FormatStyle::PointerAlignmentStyle
271 getTokenReferenceAlignment(const FormatToken &PointerOrReference) const;
272
273 FormatStyle::PointerAlignmentStyle getTokenPointerOrReferenceAlignment(
274 const FormatToken &PointerOrReference) const;
275
276 const FormatStyle &Style;
277
278 bool IsCpp;
279 LangOptions LangOpts;
280
281 const AdditionalKeywords &Keywords;
282
283 SmallVector<ScopeType> Scopes, MacroBodyScopes;
284};
285
286} // end namespace format
287} // end namespace clang
288
289#endif
290