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