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 15 #include "QualifierAlignmentFixer.h" 16 #include "FormatToken.h" 17 #include "llvm/Support/Debug.h" 18 #include "llvm/Support/Regex.h" 19 20 #include <algorithm> 21 22 #define DEBUG_TYPE "format-qualifier-alignment-fixer" 23 24 namespace clang { 25 namespace format { 26 27 QualifierAlignmentFixer::QualifierAlignmentFixer( 28 const Environment &Env, const FormatStyle &Style, StringRef &Code, 29 ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn, 30 unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName) 31 : TokenAnalyzer(Env, Style), Code(Code), Ranges(Ranges), 32 FirstStartColumn(FirstStartColumn), NextStartColumn(NextStartColumn), 33 LastStartColumn(LastStartColumn), FileName(FileName) { 34 std::vector<std::string> LeftOrder; 35 std::vector<std::string> RightOrder; 36 std::vector<tok::TokenKind> ConfiguredQualifierTokens; 37 PrepareLeftRightOrdering(Style.QualifierOrder, LeftOrder, RightOrder, 38 ConfiguredQualifierTokens); 39 40 // Handle the left and right Alignment Seperately 41 for (const auto &Qualifier : LeftOrder) { 42 Passes.emplace_back( 43 [&, Qualifier, ConfiguredQualifierTokens](const Environment &Env) { 44 return LeftRightQualifierAlignmentFixer(Env, Style, Qualifier, 45 ConfiguredQualifierTokens, 46 /*RightAlign=*/false) 47 .process(); 48 }); 49 } 50 for (const auto &Qualifier : RightOrder) { 51 Passes.emplace_back( 52 [&, Qualifier, ConfiguredQualifierTokens](const Environment &Env) { 53 return LeftRightQualifierAlignmentFixer(Env, Style, Qualifier, 54 ConfiguredQualifierTokens, 55 /*RightAlign=*/true) 56 .process(); 57 }); 58 } 59 } 60 61 std::pair<tooling::Replacements, unsigned> QualifierAlignmentFixer::analyze( 62 TokenAnnotator &Annotator, SmallVectorImpl<AnnotatedLine *> &AnnotatedLines, 63 FormatTokenLexer &Tokens) { 64 auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn, 65 NextStartColumn, LastStartColumn); 66 if (!Env) 67 return {}; 68 llvm::Optional<std::string> CurrentCode = None; 69 tooling::Replacements Fixes; 70 for (size_t I = 0, E = Passes.size(); I < E; ++I) { 71 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env); 72 auto NewCode = applyAllReplacements( 73 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first); 74 if (NewCode) { 75 Fixes = Fixes.merge(PassFixes.first); 76 if (I + 1 < E) { 77 CurrentCode = std::move(*NewCode); 78 Env = Environment::make( 79 *CurrentCode, FileName, 80 tooling::calculateRangesAfterReplacements(Fixes, Ranges), 81 FirstStartColumn, NextStartColumn, LastStartColumn); 82 if (!Env) 83 return {}; 84 } 85 } 86 } 87 88 // Don't make replacements that replace nothing. 89 tooling::Replacements NonNoOpFixes; 90 91 for (const tooling::Replacement &Fix : Fixes) { 92 StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength()); 93 94 if (!OriginalCode.equals(Fix.getReplacementText())) { 95 auto Err = NonNoOpFixes.add(Fix); 96 if (Err) 97 llvm::errs() << "Error adding replacements : " 98 << llvm::toString(std::move(Err)) << "\n"; 99 } 100 } 101 return {NonNoOpFixes, 0}; 102 } 103 104 static void replaceToken(const SourceManager &SourceMgr, 105 tooling::Replacements &Fixes, 106 const CharSourceRange &Range, std::string NewText) { 107 auto Replacement = tooling::Replacement(SourceMgr, Range, NewText); 108 auto Err = Fixes.add(Replacement); 109 110 if (Err) 111 llvm::errs() << "Error while rearranging Qualifier : " 112 << llvm::toString(std::move(Err)) << "\n"; 113 } 114 115 static void removeToken(const SourceManager &SourceMgr, 116 tooling::Replacements &Fixes, 117 const FormatToken *First) { 118 auto Range = CharSourceRange::getCharRange(First->getStartOfNonWhitespace(), 119 First->Tok.getEndLoc()); 120 replaceToken(SourceMgr, Fixes, Range, ""); 121 } 122 123 static void insertQualifierAfter(const SourceManager &SourceMgr, 124 tooling::Replacements &Fixes, 125 const FormatToken *First, 126 const std::string &Qualifier) { 127 FormatToken *Next = First->Next; 128 if (!Next) 129 return; 130 auto Range = CharSourceRange::getCharRange(Next->getStartOfNonWhitespace(), 131 Next->Tok.getEndLoc()); 132 133 std::string NewText = " " + Qualifier + " "; 134 NewText += Next->TokenText; 135 replaceToken(SourceMgr, Fixes, Range, NewText); 136 } 137 138 static void insertQualifierBefore(const SourceManager &SourceMgr, 139 tooling::Replacements &Fixes, 140 const FormatToken *First, 141 const std::string &Qualifier) { 142 auto Range = CharSourceRange::getCharRange(First->getStartOfNonWhitespace(), 143 First->Tok.getEndLoc()); 144 145 std::string NewText = " " + Qualifier + " "; 146 NewText += First->TokenText; 147 148 replaceToken(SourceMgr, Fixes, Range, NewText); 149 } 150 151 static bool endsWithSpace(const std::string &s) { 152 if (s.empty()) { 153 return false; 154 } 155 return isspace(s.back()); 156 } 157 158 static bool startsWithSpace(const std::string &s) { 159 if (s.empty()) { 160 return false; 161 } 162 return isspace(s.front()); 163 } 164 165 static void rotateTokens(const SourceManager &SourceMgr, 166 tooling::Replacements &Fixes, const FormatToken *First, 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 189 NewText += Tok->TokenText; 190 Tok = Tok->Next; 191 } 192 193 // If we are rotating to the right we move the first token to the back. 194 if (!Left) { 195 if (!NewText.empty() && !startsWithSpace(NewText)) { 196 NewText += " "; 197 } 198 NewText += First->TokenText; 199 } 200 201 auto Range = CharSourceRange::getCharRange(First->getStartOfNonWhitespace(), 202 Last->Tok.getEndLoc()); 203 204 replaceToken(SourceMgr, Fixes, Range, NewText); 205 } 206 207 const FormatToken *LeftRightQualifierAlignmentFixer::analyzeRight( 208 const SourceManager &SourceMgr, const AdditionalKeywords &Keywords, 209 tooling::Replacements &Fixes, const FormatToken *Tok, 210 const std::string &Qualifier, tok::TokenKind QualifierType) { 211 // We only need to think about streams that begin with a qualifier. 212 if (!Tok->is(QualifierType)) 213 return Tok; 214 // Don't concern yourself if nothing follows the qualifier. 215 if (!Tok->Next) 216 return Tok; 217 if (LeftRightQualifierAlignmentFixer::isPossibleMacro(Tok->Next)) 218 return Tok; 219 220 FormatToken *Qual = Tok->Next; 221 FormatToken *LastQual = Qual; 222 while (Qual && isQualifierOrType(Qual, ConfiguredQualifierTokens)) { 223 LastQual = Qual; 224 Qual = Qual->Next; 225 } 226 if (LastQual && Qual != LastQual) { 227 rotateTokens(SourceMgr, Fixes, Tok, LastQual, /*Left=*/false); 228 Tok = LastQual; 229 } else if (Tok->startsSequence(QualifierType, tok::identifier, 230 TT_TemplateOpener)) { 231 // Read from the TemplateOpener to 232 // TemplateCloser as in const ArrayRef<int> a; const ArrayRef<int> &a; 233 FormatToken *EndTemplate = Tok->Next->Next->MatchingParen; 234 if (EndTemplate) { 235 // Move to the end of any template class members e.g. 236 // `Foo<int>::iterator`. 237 if (EndTemplate->startsSequence(TT_TemplateCloser, tok::coloncolon, 238 tok::identifier)) 239 EndTemplate = EndTemplate->Next->Next; 240 } 241 if (EndTemplate && EndTemplate->Next && 242 !EndTemplate->Next->isOneOf(tok::equal, tok::l_paren)) { 243 insertQualifierAfter(SourceMgr, Fixes, EndTemplate, Qualifier); 244 // Remove the qualifier. 245 removeToken(SourceMgr, Fixes, Tok); 246 return Tok; 247 } 248 } else if (Tok->startsSequence(QualifierType, tok::identifier)) { 249 FormatToken *Next = Tok->Next; 250 // The case `const Foo` -> `Foo const` 251 // The case `const Foo *` -> `Foo const *` 252 // The case `const Foo &` -> `Foo const &` 253 // The case `const Foo &&` -> `Foo const &&` 254 // The case `const std::Foo &&` -> `std::Foo const &&` 255 // The case `const std::Foo<T> &&` -> `std::Foo<T> const &&` 256 while (Next && Next->isOneOf(tok::identifier, tok::coloncolon)) { 257 Next = Next->Next; 258 } 259 if (Next && Next->is(TT_TemplateOpener)) { 260 Next = Next->MatchingParen; 261 // Move to the end of any template class members e.g. 262 // `Foo<int>::iterator`. 263 if (Next && Next->startsSequence(TT_TemplateCloser, tok::coloncolon, 264 tok::identifier)) 265 return Tok; 266 assert(Next && "Missing template opener"); 267 Next = Next->Next; 268 } 269 if (Next && Next->isOneOf(tok::star, tok::amp, tok::ampamp) && 270 !Tok->Next->isOneOf(Keywords.kw_override, Keywords.kw_final)) { 271 if (Next->Previous && !Next->Previous->is(QualifierType)) { 272 insertQualifierAfter(SourceMgr, Fixes, Next->Previous, Qualifier); 273 removeToken(SourceMgr, Fixes, Tok); 274 } 275 return Next; 276 } 277 } 278 279 return Tok; 280 } 281 282 const FormatToken *LeftRightQualifierAlignmentFixer::analyzeLeft( 283 const SourceManager &SourceMgr, const AdditionalKeywords &Keywords, 284 tooling::Replacements &Fixes, const FormatToken *Tok, 285 const std::string &Qualifier, tok::TokenKind QualifierType) { 286 // if Tok is an identifier and possibly a macro then don't convert. 287 if (LeftRightQualifierAlignmentFixer::isPossibleMacro(Tok)) 288 return Tok; 289 290 const FormatToken *Qual = Tok; 291 const FormatToken *LastQual = Qual; 292 while (Qual && isQualifierOrType(Qual, ConfiguredQualifierTokens)) { 293 LastQual = Qual; 294 Qual = Qual->Next; 295 if (Qual && Qual->is(QualifierType)) 296 break; 297 } 298 299 if (!Qual) { 300 return Tok; 301 } 302 303 if (LastQual && Qual != LastQual && Qual->is(QualifierType)) { 304 rotateTokens(SourceMgr, Fixes, Tok, Qual, /*Left=*/true); 305 Tok = Qual->Next; 306 } else if (Tok->startsSequence(tok::identifier, QualifierType)) { 307 if (Tok->Next->Next && Tok->Next->Next->isOneOf(tok::identifier, tok::star, 308 tok::amp, tok::ampamp)) { 309 // Don't swap `::iterator const` to `::const iterator`. 310 if (!Tok->Previous || 311 (Tok->Previous && !Tok->Previous->is(tok::coloncolon))) { 312 rotateTokens(SourceMgr, Fixes, Tok, Tok->Next, /*Left=*/true); 313 Tok = Tok->Next; 314 } 315 } 316 } 317 if (Tok->is(TT_TemplateOpener) && Tok->Next && 318 (Tok->Next->is(tok::identifier) || Tok->Next->isSimpleTypeSpecifier()) && 319 Tok->Next->Next && Tok->Next->Next->is(QualifierType)) { 320 rotateTokens(SourceMgr, Fixes, Tok->Next, Tok->Next->Next, /*Left=*/true); 321 } 322 if (Tok->startsSequence(tok::identifier) && Tok->Next) { 323 if (Tok->Previous && 324 Tok->Previous->isOneOf(tok::star, tok::ampamp, tok::amp)) { 325 return Tok; 326 } 327 const FormatToken *Next = Tok->Next; 328 // The case `std::Foo<T> const` -> `const std::Foo<T> &&` 329 while (Next && Next->isOneOf(tok::identifier, tok::coloncolon)) 330 Next = Next->Next; 331 if (Next && Next->Previous && 332 Next->Previous->startsSequence(tok::identifier, TT_TemplateOpener)) { 333 // Read from to the end of the TemplateOpener to 334 // TemplateCloser const ArrayRef<int> a; const ArrayRef<int> &a; 335 if (Next->is(tok::comment) && Next->getNextNonComment()) 336 Next = Next->getNextNonComment(); 337 assert(Next->MatchingParen && "Missing template closer"); 338 Next = Next->MatchingParen->Next; 339 340 // Move to the end of any template class members e.g. 341 // `Foo<int>::iterator`. 342 if (Next && Next->startsSequence(tok::coloncolon, tok::identifier)) 343 Next = Next->Next->Next; 344 if (Next && Next->is(QualifierType)) { 345 // Remove the const. 346 insertQualifierBefore(SourceMgr, Fixes, Tok, Qualifier); 347 removeToken(SourceMgr, Fixes, Next); 348 return Next; 349 } 350 } 351 if (Next && Next->Next && 352 Next->Next->isOneOf(tok::amp, tok::ampamp, tok::star)) { 353 if (Next->is(QualifierType)) { 354 // Remove the qualifier. 355 insertQualifierBefore(SourceMgr, Fixes, Tok, Qualifier); 356 removeToken(SourceMgr, Fixes, Next); 357 return Next; 358 } 359 } 360 } 361 return Tok; 362 } 363 364 tok::TokenKind LeftRightQualifierAlignmentFixer::getTokenFromQualifier( 365 const std::string &Qualifier) { 366 // Don't let 'type' be an identifier, but steal typeof token. 367 return llvm::StringSwitch<tok::TokenKind>(Qualifier) 368 .Case("type", tok::kw_typeof) 369 .Case("const", tok::kw_const) 370 .Case("volatile", tok::kw_volatile) 371 .Case("static", tok::kw_static) 372 .Case("inline", tok::kw_inline) 373 .Case("constexpr", tok::kw_constexpr) 374 .Case("restrict", tok::kw_restrict) 375 .Default(tok::identifier); 376 } 377 378 LeftRightQualifierAlignmentFixer::LeftRightQualifierAlignmentFixer( 379 const Environment &Env, const FormatStyle &Style, 380 const std::string &Qualifier, 381 const std::vector<tok::TokenKind> &QualifierTokens, bool RightAlign) 382 : TokenAnalyzer(Env, Style), Qualifier(Qualifier), RightAlign(RightAlign), 383 ConfiguredQualifierTokens(QualifierTokens) {} 384 385 std::pair<tooling::Replacements, unsigned> 386 LeftRightQualifierAlignmentFixer::analyze( 387 TokenAnnotator &Annotator, SmallVectorImpl<AnnotatedLine *> &AnnotatedLines, 388 FormatTokenLexer &Tokens) { 389 tooling::Replacements Fixes; 390 const AdditionalKeywords &Keywords = Tokens.getKeywords(); 391 const SourceManager &SourceMgr = Env.getSourceManager(); 392 AffectedRangeMgr.computeAffectedLines(AnnotatedLines); 393 394 tok::TokenKind QualifierToken = getTokenFromQualifier(Qualifier); 395 assert(QualifierToken != tok::identifier && "Unrecognised Qualifier"); 396 397 for (AnnotatedLine *Line : AnnotatedLines) { 398 FormatToken *First = Line->First; 399 assert(First); 400 if (First->Finalized) 401 continue; 402 403 const auto *Last = Line->Last; 404 405 for (const auto *Tok = First; Tok && Tok != Last && Tok->Next; 406 Tok = Tok->Next) { 407 if (Tok->is(tok::comment)) 408 continue; 409 if (RightAlign) 410 Tok = analyzeRight(SourceMgr, Keywords, Fixes, Tok, Qualifier, 411 QualifierToken); 412 else 413 Tok = analyzeLeft(SourceMgr, Keywords, Fixes, Tok, Qualifier, 414 QualifierToken); 415 } 416 } 417 return {Fixes, 0}; 418 } 419 420 void QualifierAlignmentFixer::PrepareLeftRightOrdering( 421 const std::vector<std::string> &Order, std::vector<std::string> &LeftOrder, 422 std::vector<std::string> &RightOrder, 423 std::vector<tok::TokenKind> &Qualifiers) { 424 425 // Depending on the position of type in the order you need 426 // To iterate forward or backward through the order list as qualifier 427 // can push through each other. 428 // The Order list must define the position of "type" to signify 429 assert(llvm::is_contained(Order, "type") && 430 "QualifierOrder must contain type"); 431 // Split the Order list by type and reverse the left side. 432 433 bool left = true; 434 for (const auto &s : Order) { 435 if (s == "type") { 436 left = false; 437 continue; 438 } 439 440 tok::TokenKind QualifierToken = 441 LeftRightQualifierAlignmentFixer::getTokenFromQualifier(s); 442 if (QualifierToken != tok::kw_typeof && QualifierToken != tok::identifier) { 443 Qualifiers.push_back(QualifierToken); 444 } 445 446 if (left) 447 // Reverse the order for left aligned items. 448 LeftOrder.insert(LeftOrder.begin(), s); 449 else 450 RightOrder.push_back(s); 451 } 452 } 453 454 bool LeftRightQualifierAlignmentFixer::isQualifierOrType( 455 const FormatToken *Tok, const std::vector<tok::TokenKind> &specifiedTypes) { 456 return Tok && (Tok->isSimpleTypeSpecifier() || Tok->is(tok::kw_auto) || 457 llvm::is_contained(specifiedTypes, Tok->Tok.getKind())); 458 } 459 460 // If a token is an identifier and it's upper case, it could 461 // be a macro and hence we need to be able to ignore it. 462 bool LeftRightQualifierAlignmentFixer::isPossibleMacro(const FormatToken *Tok) { 463 if (!Tok) 464 return false; 465 if (!Tok->is(tok::identifier)) 466 return false; 467 if (Tok->TokenText.upper() == Tok->TokenText.str()) 468 return true; 469 return false; 470 } 471 472 } // namespace format 473 } // namespace clang 474