SortJavaScriptImports.cpp 17 KB

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