1 //===--- SortJavaScriptImports.cpp - Sort ES6 Imports -----------*- 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 sort operation for JavaScript ES6 imports. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "SortJavaScriptImports.h" 15 #include "TokenAnalyzer.h" 16 #include "TokenAnnotator.h" 17 #include "clang/Basic/Diagnostic.h" 18 #include "clang/Basic/DiagnosticOptions.h" 19 #include "clang/Basic/LLVM.h" 20 #include "clang/Basic/SourceLocation.h" 21 #include "clang/Basic/SourceManager.h" 22 #include "clang/Format/Format.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/Support/Debug.h" 26 #include <algorithm> 27 #include <string> 28 29 #define DEBUG_TYPE "format-formatter" 30 31 namespace clang { 32 namespace format { 33 34 class FormatTokenLexer; 35 36 using clang::format::FormatStyle; 37 38 // An imported symbol in a JavaScript ES6 import/export, possibly aliased. 39 struct JsImportedSymbol { 40 StringRef Symbol; 41 StringRef Alias; 42 SourceRange Range; 43 44 bool operator==(const JsImportedSymbol &RHS) const { 45 // Ignore Range for comparison, it is only used to stitch code together, 46 // but imports at different code locations are still conceptually the same. 47 return Symbol == RHS.Symbol && Alias == RHS.Alias; 48 } 49 }; 50 51 // An ES6 module reference. 52 // 53 // ES6 implements a module system, where individual modules (~= source files) 54 // can reference other modules, either importing symbols from them, or exporting 55 // symbols from them: 56 // import {foo} from 'foo'; 57 // export {foo}; 58 // export {bar} from 'bar'; 59 // 60 // `export`s with URLs are syntactic sugar for an import of the symbol from the 61 // URL, followed by an export of the symbol, allowing this code to treat both 62 // statements more or less identically, with the exception being that `export`s 63 // are sorted last. 64 // 65 // imports and exports support individual symbols, but also a wildcard syntax: 66 // import * as prefix from 'foo'; 67 // export * from 'bar'; 68 // 69 // This struct represents both exports and imports to build up the information 70 // required for sorting module references. 71 struct JsModuleReference { 72 bool IsExport = false; 73 // Module references are sorted into these categories, in order. 74 enum ReferenceCategory { 75 SIDE_EFFECT, // "import 'something';" 76 ABSOLUTE, // from 'something' 77 RELATIVE_PARENT, // from '../*' 78 RELATIVE, // from './*' 79 }; 80 ReferenceCategory Category = ReferenceCategory::SIDE_EFFECT; 81 // The URL imported, e.g. `import .. from 'url';`. Empty for `export {a, b};`. 82 StringRef URL; 83 // Prefix from "import * as prefix". Empty for symbol imports and `export *`. 84 // Implies an empty names list. 85 StringRef Prefix; 86 // Default import from "import DefaultName from '...';". 87 StringRef DefaultImport; 88 // Symbols from `import {SymbolA, SymbolB, ...} from ...;`. 89 SmallVector<JsImportedSymbol, 1> Symbols; 90 // Whether some symbols were merged into this one. Controls if the module 91 // reference needs re-formatting. 92 bool SymbolsMerged = false; 93 // The source location just after { and just before } in the import. 94 // Extracted eagerly to allow modification of Symbols later on. 95 SourceLocation SymbolsStart, SymbolsEnd; 96 // Textual position of the import/export, including preceding and trailing 97 // comments. 98 SourceRange Range; 99 }; 100 101 bool operator<(const JsModuleReference &LHS, const JsModuleReference &RHS) { 102 if (LHS.IsExport != RHS.IsExport) 103 return LHS.IsExport < RHS.IsExport; 104 if (LHS.Category != RHS.Category) 105 return LHS.Category < RHS.Category; 106 if (LHS.Category == JsModuleReference::ReferenceCategory::SIDE_EFFECT) 107 // Side effect imports might be ordering sensitive. Consider them equal so 108 // that they maintain their relative order in the stable sort below. 109 // This retains transitivity because LHS.Category == RHS.Category here. 110 return false; 111 // Empty URLs sort *last* (for export {...};). 112 if (LHS.URL.empty() != RHS.URL.empty()) 113 return LHS.URL.empty() < RHS.URL.empty(); 114 if (int Res = LHS.URL.compare_lower(RHS.URL)) 115 return Res < 0; 116 // '*' imports (with prefix) sort before {a, b, ...} imports. 117 if (LHS.Prefix.empty() != RHS.Prefix.empty()) 118 return LHS.Prefix.empty() < RHS.Prefix.empty(); 119 if (LHS.Prefix != RHS.Prefix) 120 return LHS.Prefix > RHS.Prefix; 121 return false; 122 } 123 124 // JavaScriptImportSorter sorts JavaScript ES6 imports and exports. It is 125 // implemented as a TokenAnalyzer because ES6 imports have substantial syntactic 126 // structure, making it messy to sort them using regular expressions. 127 class JavaScriptImportSorter : public TokenAnalyzer { 128 public: 129 JavaScriptImportSorter(const Environment &Env, const FormatStyle &Style) 130 : TokenAnalyzer(Env, Style), 131 FileContents(Env.getSourceManager().getBufferData(Env.getFileID())) {} 132 133 std::pair<tooling::Replacements, unsigned> 134 analyze(TokenAnnotator &Annotator, 135 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines, 136 FormatTokenLexer &Tokens) override { 137 tooling::Replacements Result; 138 AffectedRangeMgr.computeAffectedLines(AnnotatedLines); 139 140 const AdditionalKeywords &Keywords = Tokens.getKeywords(); 141 SmallVector<JsModuleReference, 16> References; 142 AnnotatedLine *FirstNonImportLine; 143 std::tie(References, FirstNonImportLine) = 144 parseModuleReferences(Keywords, AnnotatedLines); 145 146 if (References.empty()) 147 return {Result, 0}; 148 149 SmallVector<unsigned, 16> Indices; 150 for (unsigned i = 0, e = References.size(); i != e; ++i) 151 Indices.push_back(i); 152 llvm::stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) { 153 return References[LHSI] < References[RHSI]; 154 }); 155 bool ReferencesInOrder = llvm::is_sorted(Indices); 156 157 mergeModuleReferences(References, Indices); 158 159 std::string ReferencesText; 160 bool SymbolsInOrder = true; 161 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 162 JsModuleReference Reference = References[Indices[i]]; 163 if (appendReference(ReferencesText, Reference)) 164 SymbolsInOrder = false; 165 if (i + 1 < e) { 166 // Insert breaks between imports and exports. 167 ReferencesText += "\n"; 168 // Separate imports groups with two line breaks, but keep all exports 169 // in a single group. 170 if (!Reference.IsExport && 171 (Reference.IsExport != References[Indices[i + 1]].IsExport || 172 Reference.Category != References[Indices[i + 1]].Category)) 173 ReferencesText += "\n"; 174 } 175 } 176 if (ReferencesInOrder && SymbolsInOrder) 177 return {Result, 0}; 178 179 SourceRange InsertionPoint = References[0].Range; 180 InsertionPoint.setEnd(References[References.size() - 1].Range.getEnd()); 181 182 // The loop above might collapse previously existing line breaks between 183 // import blocks, and thus shrink the file. SortIncludes must not shrink 184 // overall source length as there is currently no re-calculation of ranges 185 // after applying source sorting. 186 // This loop just backfills trailing spaces after the imports, which are 187 // harmless and will be stripped by the subsequent formatting pass. 188 // FIXME: A better long term fix is to re-calculate Ranges after sorting. 189 unsigned PreviousSize = getSourceText(InsertionPoint).size(); 190 while (ReferencesText.size() < PreviousSize) { 191 ReferencesText += " "; 192 } 193 194 // Separate references from the main code body of the file. 195 if (FirstNonImportLine && FirstNonImportLine->First->NewlinesBefore < 2) 196 ReferencesText += "\n"; 197 198 LLVM_DEBUG(llvm::dbgs() << "Replacing imports:\n" 199 << getSourceText(InsertionPoint) << "\nwith:\n" 200 << ReferencesText << "\n"); 201 auto Err = Result.add(tooling::Replacement( 202 Env.getSourceManager(), CharSourceRange::getCharRange(InsertionPoint), 203 ReferencesText)); 204 // FIXME: better error handling. For now, just print error message and skip 205 // the replacement for the release version. 206 if (Err) { 207 llvm::errs() << llvm::toString(std::move(Err)) << "\n"; 208 assert(false); 209 } 210 211 return {Result, 0}; 212 } 213 214 private: 215 FormatToken *Current; 216 FormatToken *LineEnd; 217 218 FormatToken invalidToken; 219 220 StringRef FileContents; 221 222 void skipComments() { Current = skipComments(Current); } 223 224 FormatToken *skipComments(FormatToken *Tok) { 225 while (Tok && Tok->is(tok::comment)) 226 Tok = Tok->Next; 227 return Tok; 228 } 229 230 void nextToken() { 231 Current = Current->Next; 232 skipComments(); 233 if (!Current || Current == LineEnd->Next) { 234 // Set the current token to an invalid token, so that further parsing on 235 // this line fails. 236 invalidToken.Tok.setKind(tok::unknown); 237 Current = &invalidToken; 238 } 239 } 240 241 StringRef getSourceText(SourceRange Range) { 242 return getSourceText(Range.getBegin(), Range.getEnd()); 243 } 244 245 StringRef getSourceText(SourceLocation Begin, SourceLocation End) { 246 const SourceManager &SM = Env.getSourceManager(); 247 return FileContents.substr(SM.getFileOffset(Begin), 248 SM.getFileOffset(End) - SM.getFileOffset(Begin)); 249 } 250 251 // Merge module references. 252 // After sorting, find all references that import named symbols from the 253 // same URL and merge their names. E.g. 254 // import {X} from 'a'; 255 // import {Y} from 'a'; 256 // should be rewritten to: 257 // import {X, Y} from 'a'; 258 // Note: this modifies the passed in ``Indices`` vector (by removing no longer 259 // needed references), but not ``References``. 260 // ``JsModuleReference``s that get merged have the ``SymbolsMerged`` flag 261 // flipped to true. 262 void mergeModuleReferences(SmallVector<JsModuleReference, 16> &References, 263 SmallVector<unsigned, 16> &Indices) { 264 JsModuleReference *PreviousReference = &References[Indices[0]]; 265 auto *It = std::next(Indices.begin()); 266 while (It != std::end(Indices)) { 267 JsModuleReference *Reference = &References[*It]; 268 // Skip: 269 // import 'foo'; 270 // import * as foo from 'foo'; on either previous or this. 271 // import Default from 'foo'; on either previous or this. 272 // mismatching 273 if (Reference->Category == JsModuleReference::SIDE_EFFECT || 274 !PreviousReference->Prefix.empty() || !Reference->Prefix.empty() || 275 !PreviousReference->DefaultImport.empty() || 276 !Reference->DefaultImport.empty() || Reference->Symbols.empty() || 277 PreviousReference->URL != Reference->URL) { 278 PreviousReference = Reference; 279 ++It; 280 continue; 281 } 282 // Merge symbols from identical imports. 283 PreviousReference->Symbols.append(Reference->Symbols); 284 PreviousReference->SymbolsMerged = true; 285 // Remove the merged import. 286 It = Indices.erase(It); 287 } 288 } 289 290 // Appends ``Reference`` to ``Buffer``, returning true if text within the 291 // ``Reference`` changed (e.g. symbol order). 292 bool appendReference(std::string &Buffer, JsModuleReference &Reference) { 293 // Sort the individual symbols within the import. 294 // E.g. `import {b, a} from 'x';` -> `import {a, b} from 'x';` 295 SmallVector<JsImportedSymbol, 1> Symbols = Reference.Symbols; 296 llvm::stable_sort( 297 Symbols, [&](const JsImportedSymbol &LHS, const JsImportedSymbol &RHS) { 298 return LHS.Symbol.compare_lower(RHS.Symbol) < 0; 299 }); 300 if (!Reference.SymbolsMerged && Symbols == Reference.Symbols) { 301 // Symbols didn't change, just emit the entire module reference. 302 StringRef ReferenceStmt = getSourceText(Reference.Range); 303 Buffer += ReferenceStmt; 304 return false; 305 } 306 // Stitch together the module reference start... 307 Buffer += getSourceText(Reference.Range.getBegin(), Reference.SymbolsStart); 308 // ... then the references in order ... 309 for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) { 310 if (I != Symbols.begin()) 311 Buffer += ","; 312 Buffer += getSourceText(I->Range); 313 } 314 // ... followed by the module reference end. 315 Buffer += getSourceText(Reference.SymbolsEnd, Reference.Range.getEnd()); 316 return true; 317 } 318 319 // Parses module references in the given lines. Returns the module references, 320 // and a pointer to the first "main code" line if that is adjacent to the 321 // affected lines of module references, nullptr otherwise. 322 std::pair<SmallVector<JsModuleReference, 16>, AnnotatedLine *> 323 parseModuleReferences(const AdditionalKeywords &Keywords, 324 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) { 325 SmallVector<JsModuleReference, 16> References; 326 SourceLocation Start; 327 AnnotatedLine *FirstNonImportLine = nullptr; 328 bool AnyImportAffected = false; 329 for (auto *Line : AnnotatedLines) { 330 Current = Line->First; 331 LineEnd = Line->Last; 332 skipComments(); 333 if (Start.isInvalid() || References.empty()) 334 // After the first file level comment, consider line comments to be part 335 // of the import that immediately follows them by using the previously 336 // set Start. 337 Start = Line->First->Tok.getLocation(); 338 if (!Current) { 339 // Only comments on this line. Could be the first non-import line. 340 FirstNonImportLine = Line; 341 continue; 342 } 343 JsModuleReference Reference; 344 Reference.Range.setBegin(Start); 345 if (!parseModuleReference(Keywords, Reference)) { 346 if (!FirstNonImportLine) 347 FirstNonImportLine = Line; // if no comment before. 348 break; 349 } 350 FirstNonImportLine = nullptr; 351 AnyImportAffected = AnyImportAffected || Line->Affected; 352 Reference.Range.setEnd(LineEnd->Tok.getEndLoc()); 353 LLVM_DEBUG({ 354 llvm::dbgs() << "JsModuleReference: {" 355 << "is_export: " << Reference.IsExport 356 << ", cat: " << Reference.Category 357 << ", url: " << Reference.URL 358 << ", prefix: " << Reference.Prefix; 359 for (size_t i = 0; i < Reference.Symbols.size(); ++i) 360 llvm::dbgs() << ", " << Reference.Symbols[i].Symbol << " as " 361 << Reference.Symbols[i].Alias; 362 llvm::dbgs() << ", text: " << getSourceText(Reference.Range); 363 llvm::dbgs() << "}\n"; 364 }); 365 References.push_back(Reference); 366 Start = SourceLocation(); 367 } 368 // Sort imports if any import line was affected. 369 if (!AnyImportAffected) 370 References.clear(); 371 return std::make_pair(References, FirstNonImportLine); 372 } 373 374 // Parses a JavaScript/ECMAScript 6 module reference. 375 // See http://www.ecma-international.org/ecma-262/6.0/#sec-scripts-and-modules 376 // for grammar EBNF (production ModuleItem). 377 bool parseModuleReference(const AdditionalKeywords &Keywords, 378 JsModuleReference &Reference) { 379 if (!Current || !Current->isOneOf(Keywords.kw_import, tok::kw_export)) 380 return false; 381 Reference.IsExport = Current->is(tok::kw_export); 382 383 nextToken(); 384 if (Current->isStringLiteral() && !Reference.IsExport) { 385 // "import 'side-effect';" 386 Reference.Category = JsModuleReference::ReferenceCategory::SIDE_EFFECT; 387 Reference.URL = 388 Current->TokenText.substr(1, Current->TokenText.size() - 2); 389 return true; 390 } 391 392 if (!parseModuleBindings(Keywords, Reference)) 393 return false; 394 395 if (Current->is(Keywords.kw_from)) { 396 // imports have a 'from' clause, exports might not. 397 nextToken(); 398 if (!Current->isStringLiteral()) 399 return false; 400 // URL = TokenText without the quotes. 401 Reference.URL = 402 Current->TokenText.substr(1, Current->TokenText.size() - 2); 403 if (Reference.URL.startswith("..")) 404 Reference.Category = 405 JsModuleReference::ReferenceCategory::RELATIVE_PARENT; 406 else if (Reference.URL.startswith(".")) 407 Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE; 408 else 409 Reference.Category = JsModuleReference::ReferenceCategory::ABSOLUTE; 410 } else { 411 // w/o URL groups with "empty". 412 Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE; 413 } 414 return true; 415 } 416 417 bool parseModuleBindings(const AdditionalKeywords &Keywords, 418 JsModuleReference &Reference) { 419 if (parseStarBinding(Keywords, Reference)) 420 return true; 421 return parseNamedBindings(Keywords, Reference); 422 } 423 424 bool parseStarBinding(const AdditionalKeywords &Keywords, 425 JsModuleReference &Reference) { 426 // * as prefix from '...'; 427 if (Current->isNot(tok::star)) 428 return false; 429 nextToken(); 430 if (Current->isNot(Keywords.kw_as)) 431 return false; 432 nextToken(); 433 if (Current->isNot(tok::identifier)) 434 return false; 435 Reference.Prefix = Current->TokenText; 436 nextToken(); 437 return true; 438 } 439 440 bool parseNamedBindings(const AdditionalKeywords &Keywords, 441 JsModuleReference &Reference) { 442 // eat a potential "import X, " prefix. 443 if (Current->is(tok::identifier)) { 444 Reference.DefaultImport = Current->TokenText; 445 nextToken(); 446 if (Current->is(Keywords.kw_from)) 447 return true; 448 if (Current->isNot(tok::comma)) 449 return false; 450 nextToken(); // eat comma. 451 } 452 if (Current->isNot(tok::l_brace)) 453 return false; 454 455 // {sym as alias, sym2 as ...} from '...'; 456 Reference.SymbolsStart = Current->Tok.getEndLoc(); 457 while (Current->isNot(tok::r_brace)) { 458 nextToken(); 459 if (Current->is(tok::r_brace)) 460 break; 461 if (!Current->isOneOf(tok::identifier, tok::kw_default)) 462 return false; 463 464 JsImportedSymbol Symbol; 465 Symbol.Symbol = Current->TokenText; 466 // Make sure to include any preceding comments. 467 Symbol.Range.setBegin( 468 Current->getPreviousNonComment()->Next->WhitespaceRange.getBegin()); 469 nextToken(); 470 471 if (Current->is(Keywords.kw_as)) { 472 nextToken(); 473 if (!Current->isOneOf(tok::identifier, tok::kw_default)) 474 return false; 475 Symbol.Alias = Current->TokenText; 476 nextToken(); 477 } 478 Symbol.Range.setEnd(Current->Tok.getLocation()); 479 Reference.Symbols.push_back(Symbol); 480 481 if (!Current->isOneOf(tok::r_brace, tok::comma)) 482 return false; 483 } 484 Reference.SymbolsEnd = Current->Tok.getLocation(); 485 // For named imports with a trailing comma ("import {X,}"), consider the 486 // comma to be the end of the import list, so that it doesn't get removed. 487 if (Current->Previous->is(tok::comma)) 488 Reference.SymbolsEnd = Current->Previous->Tok.getLocation(); 489 nextToken(); // consume r_brace 490 return true; 491 } 492 }; 493 494 tooling::Replacements sortJavaScriptImports(const FormatStyle &Style, 495 StringRef Code, 496 ArrayRef<tooling::Range> Ranges, 497 StringRef FileName) { 498 // FIXME: Cursor support. 499 return JavaScriptImportSorter(Environment(Code, FileName, Ranges), Style) 500 .process() 501 .first; 502 } 503 504 } // end namespace format 505 } // end namespace clang 506