SortJavaScriptImports.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. //===--- SortJavaScriptImports.h - 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 "SortJavaScriptImports.h"
  16. #include "TokenAnalyzer.h"
  17. #include "TokenAnnotator.h"
  18. #include "clang/Basic/Diagnostic.h"
  19. #include "clang/Basic/DiagnosticOptions.h"
  20. #include "clang/Basic/LLVM.h"
  21. #include "clang/Basic/SourceLocation.h"
  22. #include "clang/Basic/SourceManager.h"
  23. #include "clang/Format/Format.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/Support/Debug.h"
  27. #include <algorithm>
  28. #include <string>
  29. #define DEBUG_TYPE "format-formatter"
  30. namespace clang {
  31. namespace format {
  32. class FormatTokenLexer;
  33. using clang::format::FormatStyle;
  34. // An imported symbol in a JavaScript ES6 import/export, possibly aliased.
  35. struct JsImportedSymbol {
  36. StringRef Symbol;
  37. StringRef Alias;
  38. SourceRange Range;
  39. bool operator==(const JsImportedSymbol &RHS) const {
  40. // Ignore Range for comparison, it is only used to stitch code together,
  41. // but imports at different code locations are still conceptually the same.
  42. return Symbol == RHS.Symbol && Alias == RHS.Alias;
  43. }
  44. };
  45. // An ES6 module reference.
  46. //
  47. // ES6 implements a module system, where individual modules (~= source files)
  48. // can reference other modules, either importing symbols from them, or exporting
  49. // symbols from them:
  50. // import {foo} from 'foo';
  51. // export {foo};
  52. // export {bar} from 'bar';
  53. //
  54. // `export`s with URLs are syntactic sugar for an import of the symbol from the
  55. // URL, followed by an export of the symbol, allowing this code to treat both
  56. // statements more or less identically, with the exception being that `export`s
  57. // are sorted last.
  58. //
  59. // imports and exports support individual symbols, but also a wildcard syntax:
  60. // import * as prefix from 'foo';
  61. // export * from 'bar';
  62. //
  63. // This struct represents both exports and imports to build up the information
  64. // required for sorting module references.
  65. struct JsModuleReference {
  66. bool IsExport = false;
  67. // Module references are sorted into these categories, in order.
  68. enum ReferenceCategory {
  69. SIDE_EFFECT, // "import 'something';"
  70. ABSOLUTE, // from 'something'
  71. RELATIVE_PARENT, // from '../*'
  72. RELATIVE, // from './*'
  73. };
  74. ReferenceCategory Category = ReferenceCategory::SIDE_EFFECT;
  75. // The URL imported, e.g. `import .. from 'url';`. Empty for `export {a, b};`.
  76. StringRef URL;
  77. // Prefix from "import * as prefix". Empty for symbol imports and `export *`.
  78. // Implies an empty names list.
  79. StringRef Prefix;
  80. // Symbols from `import {SymbolA, SymbolB, ...} from ...;`.
  81. SmallVector<JsImportedSymbol, 1> Symbols;
  82. // Textual position of the import/export, including preceding and trailing
  83. // comments.
  84. SourceRange Range;
  85. };
  86. bool operator<(const JsModuleReference &LHS, const JsModuleReference &RHS) {
  87. if (LHS.IsExport != RHS.IsExport)
  88. return LHS.IsExport < RHS.IsExport;
  89. if (LHS.Category != RHS.Category)
  90. return LHS.Category < RHS.Category;
  91. if (LHS.Category == JsModuleReference::ReferenceCategory::SIDE_EFFECT)
  92. // Side effect imports might be ordering sensitive. Consider them equal so
  93. // that they maintain their relative order in the stable sort below.
  94. // This retains transitivity because LHS.Category == RHS.Category here.
  95. return false;
  96. // Empty URLs sort *last* (for export {...};).
  97. if (LHS.URL.empty() != RHS.URL.empty())
  98. return LHS.URL.empty() < RHS.URL.empty();
  99. if (LHS.URL != RHS.URL)
  100. return LHS.URL < RHS.URL;
  101. // '*' imports (with prefix) sort before {a, b, ...} imports.
  102. if (LHS.Prefix.empty() != RHS.Prefix.empty())
  103. return LHS.Prefix.empty() < RHS.Prefix.empty();
  104. if (LHS.Prefix != RHS.Prefix)
  105. return LHS.Prefix > RHS.Prefix;
  106. return false;
  107. }
  108. // JavaScriptImportSorter sorts JavaScript ES6 imports and exports. It is
  109. // implemented as a TokenAnalyzer because ES6 imports have substantial syntactic
  110. // structure, making it messy to sort them using regular expressions.
  111. class JavaScriptImportSorter : public TokenAnalyzer {
  112. public:
  113. JavaScriptImportSorter(const Environment &Env, const FormatStyle &Style)
  114. : TokenAnalyzer(Env, Style),
  115. FileContents(Env.getSourceManager().getBufferData(Env.getFileID())) {}
  116. tooling::Replacements
  117. analyze(TokenAnnotator &Annotator,
  118. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  119. FormatTokenLexer &Tokens, tooling::Replacements &Result) override {
  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;
  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;
  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. Result.insert(tooling::Replacement(
  176. Env.getSourceManager(), CharSourceRange::getCharRange(InsertionPoint),
  177. ReferencesText));
  178. return Result;
  179. }
  180. private:
  181. FormatToken *Current;
  182. FormatToken *LineEnd;
  183. FormatToken invalidToken;
  184. StringRef FileContents;
  185. void skipComments() { Current = skipComments(Current); }
  186. FormatToken *skipComments(FormatToken *Tok) {
  187. while (Tok && Tok->is(tok::comment))
  188. Tok = Tok->Next;
  189. return Tok;
  190. }
  191. void nextToken() {
  192. Current = Current->Next;
  193. skipComments();
  194. if (!Current || Current == LineEnd->Next) {
  195. // Set the current token to an invalid token, so that further parsing on
  196. // this line fails.
  197. invalidToken.Tok.setKind(tok::unknown);
  198. Current = &invalidToken;
  199. }
  200. }
  201. StringRef getSourceText(SourceRange Range) {
  202. return getSourceText(Range.getBegin(), Range.getEnd());
  203. }
  204. StringRef getSourceText(SourceLocation Begin, SourceLocation End) {
  205. const SourceManager &SM = Env.getSourceManager();
  206. return FileContents.substr(SM.getFileOffset(Begin),
  207. SM.getFileOffset(End) - SM.getFileOffset(Begin));
  208. }
  209. // Appends ``Reference`` to ``Buffer``, returning true if text within the
  210. // ``Reference`` changed (e.g. symbol order).
  211. bool appendReference(std::string &Buffer, JsModuleReference &Reference) {
  212. // Sort the individual symbols within the import.
  213. // E.g. `import {b, a} from 'x';` -> `import {a, b} from 'x';`
  214. SmallVector<JsImportedSymbol, 1> Symbols = Reference.Symbols;
  215. std::stable_sort(
  216. Symbols.begin(), Symbols.end(),
  217. [&](const JsImportedSymbol &LHS, const JsImportedSymbol &RHS) {
  218. return LHS.Symbol < RHS.Symbol;
  219. });
  220. if (Symbols == Reference.Symbols) {
  221. // No change in symbol order.
  222. StringRef ReferenceStmt = getSourceText(Reference.Range);
  223. Buffer += ReferenceStmt;
  224. return false;
  225. }
  226. // Stitch together the module reference start...
  227. SourceLocation SymbolsStart = Reference.Symbols.front().Range.getBegin();
  228. SourceLocation SymbolsEnd = Reference.Symbols.back().Range.getEnd();
  229. Buffer += getSourceText(Reference.Range.getBegin(), SymbolsStart);
  230. // ... then the references in order ...
  231. for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) {
  232. if (I != Symbols.begin())
  233. Buffer += ",";
  234. Buffer += getSourceText(I->Range);
  235. }
  236. // ... followed by the module reference end.
  237. Buffer += getSourceText(SymbolsEnd, Reference.Range.getEnd());
  238. return true;
  239. }
  240. // Parses module references in the given lines. Returns the module references,
  241. // and a pointer to the first "main code" line if that is adjacent to the
  242. // affected lines of module references, nullptr otherwise.
  243. std::pair<SmallVector<JsModuleReference, 16>, AnnotatedLine*>
  244. parseModuleReferences(const AdditionalKeywords &Keywords,
  245. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  246. SmallVector<JsModuleReference, 16> References;
  247. SourceLocation Start;
  248. bool FoundLines = false;
  249. AnnotatedLine *FirstNonImportLine = nullptr;
  250. for (auto Line : AnnotatedLines) {
  251. if (!Line->Affected) {
  252. // Only sort the first contiguous block of affected lines.
  253. if (FoundLines)
  254. break;
  255. else
  256. continue;
  257. }
  258. Current = Line->First;
  259. LineEnd = Line->Last;
  260. skipComments();
  261. if (Start.isInvalid() || References.empty())
  262. // After the first file level comment, consider line comments to be part
  263. // of the import that immediately follows them by using the previously
  264. // set Start.
  265. Start = Line->First->Tok.getLocation();
  266. if (!Current)
  267. continue; // Only comments on this line.
  268. FoundLines = true;
  269. JsModuleReference Reference;
  270. Reference.Range.setBegin(Start);
  271. if (!parseModuleReference(Keywords, Reference)) {
  272. FirstNonImportLine = Line;
  273. break;
  274. }
  275. Reference.Range.setEnd(LineEnd->Tok.getEndLoc());
  276. 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. return std::make_pair(References, FirstNonImportLine);
  292. }
  293. // Parses a JavaScript/ECMAScript 6 module reference.
  294. // See http://www.ecma-international.org/ecma-262/6.0/#sec-scripts-and-modules
  295. // for grammar EBNF (production ModuleItem).
  296. bool parseModuleReference(const AdditionalKeywords &Keywords,
  297. JsModuleReference &Reference) {
  298. if (!Current || !Current->isOneOf(Keywords.kw_import, tok::kw_export))
  299. return false;
  300. Reference.IsExport = Current->is(tok::kw_export);
  301. nextToken();
  302. if (Current->isStringLiteral() && !Reference.IsExport) {
  303. // "import 'side-effect';"
  304. Reference.Category = JsModuleReference::ReferenceCategory::SIDE_EFFECT;
  305. Reference.URL =
  306. Current->TokenText.substr(1, Current->TokenText.size() - 2);
  307. return true;
  308. }
  309. if (!parseModuleBindings(Keywords, Reference))
  310. return false;
  311. nextToken();
  312. if (Current->is(Keywords.kw_from)) {
  313. // imports have a 'from' clause, exports might not.
  314. nextToken();
  315. if (!Current->isStringLiteral())
  316. return false;
  317. // URL = TokenText without the quotes.
  318. Reference.URL =
  319. Current->TokenText.substr(1, Current->TokenText.size() - 2);
  320. if (Reference.URL.startswith(".."))
  321. Reference.Category =
  322. JsModuleReference::ReferenceCategory::RELATIVE_PARENT;
  323. else if (Reference.URL.startswith("."))
  324. Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
  325. else
  326. Reference.Category = JsModuleReference::ReferenceCategory::ABSOLUTE;
  327. } else {
  328. // w/o URL groups with "empty".
  329. Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
  330. }
  331. return true;
  332. }
  333. bool parseModuleBindings(const AdditionalKeywords &Keywords,
  334. JsModuleReference &Reference) {
  335. if (parseStarBinding(Keywords, Reference))
  336. return true;
  337. return parseNamedBindings(Keywords, Reference);
  338. }
  339. bool parseStarBinding(const AdditionalKeywords &Keywords,
  340. JsModuleReference &Reference) {
  341. // * as prefix from '...';
  342. if (Current->isNot(tok::star))
  343. return false;
  344. nextToken();
  345. if (Current->isNot(Keywords.kw_as))
  346. return false;
  347. nextToken();
  348. if (Current->isNot(tok::identifier))
  349. return false;
  350. Reference.Prefix = Current->TokenText;
  351. return true;
  352. }
  353. bool parseNamedBindings(const AdditionalKeywords &Keywords,
  354. JsModuleReference &Reference) {
  355. if (Current->isNot(tok::l_brace))
  356. return false;
  357. // {sym as alias, sym2 as ...} from '...';
  358. nextToken();
  359. while (true) {
  360. if (Current->isNot(tok::identifier))
  361. return false;
  362. JsImportedSymbol Symbol;
  363. Symbol.Symbol = Current->TokenText;
  364. // Make sure to include any preceding comments.
  365. Symbol.Range.setBegin(
  366. Current->getPreviousNonComment()->Next->WhitespaceRange.getBegin());
  367. nextToken();
  368. if (Current->is(Keywords.kw_as)) {
  369. nextToken();
  370. if (Current->isNot(tok::identifier))
  371. return false;
  372. Symbol.Alias = Current->TokenText;
  373. nextToken();
  374. }
  375. Symbol.Range.setEnd(Current->Tok.getLocation());
  376. Reference.Symbols.push_back(Symbol);
  377. if (Current->is(tok::r_brace))
  378. return true;
  379. if (Current->isNot(tok::comma))
  380. return false;
  381. nextToken();
  382. }
  383. }
  384. };
  385. tooling::Replacements sortJavaScriptImports(const FormatStyle &Style,
  386. StringRef Code,
  387. ArrayRef<tooling::Range> Ranges,
  388. StringRef FileName) {
  389. // FIXME: Cursor support.
  390. std::unique_ptr<Environment> Env =
  391. Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
  392. JavaScriptImportSorter Sorter(*Env, Style);
  393. return Sorter.process();
  394. }
  395. } // end namespace format
  396. } // end namespace clang