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