clang 17.0.0git
QualifierAlignmentFixer.cpp
Go to the documentation of this file.
1//===--- LeftRightQualifierAlignmentFixer.cpp -------------------*- 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 LeftRightQualifierAlignmentFixer, a TokenAnalyzer that
11/// enforces either left or right const depending on the style.
12///
13//===----------------------------------------------------------------------===//
14
16#include "FormatToken.h"
17#include "llvm/Support/Debug.h"
18#include "llvm/Support/Regex.h"
19
20#include <algorithm>
21#include <optional>
22
23#define DEBUG_TYPE "format-qualifier-alignment-fixer"
24
25namespace clang {
26namespace format {
27
29 const Environment &Env, const FormatStyle &Style, StringRef &Code,
30 ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
31 unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName)
32 : TokenAnalyzer(Env, Style), Code(Code), Ranges(Ranges),
33 FirstStartColumn(FirstStartColumn), NextStartColumn(NextStartColumn),
34 LastStartColumn(LastStartColumn), FileName(FileName) {
35 std::vector<std::string> LeftOrder;
36 std::vector<std::string> RightOrder;
37 std::vector<tok::TokenKind> ConfiguredQualifierTokens;
38 PrepareLeftRightOrdering(Style.QualifierOrder, LeftOrder, RightOrder,
39 ConfiguredQualifierTokens);
40
41 // Handle the left and right alignment separately.
42 for (const auto &Qualifier : LeftOrder) {
43 Passes.emplace_back(
44 [&, Qualifier, ConfiguredQualifierTokens](const Environment &Env) {
46 ConfiguredQualifierTokens,
47 /*RightAlign=*/false)
48 .process();
49 });
50 }
51 for (const auto &Qualifier : RightOrder) {
52 Passes.emplace_back(
53 [&, Qualifier, ConfiguredQualifierTokens](const Environment &Env) {
55 ConfiguredQualifierTokens,
56 /*RightAlign=*/true)
57 .process();
58 });
59 }
60}
61
62std::pair<tooling::Replacements, unsigned> QualifierAlignmentFixer::analyze(
63 TokenAnnotator & /*Annotator*/,
64 SmallVectorImpl<AnnotatedLine *> & /*AnnotatedLines*/,
65 FormatTokenLexer & /*Tokens*/) {
66 auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
67 NextStartColumn, LastStartColumn);
68 if (!Env)
69 return {};
70 std::optional<std::string> CurrentCode;
72 for (size_t I = 0, E = Passes.size(); I < E; ++I) {
73 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
74 auto NewCode = applyAllReplacements(
75 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
76 if (NewCode) {
77 Fixes = Fixes.merge(PassFixes.first);
78 if (I + 1 < E) {
79 CurrentCode = std::move(*NewCode);
81 *CurrentCode, FileName,
83 FirstStartColumn, NextStartColumn, LastStartColumn);
84 if (!Env)
85 return {};
86 }
87 }
88 }
89
90 // Don't make replacements that replace nothing.
91 tooling::Replacements NonNoOpFixes;
92
93 for (const tooling::Replacement &Fix : Fixes) {
94 StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
95
96 if (!OriginalCode.equals(Fix.getReplacementText())) {
97 auto Err = NonNoOpFixes.add(Fix);
98 if (Err) {
99 llvm::errs() << "Error adding replacements : "
100 << llvm::toString(std::move(Err)) << "\n";
101 }
102 }
103 }
104 return {NonNoOpFixes, 0};
105}
106
107static void replaceToken(const SourceManager &SourceMgr,
109 const CharSourceRange &Range, std::string NewText) {
110 auto Replacement = tooling::Replacement(SourceMgr, Range, NewText);
111 auto Err = Fixes.add(Replacement);
112
113 if (Err) {
114 llvm::errs() << "Error while rearranging Qualifier : "
115 << llvm::toString(std::move(Err)) << "\n";
116 }
117}
118
119static void removeToken(const SourceManager &SourceMgr,
121 const FormatToken *First) {
122 auto Range = CharSourceRange::getCharRange(First->getStartOfNonWhitespace(),
123 First->Tok.getEndLoc());
124 replaceToken(SourceMgr, Fixes, Range, "");
125}
126
127static void insertQualifierAfter(const SourceManager &SourceMgr,
129 const FormatToken *First,
130 const std::string &Qualifier) {
131 auto Range = CharSourceRange::getCharRange(First->Tok.getLocation(),
132 First->Tok.getEndLoc());
133
134 std::string NewText{};
135 NewText += First->TokenText;
136 NewText += " " + Qualifier;
137 replaceToken(SourceMgr, Fixes, Range, NewText);
138}
139
140static void insertQualifierBefore(const SourceManager &SourceMgr,
142 const FormatToken *First,
143 const std::string &Qualifier) {
144 auto Range = CharSourceRange::getCharRange(First->getStartOfNonWhitespace(),
145 First->Tok.getEndLoc());
146
147 std::string NewText = " " + Qualifier + " ";
148 NewText += First->TokenText;
149
150 replaceToken(SourceMgr, Fixes, Range, NewText);
151}
152
153static bool endsWithSpace(const std::string &s) {
154 if (s.empty())
155 return false;
156 return isspace(s.back());
157}
158
159static bool startsWithSpace(const std::string &s) {
160 if (s.empty())
161 return false;
162 return isspace(s.front());
163}
164
165static void rotateTokens(const SourceManager &SourceMgr,
167 const FormatToken *Last, bool Left) {
168 auto *End = Last;
169 auto *Begin = First;
170 if (!Left) {
171 End = Last->Next;
172 Begin = First->Next;
173 }
174
175 std::string NewText;
176 // If we are rotating to the left we move the Last token to the front.
177 if (Left) {
178 NewText += Last->TokenText;
179 NewText += " ";
180 }
181
182 // Then move through the other tokens.
183 auto *Tok = Begin;
184 while (Tok != End) {
185 if (!NewText.empty() && !endsWithSpace(NewText))
186 NewText += " ";
187
188 NewText += Tok->TokenText;
189 Tok = Tok->Next;
190 }
191
192 // If we are rotating to the right we move the first token to the back.
193 if (!Left) {
194 if (!NewText.empty() && !startsWithSpace(NewText))
195 NewText += " ";
196 NewText += First->TokenText;
197 }
198
199 auto Range = CharSourceRange::getCharRange(First->getStartOfNonWhitespace(),
200 Last->Tok.getEndLoc());
201
202 replaceToken(SourceMgr, Fixes, Range, NewText);
203}
204
205static bool
207 const std::vector<tok::TokenKind> &Qualifiers) {
208 return Tok && llvm::is_contained(Qualifiers, Tok->Tok.getKind());
209}
210
211static bool isQualifier(const FormatToken *const Tok) {
212 if (!Tok)
213 return false;
214
215 switch (Tok->Tok.getKind()) {
216 case tok::kw_const:
217 case tok::kw_volatile:
218 case tok::kw_static:
219 case tok::kw_inline:
220 case tok::kw_constexpr:
221 case tok::kw_restrict:
222 case tok::kw_friend:
223 return true;
224 default:
225 return false;
226 }
227}
228
230 const SourceManager &SourceMgr, const AdditionalKeywords &Keywords,
231 tooling::Replacements &Fixes, const FormatToken *const Tok,
232 const std::string &Qualifier, tok::TokenKind QualifierType) {
233 // We only need to think about streams that begin with a qualifier.
234 if (!Tok->is(QualifierType))
235 return Tok;
236 // Don't concern yourself if nothing follows the qualifier.
237 if (!Tok->Next)
238 return Tok;
239
240 // Skip qualifiers to the left to find what preceeds the qualifiers.
241 // Use isQualifier rather than isConfiguredQualifier to cover all qualifiers.
242 const FormatToken *PreviousCheck = Tok->getPreviousNonComment();
243 while (isQualifier(PreviousCheck))
244 PreviousCheck = PreviousCheck->getPreviousNonComment();
245
246 // Examples given in order of ['type', 'const', 'volatile']
247 const bool IsRightQualifier = PreviousCheck && [PreviousCheck]() {
248 // The cases:
249 // `Foo() const` -> `Foo() const`
250 // `Foo() const final` -> `Foo() const final`
251 // `Foo() const override` -> `Foo() const final`
252 // `Foo() const volatile override` -> `Foo() const volatile override`
253 // `Foo() volatile const final` -> `Foo() const volatile final`
254 if (PreviousCheck->is(tok::r_paren))
255 return true;
256
257 // The cases:
258 // `struct {} volatile const a;` -> `struct {} const volatile a;`
259 // `class {} volatile const a;` -> `class {} const volatile a;`
260 if (PreviousCheck->is(tok::r_brace))
261 return true;
262
263 // The case:
264 // `template <class T> const Bar Foo()` ->
265 // `template <class T> Bar const Foo()`
266 // The cases:
267 // `Foo<int> const foo` -> `Foo<int> const foo`
268 // `Foo<int> volatile const` -> `Foo<int> const volatile`
269 // The case:
270 // ```
271 // template <class T>
272 // requires Concept1<T> && requires Concept2<T>
273 // const Foo f();
274 // ```
275 // ->
276 // ```
277 // template <class T>
278 // requires Concept1<T> && requires Concept2<T>
279 // Foo const f();
280 // ```
281 if (PreviousCheck->is(TT_TemplateCloser)) {
282 // If the token closes a template<> or requires clause, then it is a left
283 // qualifier and should be moved to the right.
284 return !(PreviousCheck->ClosesTemplateDeclaration ||
285 PreviousCheck->ClosesRequiresClause);
286 }
287
288 // The case `Foo* const` -> `Foo* const`
289 // The case `Foo* volatile const` -> `Foo* const volatile`
290 // The case `int32_t const` -> `int32_t const`
291 // The case `auto volatile const` -> `auto const volatile`
292 if (PreviousCheck->isOneOf(TT_PointerOrReference, tok::identifier,
293 tok::kw_auto)) {
294 return true;
295 }
296
297 return false;
298 }();
299
300 // Find the last qualifier to the right.
301 const FormatToken *LastQual = Tok;
302 while (isQualifier(LastQual->getNextNonComment()))
303 LastQual = LastQual->getNextNonComment();
304
305 // If this qualifier is to the right of a type or pointer do a partial sort
306 // and return.
307 if (IsRightQualifier) {
308 if (LastQual != Tok)
309 rotateTokens(SourceMgr, Fixes, Tok, LastQual, /*Left=*/false);
310 return Tok;
311 }
312
313 const FormatToken *TypeToken = LastQual->getNextNonComment();
314 if (!TypeToken)
315 return Tok;
316
317 // Stay safe and don't move past macros, also don't bother with sorting.
318 if (isPossibleMacro(TypeToken))
319 return Tok;
320
321 // The case `const long long int volatile` -> `long long int const volatile`
322 // The case `long const long int volatile` -> `long long int const volatile`
323 // The case `long long volatile int const` -> `long long int const volatile`
324 // The case `const long long volatile int` -> `long long int const volatile`
325 if (TypeToken->isSimpleTypeSpecifier()) {
326 // The case `const decltype(foo)` -> `const decltype(foo)`
327 // The case `const typeof(foo)` -> `const typeof(foo)`
328 // The case `const _Atomic(foo)` -> `const _Atomic(foo)`
329 if (TypeToken->isOneOf(tok::kw_decltype, tok::kw_typeof, tok::kw__Atomic))
330 return Tok;
331
332 const FormatToken *LastSimpleTypeSpecifier = TypeToken;
333 while (isQualifierOrType(LastSimpleTypeSpecifier->getNextNonComment()))
334 LastSimpleTypeSpecifier = LastSimpleTypeSpecifier->getNextNonComment();
335
336 rotateTokens(SourceMgr, Fixes, Tok, LastSimpleTypeSpecifier,
337 /*Left=*/false);
338 return LastSimpleTypeSpecifier;
339 }
340
341 // The case `unsigned short const` -> `unsigned short const`
342 // The case:
343 // `unsigned short volatile const` -> `unsigned short const volatile`
344 if (PreviousCheck && PreviousCheck->isSimpleTypeSpecifier()) {
345 if (LastQual != Tok)
346 rotateTokens(SourceMgr, Fixes, Tok, LastQual, /*Left=*/false);
347 return Tok;
348 }
349
350 // Skip the typename keyword.
351 // The case `const typename C::type` -> `typename C::type const`
352 if (TypeToken->is(tok::kw_typename))
353 TypeToken = TypeToken->getNextNonComment();
354
355 // Skip the initial :: of a global-namespace type.
356 // The case `const ::...` -> `::... const`
357 if (TypeToken->is(tok::coloncolon)) {
358 // The case `const ::template Foo...` -> `::template Foo... const`
359 TypeToken = TypeToken->getNextNonComment();
360 if (TypeToken && TypeToken->is(tok::kw_template))
361 TypeToken = TypeToken->getNextNonComment();
362 }
363
364 // Don't change declarations such as
365 // `foo(const struct Foo a);` -> `foo(const struct Foo a);`
366 // as they would currently change code such as
367 // `const struct my_struct_t {} my_struct;` -> `struct my_struct_t const {}
368 // my_struct;`
369 if (TypeToken->isOneOf(tok::kw_struct, tok::kw_class))
370 return Tok;
371
372 if (TypeToken->isOneOf(tok::kw_auto, tok::identifier)) {
373 // The case `const auto` -> `auto const`
374 // The case `const Foo` -> `Foo const`
375 // The case `const ::Foo` -> `::Foo const`
376 // The case `const Foo *` -> `Foo const *`
377 // The case `const Foo &` -> `Foo const &`
378 // The case `const Foo &&` -> `Foo const &&`
379 // The case `const std::Foo &&` -> `std::Foo const &&`
380 // The case `const std::Foo<T> &&` -> `std::Foo<T> const &&`
381 // The case `const ::template Foo` -> `::template Foo const`
382 // The case `const T::template Foo` -> `T::template Foo const`
383 const FormatToken *Next = nullptr;
384 while ((Next = TypeToken->getNextNonComment()) &&
385 (Next->is(TT_TemplateOpener) ||
386 Next->startsSequence(tok::coloncolon, tok::identifier) ||
387 Next->startsSequence(tok::coloncolon, tok::kw_template,
388 tok::identifier))) {
389 if (Next->is(TT_TemplateOpener)) {
390 assert(Next->MatchingParen && "Missing template closer");
391 TypeToken = Next->MatchingParen;
392 } else if (Next->startsSequence(tok::coloncolon, tok::identifier)) {
393 TypeToken = Next->getNextNonComment();
394 } else {
395 TypeToken = Next->getNextNonComment()->getNextNonComment();
396 }
397 }
398
399 // Place the Qualifier at the end of the list of qualifiers.
400 while (isQualifier(TypeToken->getNextNonComment())) {
401 // The case `volatile Foo::iter const` -> `Foo::iter const volatile`
402 TypeToken = TypeToken->getNextNonComment();
403 }
404
405 insertQualifierAfter(SourceMgr, Fixes, TypeToken, Qualifier);
406 // Remove token and following whitespace.
409 replaceToken(SourceMgr, Fixes, Range, "");
410 }
411
412 return Tok;
413}
414
416 const SourceManager &SourceMgr, const AdditionalKeywords &Keywords,
417 tooling::Replacements &Fixes, const FormatToken *const Tok,
418 const std::string &Qualifier, tok::TokenKind QualifierType) {
419 // We only need to think about streams that begin with a qualifier.
420 if (!Tok->is(QualifierType))
421 return Tok;
422 // Don't concern yourself if nothing preceeds the qualifier.
423 if (!Tok->getPreviousNonComment())
424 return Tok;
425
426 // Skip qualifiers to the left to find what preceeds the qualifiers.
427 const FormatToken *TypeToken = Tok->getPreviousNonComment();
428 while (isQualifier(TypeToken))
429 TypeToken = TypeToken->getPreviousNonComment();
430
431 // For left qualifiers preceeded by nothing, a template declaration, or *,&,&&
432 // we only perform sorting.
433 if (!TypeToken || TypeToken->isOneOf(tok::star, tok::amp, tok::ampamp) ||
434 TypeToken->ClosesRequiresClause || TypeToken->ClosesTemplateDeclaration) {
435
436 // Don't sort past a non-configured qualifier token.
437 const FormatToken *FirstQual = Tok;
439 ConfiguredQualifierTokens)) {
440 FirstQual = FirstQual->getPreviousNonComment();
441 }
442
443 if (FirstQual != Tok)
444 rotateTokens(SourceMgr, Fixes, FirstQual, Tok, /*Left=*/true);
445 return Tok;
446 }
447
448 // Stay safe and don't move past macros, also don't bother with sorting.
449 if (isPossibleMacro(TypeToken))
450 return Tok;
451
452 // Examples given in order of ['const', 'volatile', 'type']
453
454 // The case `volatile long long int const` -> `const volatile long long int`
455 // The case `volatile long long const int` -> `const volatile long long int`
456 // The case `const long long volatile int` -> `const volatile long long int`
457 // The case `long volatile long int const` -> `const volatile long long int`
458 if (TypeToken->isSimpleTypeSpecifier()) {
459 const FormatToken *LastSimpleTypeSpecifier = TypeToken;
461 LastSimpleTypeSpecifier->getPreviousNonComment(),
462 ConfiguredQualifierTokens)) {
463 LastSimpleTypeSpecifier =
464 LastSimpleTypeSpecifier->getPreviousNonComment();
465 }
466
467 rotateTokens(SourceMgr, Fixes, LastSimpleTypeSpecifier, Tok,
468 /*Left=*/true);
469 return Tok;
470 }
471
472 if (TypeToken->isOneOf(tok::kw_auto, tok::identifier, TT_TemplateCloser)) {
473 const auto IsStartOfType = [](const FormatToken *const Tok) -> bool {
474 if (!Tok)
475 return true;
476
477 // A template closer is not the start of a type.
478 // The case `?<> const` -> `const ?<>`
479 if (Tok->is(TT_TemplateCloser))
480 return false;
481
482 const FormatToken *const Previous = Tok->getPreviousNonComment();
483 if (!Previous)
484 return true;
485
486 // An identifier preceeded by :: is not the start of a type.
487 // The case `?::Foo const` -> `const ?::Foo`
488 if (Tok->is(tok::identifier) && Previous->is(tok::coloncolon))
489 return false;
490
491 const FormatToken *const PrePrevious = Previous->getPreviousNonComment();
492 // An identifier preceeded by ::template is not the start of a type.
493 // The case `?::template Foo const` -> `const ?::template Foo`
494 if (Tok->is(tok::identifier) && Previous->is(tok::kw_template) &&
495 PrePrevious && PrePrevious->is(tok::coloncolon)) {
496 return false;
497 }
498
499 return true;
500 };
501
502 while (!IsStartOfType(TypeToken)) {
503 // The case `?<>`
504 if (TypeToken->is(TT_TemplateCloser)) {
505 assert(TypeToken->MatchingParen && "Missing template opener");
506 TypeToken = TypeToken->MatchingParen->getPreviousNonComment();
507 } else {
508 // The cases
509 // `::Foo`
510 // `?>::Foo`
511 // `?Bar::Foo`
512 // `::template Foo`
513 // `?>::template Foo`
514 // `?Bar::template Foo`
515 if (TypeToken->getPreviousNonComment()->is(tok::kw_template))
516 TypeToken = TypeToken->getPreviousNonComment();
517
518 const FormatToken *const ColonColon =
519 TypeToken->getPreviousNonComment();
520 const FormatToken *const PreColonColon =
521 ColonColon->getPreviousNonComment();
522 if (PreColonColon &&
523 PreColonColon->isOneOf(TT_TemplateCloser, tok::identifier)) {
524 TypeToken = PreColonColon;
525 } else {
526 TypeToken = ColonColon;
527 }
528 }
529 }
530
531 assert(TypeToken && "Should be auto or identifier");
532
533 // Place the Qualifier at the start of the list of qualifiers.
534 const FormatToken *Previous = nullptr;
535 while ((Previous = TypeToken->getPreviousNonComment()) &&
536 (isConfiguredQualifier(Previous, ConfiguredQualifierTokens) ||
537 Previous->is(tok::kw_typename))) {
538 // The case `volatile Foo::iter const` -> `const volatile Foo::iter`
539 // The case `typename C::type const` -> `const typename C::type`
540 TypeToken = Previous;
541 }
542
543 // Don't change declarations such as
544 // `foo(struct Foo const a);` -> `foo(struct Foo const a);`
545 if (!Previous || !Previous->isOneOf(tok::kw_struct, tok::kw_class)) {
546 insertQualifierBefore(SourceMgr, Fixes, TypeToken, Qualifier);
547 removeToken(SourceMgr, Fixes, Tok);
548 }
549 }
550
551 return Tok;
552}
553
555 const std::string &Qualifier) {
556 // Don't let 'type' be an identifier, but steal typeof token.
557 return llvm::StringSwitch<tok::TokenKind>(Qualifier)
558 .Case("type", tok::kw_typeof)
559 .Case("const", tok::kw_const)
560 .Case("volatile", tok::kw_volatile)
561 .Case("static", tok::kw_static)
562 .Case("inline", tok::kw_inline)
563 .Case("constexpr", tok::kw_constexpr)
564 .Case("restrict", tok::kw_restrict)
565 .Case("friend", tok::kw_friend)
566 .Default(tok::identifier);
567}
568
570 const Environment &Env, const FormatStyle &Style,
571 const std::string &Qualifier,
572 const std::vector<tok::TokenKind> &QualifierTokens, bool RightAlign)
573 : TokenAnalyzer(Env, Style), Qualifier(Qualifier), RightAlign(RightAlign),
574 ConfiguredQualifierTokens(QualifierTokens) {}
575
576std::pair<tooling::Replacements, unsigned>
578 TokenAnnotator & /*Annotator*/,
579 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
580 FormatTokenLexer &Tokens) {
582 const AdditionalKeywords &Keywords = Tokens.getKeywords();
583 const SourceManager &SourceMgr = Env.getSourceManager();
585
586 tok::TokenKind QualifierToken = getTokenFromQualifier(Qualifier);
587 assert(QualifierToken != tok::identifier && "Unrecognised Qualifier");
588
589 for (AnnotatedLine *Line : AnnotatedLines) {
590 if (Line->InPPDirective)
591 continue;
592 FormatToken *First = Line->First;
593 assert(First);
594 if (First->Finalized)
595 continue;
596
597 const auto *Last = Line->Last;
598
599 for (const auto *Tok = First; Tok && Tok != Last && Tok->Next;
600 Tok = Tok->Next) {
601 if (Tok->is(tok::comment))
602 continue;
603 if (RightAlign) {
604 Tok = analyzeRight(SourceMgr, Keywords, Fixes, Tok, Qualifier,
605 QualifierToken);
606 } else {
607 Tok = analyzeLeft(SourceMgr, Keywords, Fixes, Tok, Qualifier,
608 QualifierToken);
609 }
610 }
611 }
612 return {Fixes, 0};
613}
614
616 const std::vector<std::string> &Order, std::vector<std::string> &LeftOrder,
617 std::vector<std::string> &RightOrder,
618 std::vector<tok::TokenKind> &Qualifiers) {
619
620 // Depending on the position of type in the order you need
621 // To iterate forward or backward through the order list as qualifier
622 // can push through each other.
623 // The Order list must define the position of "type" to signify
624 assert(llvm::is_contained(Order, "type") &&
625 "QualifierOrder must contain type");
626 // Split the Order list by type and reverse the left side.
627
628 bool left = true;
629 for (const auto &s : Order) {
630 if (s == "type") {
631 left = false;
632 continue;
633 }
634
635 tok::TokenKind QualifierToken =
637 if (QualifierToken != tok::kw_typeof && QualifierToken != tok::identifier)
638 Qualifiers.push_back(QualifierToken);
639
640 if (left) {
641 // Reverse the order for left aligned items.
642 LeftOrder.insert(LeftOrder.begin(), s);
643 } else {
644 RightOrder.push_back(s);
645 }
646 }
647}
648
650 const FormatToken *const Tok) {
651 return Tok && (Tok->isSimpleTypeSpecifier() || Tok->is(tok::kw_auto) ||
652 isQualifier(Tok));
653}
654
656 const FormatToken *const Tok,
657 const std::vector<tok::TokenKind> &Qualifiers) {
658 return Tok && (Tok->isSimpleTypeSpecifier() || Tok->is(tok::kw_auto) ||
660}
661
662// If a token is an identifier and it's upper case, it could
663// be a macro and hence we need to be able to ignore it.
665 if (!Tok)
666 return false;
667 if (!Tok->is(tok::identifier))
668 return false;
669 if (Tok->TokenText.upper() == Tok->TokenText.str()) {
670 // T,K,U,V likely could be template arguments
671 return (Tok->TokenText.size() != 1);
672 }
673 return false;
674}
675
676} // namespace format
677} // namespace clang
This file contains the declaration of the FormatToken, a wrapper around Token with additional informa...
This file declares LeftRightQualifierAlignmentFixer, a TokenAnalyzer that enforces either east or wes...
SourceLocation Begin
StateNode * Previous
__device__ __2f16 float bool s
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
The collection of all-type qualifiers we support.
Definition: Type.h:146
This class handles loading and caching of source files into memory.
tok::TokenKind getKind() const
Definition: Token.h:93
bool computeAffectedLines(SmallVectorImpl< AnnotatedLine * > &Lines)
SourceManager & getSourceManager() const
Definition: TokenAnalyzer.h:49
static std::unique_ptr< Environment > make(StringRef Code, StringRef FileName, ArrayRef< tooling::Range > Ranges, unsigned FirstStartColumn=0, unsigned NextStartColumn=0, unsigned LastStartColumn=0)
LeftRightQualifierAlignmentFixer(const Environment &Env, const FormatStyle &Style, const std::string &Qualifier, const std::vector< tok::TokenKind > &ConfiguredQualifierTokens, bool RightAlign)
static bool isQualifierOrType(const FormatToken *Tok)
static bool isConfiguredQualifierOrType(const FormatToken *Tok, const std::vector< tok::TokenKind > &Qualifiers)
const FormatToken * analyzeLeft(const SourceManager &SourceMgr, const AdditionalKeywords &Keywords, tooling::Replacements &Fixes, const FormatToken *Tok, const std::string &Qualifier, tok::TokenKind QualifierType)
const FormatToken * analyzeRight(const SourceManager &SourceMgr, const AdditionalKeywords &Keywords, tooling::Replacements &Fixes, const FormatToken *Tok, const std::string &Qualifier, tok::TokenKind QualifierType)
std::pair< tooling::Replacements, unsigned > analyze(TokenAnnotator &Annotator, SmallVectorImpl< AnnotatedLine * > &AnnotatedLines, FormatTokenLexer &Tokens) override
static tok::TokenKind getTokenFromQualifier(const std::string &Qualifier)
static void PrepareLeftRightOrdering(const std::vector< std::string > &Order, std::vector< std::string > &LeftOrder, std::vector< std::string > &RightOrder, std::vector< tok::TokenKind > &Qualifiers)
std::pair< tooling::Replacements, unsigned > analyze(TokenAnnotator &Annotator, SmallVectorImpl< AnnotatedLine * > &AnnotatedLines, FormatTokenLexer &Tokens) override
QualifierAlignmentFixer(const Environment &Env, const FormatStyle &Style, StringRef &Code, ArrayRef< tooling::Range > Ranges, unsigned FirstStartColumn, unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName)
AffectedRangeManager AffectedRangeMgr
const Environment & Env
std::pair< tooling::Replacements, unsigned > process(bool SkipAnnotation=false)
Determines extra information about the tokens comprising an UnwrappedLine.
A text replacement.
Definition: Replacement.h:83
Maintains a set of replacements that are conflict-free.
Definition: Replacement.h:212
llvm::Error add(const Replacement &R)
Adds a new replacement R to the current set of replacements.
Replacements merge(const Replacements &Replaces) const
Merges Replaces into the current replacements.
static void replaceToken(const SourceManager &SourceMgr, tooling::Replacements &Fixes, const CharSourceRange &Range, std::string NewText)
static bool endsWithSpace(const std::string &s)
static void insertQualifierAfter(const SourceManager &SourceMgr, tooling::Replacements &Fixes, const FormatToken *First, const std::string &Qualifier)
static void insertQualifierBefore(const SourceManager &SourceMgr, tooling::Replacements &Fixes, const FormatToken *First, const std::string &Qualifier)
static void rotateTokens(const SourceManager &SourceMgr, tooling::Replacements &Fixes, const FormatToken *First, const FormatToken *Last, bool Left)
static void removeToken(const SourceManager &SourceMgr, tooling::Replacements &Fixes, const FormatToken *First)
static bool isConfiguredQualifier(const FormatToken *const Tok, const std::vector< tok::TokenKind > &Qualifiers)
static bool startsWithSpace(const std::string &s)
static bool isQualifier(const FormatToken *const Tok)
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
std::vector< Range > calculateRangesAfterReplacements(const Replacements &Replaces, const std::vector< Range > &Ranges)
Calculates the new ranges after Replaces are applied.
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang's l...
Definition: FormatToken.h:935
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:55
std::vector< std::string > QualifierOrder
The order in which the qualifiers appear.
Definition: Format.h:3139
A wrapper around a Token storing information about the whitespace characters preceding it.
Definition: FormatToken.h:249
unsigned ClosesTemplateDeclaration
true if this is the ">" of "template<..>".
Definition: FormatToken.h:302
StringRef TokenText
The raw text of the token.
Definition: FormatToken.h:268
SourceLocation getStartOfNonWhitespace() const
Returns actual token start location without leading escaped newlines and whitespace.
Definition: FormatToken.h:728
FormatToken * getNextNonComment() const
Returns the next token ignoring comments.
Definition: FormatToken.h:754
FormatToken * getPreviousNonComment() const
Returns the previous token ignoring comments.
Definition: FormatToken.h:746
bool isSimpleTypeSpecifier() const
Determine whether the token is a simple-type-specifier.
Definition: FormatToken.cpp:39
FormatToken * Next
The next token in the unwrapped line.
Definition: FormatToken.h:506
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:543
bool isOneOf(A K1, B K2) const
Definition: FormatToken.h:555
unsigned ClosesRequiresClause
true if this is the last token within requires clause.
Definition: FormatToken.h:326
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
Definition: FormatToken.h:500