SortJavaScriptImports.cpp 17 KB

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