SortJavaScriptImports.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. /// 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);
  121. const AdditionalKeywords &Keywords = Tokens.getKeywords();
  122. SmallVector<JsModuleReference, 16> References;
  123. AnnotatedLine *FirstNonImportLine;
  124. std::tie(References, FirstNonImportLine) =
  125. parseModuleReferences(Keywords, AnnotatedLines);
  126. if (References.empty())
  127. return {Result, 0};
  128. SmallVector<unsigned, 16> Indices;
  129. for (unsigned i = 0, e = References.size(); i != e; ++i)
  130. Indices.push_back(i);
  131. std::stable_sort(Indices.begin(), Indices.end(),
  132. [&](unsigned LHSI, unsigned RHSI) {
  133. return References[LHSI] < References[RHSI];
  134. });
  135. bool ReferencesInOrder = std::is_sorted(Indices.begin(), Indices.end());
  136. std::string ReferencesText;
  137. bool SymbolsInOrder = true;
  138. for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
  139. JsModuleReference Reference = References[Indices[i]];
  140. if (appendReference(ReferencesText, Reference))
  141. SymbolsInOrder = false;
  142. if (i + 1 < e) {
  143. // Insert breaks between imports and exports.
  144. ReferencesText += "\n";
  145. // Separate imports groups with two line breaks, but keep all exports
  146. // in a single group.
  147. if (!Reference.IsExport &&
  148. (Reference.IsExport != References[Indices[i + 1]].IsExport ||
  149. Reference.Category != References[Indices[i + 1]].Category))
  150. ReferencesText += "\n";
  151. }
  152. }
  153. if (ReferencesInOrder && SymbolsInOrder)
  154. return {Result, 0};
  155. SourceRange InsertionPoint = References[0].Range;
  156. InsertionPoint.setEnd(References[References.size() - 1].Range.getEnd());
  157. // The loop above might collapse previously existing line breaks between
  158. // import blocks, and thus shrink the file. SortIncludes must not shrink
  159. // overall source length as there is currently no re-calculation of ranges
  160. // after applying source sorting.
  161. // This loop just backfills trailing spaces after the imports, which are
  162. // harmless and will be stripped by the subsequent formatting pass.
  163. // FIXME: A better long term fix is to re-calculate Ranges after sorting.
  164. unsigned PreviousSize = getSourceText(InsertionPoint).size();
  165. while (ReferencesText.size() < PreviousSize) {
  166. ReferencesText += " ";
  167. }
  168. // Separate references from the main code body of the file.
  169. if (FirstNonImportLine && FirstNonImportLine->First->NewlinesBefore < 2)
  170. ReferencesText += "\n";
  171. DEBUG(llvm::dbgs() << "Replacing imports:\n"
  172. << getSourceText(InsertionPoint) << "\nwith:\n"
  173. << ReferencesText << "\n");
  174. auto Err = Result.add(tooling::Replacement(
  175. Env.getSourceManager(), CharSourceRange::getCharRange(InsertionPoint),
  176. ReferencesText));
  177. // FIXME: better error handling. For now, just print error message and skip
  178. // the replacement for the release version.
  179. if (Err) {
  180. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  181. assert(false);
  182. }
  183. return {Result, 0};
  184. }
  185. private:
  186. FormatToken *Current;
  187. FormatToken *LineEnd;
  188. FormatToken invalidToken;
  189. StringRef FileContents;
  190. void skipComments() { Current = skipComments(Current); }
  191. FormatToken *skipComments(FormatToken *Tok) {
  192. while (Tok && Tok->is(tok::comment))
  193. Tok = Tok->Next;
  194. return Tok;
  195. }
  196. void nextToken() {
  197. Current = Current->Next;
  198. skipComments();
  199. if (!Current || Current == LineEnd->Next) {
  200. // Set the current token to an invalid token, so that further parsing on
  201. // this line fails.
  202. invalidToken.Tok.setKind(tok::unknown);
  203. Current = &invalidToken;
  204. }
  205. }
  206. StringRef getSourceText(SourceRange Range) {
  207. return getSourceText(Range.getBegin(), Range.getEnd());
  208. }
  209. StringRef getSourceText(SourceLocation Begin, SourceLocation End) {
  210. const SourceManager &SM = Env.getSourceManager();
  211. return FileContents.substr(SM.getFileOffset(Begin),
  212. SM.getFileOffset(End) - SM.getFileOffset(Begin));
  213. }
  214. // Appends ``Reference`` to ``Buffer``, returning true if text within the
  215. // ``Reference`` changed (e.g. symbol order).
  216. bool appendReference(std::string &Buffer, JsModuleReference &Reference) {
  217. // Sort the individual symbols within the import.
  218. // E.g. `import {b, a} from 'x';` -> `import {a, b} from 'x';`
  219. SmallVector<JsImportedSymbol, 1> Symbols = Reference.Symbols;
  220. std::stable_sort(
  221. Symbols.begin(), Symbols.end(),
  222. [&](const JsImportedSymbol &LHS, const JsImportedSymbol &RHS) {
  223. return LHS.Symbol.compare_lower(RHS.Symbol) < 0;
  224. });
  225. if (Symbols == Reference.Symbols) {
  226. // No change in symbol order.
  227. StringRef ReferenceStmt = getSourceText(Reference.Range);
  228. Buffer += ReferenceStmt;
  229. return false;
  230. }
  231. // Stitch together the module reference start...
  232. SourceLocation SymbolsStart = Reference.Symbols.front().Range.getBegin();
  233. SourceLocation SymbolsEnd = Reference.Symbols.back().Range.getEnd();
  234. Buffer += getSourceText(Reference.Range.getBegin(), SymbolsStart);
  235. // ... then the references in order ...
  236. for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) {
  237. if (I != Symbols.begin())
  238. Buffer += ",";
  239. Buffer += getSourceText(I->Range);
  240. }
  241. // ... followed by the module reference end.
  242. Buffer += getSourceText(SymbolsEnd, Reference.Range.getEnd());
  243. return true;
  244. }
  245. // Parses module references in the given lines. Returns the module references,
  246. // and a pointer to the first "main code" line if that is adjacent to the
  247. // affected lines of module references, nullptr otherwise.
  248. std::pair<SmallVector<JsModuleReference, 16>, AnnotatedLine *>
  249. parseModuleReferences(const AdditionalKeywords &Keywords,
  250. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  251. SmallVector<JsModuleReference, 16> References;
  252. SourceLocation Start;
  253. AnnotatedLine *FirstNonImportLine = nullptr;
  254. bool AnyImportAffected = false;
  255. for (auto Line : AnnotatedLines) {
  256. Current = Line->First;
  257. LineEnd = Line->Last;
  258. skipComments();
  259. if (Start.isInvalid() || References.empty())
  260. // After the first file level comment, consider line comments to be part
  261. // of the import that immediately follows them by using the previously
  262. // set Start.
  263. Start = Line->First->Tok.getLocation();
  264. if (!Current) {
  265. // Only comments on this line. Could be the first non-import line.
  266. FirstNonImportLine = Line;
  267. continue;
  268. }
  269. JsModuleReference Reference;
  270. Reference.Range.setBegin(Start);
  271. if (!parseModuleReference(Keywords, Reference)) {
  272. if (!FirstNonImportLine)
  273. FirstNonImportLine = Line; // if no comment before.
  274. break;
  275. }
  276. FirstNonImportLine = nullptr;
  277. AnyImportAffected = AnyImportAffected || Line->Affected;
  278. Reference.Range.setEnd(LineEnd->Tok.getEndLoc());
  279. DEBUG({
  280. llvm::dbgs() << "JsModuleReference: {"
  281. << "is_export: " << Reference.IsExport
  282. << ", cat: " << Reference.Category
  283. << ", url: " << Reference.URL
  284. << ", prefix: " << Reference.Prefix;
  285. for (size_t i = 0; i < Reference.Symbols.size(); ++i)
  286. llvm::dbgs() << ", " << Reference.Symbols[i].Symbol << " as "
  287. << Reference.Symbols[i].Alias;
  288. llvm::dbgs() << ", text: " << getSourceText(Reference.Range);
  289. llvm::dbgs() << "}\n";
  290. });
  291. References.push_back(Reference);
  292. Start = SourceLocation();
  293. }
  294. // Sort imports if any import line was affected.
  295. if (!AnyImportAffected)
  296. References.clear();
  297. return std::make_pair(References, FirstNonImportLine);
  298. }
  299. // Parses a JavaScript/ECMAScript 6 module reference.
  300. // See http://www.ecma-international.org/ecma-262/6.0/#sec-scripts-and-modules
  301. // for grammar EBNF (production ModuleItem).
  302. bool parseModuleReference(const AdditionalKeywords &Keywords,
  303. JsModuleReference &Reference) {
  304. if (!Current || !Current->isOneOf(Keywords.kw_import, tok::kw_export))
  305. return false;
  306. Reference.IsExport = Current->is(tok::kw_export);
  307. nextToken();
  308. if (Current->isStringLiteral() && !Reference.IsExport) {
  309. // "import 'side-effect';"
  310. Reference.Category = JsModuleReference::ReferenceCategory::SIDE_EFFECT;
  311. Reference.URL =
  312. Current->TokenText.substr(1, Current->TokenText.size() - 2);
  313. return true;
  314. }
  315. if (!parseModuleBindings(Keywords, Reference))
  316. return false;
  317. if (Current->is(Keywords.kw_from)) {
  318. // imports have a 'from' clause, exports might not.
  319. nextToken();
  320. if (!Current->isStringLiteral())
  321. return false;
  322. // URL = TokenText without the quotes.
  323. Reference.URL =
  324. Current->TokenText.substr(1, Current->TokenText.size() - 2);
  325. if (Reference.URL.startswith(".."))
  326. Reference.Category =
  327. JsModuleReference::ReferenceCategory::RELATIVE_PARENT;
  328. else if (Reference.URL.startswith("."))
  329. Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
  330. else
  331. Reference.Category = JsModuleReference::ReferenceCategory::ABSOLUTE;
  332. } else {
  333. // w/o URL groups with "empty".
  334. Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
  335. }
  336. return true;
  337. }
  338. bool parseModuleBindings(const AdditionalKeywords &Keywords,
  339. JsModuleReference &Reference) {
  340. if (parseStarBinding(Keywords, Reference))
  341. return true;
  342. return parseNamedBindings(Keywords, Reference);
  343. }
  344. bool parseStarBinding(const AdditionalKeywords &Keywords,
  345. JsModuleReference &Reference) {
  346. // * as prefix from '...';
  347. if (Current->isNot(tok::star))
  348. return false;
  349. nextToken();
  350. if (Current->isNot(Keywords.kw_as))
  351. return false;
  352. nextToken();
  353. if (Current->isNot(tok::identifier))
  354. return false;
  355. Reference.Prefix = Current->TokenText;
  356. nextToken();
  357. return true;
  358. }
  359. bool parseNamedBindings(const AdditionalKeywords &Keywords,
  360. JsModuleReference &Reference) {
  361. if (Current->is(tok::identifier)) {
  362. nextToken();
  363. if (Current->is(Keywords.kw_from))
  364. return true;
  365. if (Current->isNot(tok::comma))
  366. return false;
  367. nextToken(); // eat comma.
  368. }
  369. if (Current->isNot(tok::l_brace))
  370. return false;
  371. // {sym as alias, sym2 as ...} from '...';
  372. while (Current->isNot(tok::r_brace)) {
  373. nextToken();
  374. if (Current->is(tok::r_brace))
  375. break;
  376. if (!Current->isOneOf(tok::identifier, tok::kw_default))
  377. return false;
  378. JsImportedSymbol Symbol;
  379. Symbol.Symbol = Current->TokenText;
  380. // Make sure to include any preceding comments.
  381. Symbol.Range.setBegin(
  382. Current->getPreviousNonComment()->Next->WhitespaceRange.getBegin());
  383. nextToken();
  384. if (Current->is(Keywords.kw_as)) {
  385. nextToken();
  386. if (!Current->isOneOf(tok::identifier, tok::kw_default))
  387. return false;
  388. Symbol.Alias = Current->TokenText;
  389. nextToken();
  390. }
  391. Symbol.Range.setEnd(Current->Tok.getLocation());
  392. Reference.Symbols.push_back(Symbol);
  393. if (!Current->isOneOf(tok::r_brace, tok::comma))
  394. return false;
  395. }
  396. nextToken(); // consume r_brace
  397. return true;
  398. }
  399. };
  400. tooling::Replacements sortJavaScriptImports(const FormatStyle &Style,
  401. StringRef Code,
  402. ArrayRef<tooling::Range> Ranges,
  403. StringRef FileName) {
  404. // FIXME: Cursor support.
  405. return JavaScriptImportSorter(Environment(Code, FileName, Ranges), Style)
  406. .process()
  407. .first;
  408. }
  409. } // end namespace format
  410. } // end namespace clang