xref: /llvm-project/clang/lib/Format/SortJavaScriptImports.cpp (revision fbc6f42dbee5d1d4ced30f520418c2b62942845a)
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           PreviousReference->Category == JsModuleReference::SIDE_EFFECT ||
275           Reference->IsExport != PreviousReference->IsExport ||
276           !PreviousReference->Prefix.empty() || !Reference->Prefix.empty() ||
277           !PreviousReference->DefaultImport.empty() ||
278           !Reference->DefaultImport.empty() || Reference->Symbols.empty() ||
279           PreviousReference->URL != Reference->URL) {
280         PreviousReference = Reference;
281         ++It;
282         continue;
283       }
284       // Merge symbols from identical imports.
285       PreviousReference->Symbols.append(Reference->Symbols);
286       PreviousReference->SymbolsMerged = true;
287       // Remove the merged import.
288       It = Indices.erase(It);
289     }
290   }
291 
292   // Appends ``Reference`` to ``Buffer``, returning true if text within the
293   // ``Reference`` changed (e.g. symbol order).
294   bool appendReference(std::string &Buffer, JsModuleReference &Reference) {
295     // Sort the individual symbols within the import.
296     // E.g. `import {b, a} from 'x';` -> `import {a, b} from 'x';`
297     SmallVector<JsImportedSymbol, 1> Symbols = Reference.Symbols;
298     llvm::stable_sort(
299         Symbols, [&](const JsImportedSymbol &LHS, const JsImportedSymbol &RHS) {
300           return LHS.Symbol.compare_lower(RHS.Symbol) < 0;
301         });
302     if (!Reference.SymbolsMerged && Symbols == Reference.Symbols) {
303       // Symbols didn't change, just emit the entire module reference.
304       StringRef ReferenceStmt = getSourceText(Reference.Range);
305       Buffer += ReferenceStmt;
306       return false;
307     }
308     // Stitch together the module reference start...
309     Buffer += getSourceText(Reference.Range.getBegin(), Reference.SymbolsStart);
310     // ... then the references in order ...
311     for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) {
312       if (I != Symbols.begin())
313         Buffer += ",";
314       Buffer += getSourceText(I->Range);
315     }
316     // ... followed by the module reference end.
317     Buffer += getSourceText(Reference.SymbolsEnd, Reference.Range.getEnd());
318     return true;
319   }
320 
321   // Parses module references in the given lines. Returns the module references,
322   // and a pointer to the first "main code" line if that is adjacent to the
323   // affected lines of module references, nullptr otherwise.
324   std::pair<SmallVector<JsModuleReference, 16>, AnnotatedLine *>
325   parseModuleReferences(const AdditionalKeywords &Keywords,
326                         SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
327     SmallVector<JsModuleReference, 16> References;
328     SourceLocation Start;
329     AnnotatedLine *FirstNonImportLine = nullptr;
330     bool AnyImportAffected = false;
331     for (auto *Line : AnnotatedLines) {
332       Current = Line->First;
333       LineEnd = Line->Last;
334       skipComments();
335       if (Start.isInvalid() || References.empty())
336         // After the first file level comment, consider line comments to be part
337         // of the import that immediately follows them by using the previously
338         // set Start.
339         Start = Line->First->Tok.getLocation();
340       if (!Current) {
341         // Only comments on this line. Could be the first non-import line.
342         FirstNonImportLine = Line;
343         continue;
344       }
345       JsModuleReference Reference;
346       Reference.Range.setBegin(Start);
347       if (!parseModuleReference(Keywords, Reference)) {
348         if (!FirstNonImportLine)
349           FirstNonImportLine = Line; // if no comment before.
350         break;
351       }
352       FirstNonImportLine = nullptr;
353       AnyImportAffected = AnyImportAffected || Line->Affected;
354       Reference.Range.setEnd(LineEnd->Tok.getEndLoc());
355       LLVM_DEBUG({
356         llvm::dbgs() << "JsModuleReference: {"
357                      << "is_export: " << Reference.IsExport
358                      << ", cat: " << Reference.Category
359                      << ", url: " << Reference.URL
360                      << ", prefix: " << Reference.Prefix;
361         for (size_t i = 0; i < Reference.Symbols.size(); ++i)
362           llvm::dbgs() << ", " << Reference.Symbols[i].Symbol << " as "
363                        << Reference.Symbols[i].Alias;
364         llvm::dbgs() << ", text: " << getSourceText(Reference.Range);
365         llvm::dbgs() << "}\n";
366       });
367       References.push_back(Reference);
368       Start = SourceLocation();
369     }
370     // Sort imports if any import line was affected.
371     if (!AnyImportAffected)
372       References.clear();
373     return std::make_pair(References, FirstNonImportLine);
374   }
375 
376   // Parses a JavaScript/ECMAScript 6 module reference.
377   // See http://www.ecma-international.org/ecma-262/6.0/#sec-scripts-and-modules
378   // for grammar EBNF (production ModuleItem).
379   bool parseModuleReference(const AdditionalKeywords &Keywords,
380                             JsModuleReference &Reference) {
381     if (!Current || !Current->isOneOf(Keywords.kw_import, tok::kw_export))
382       return false;
383     Reference.IsExport = Current->is(tok::kw_export);
384 
385     nextToken();
386     if (Current->isStringLiteral() && !Reference.IsExport) {
387       // "import 'side-effect';"
388       Reference.Category = JsModuleReference::ReferenceCategory::SIDE_EFFECT;
389       Reference.URL =
390           Current->TokenText.substr(1, Current->TokenText.size() - 2);
391       return true;
392     }
393 
394     if (!parseModuleBindings(Keywords, Reference))
395       return false;
396 
397     if (Current->is(Keywords.kw_from)) {
398       // imports have a 'from' clause, exports might not.
399       nextToken();
400       if (!Current->isStringLiteral())
401         return false;
402       // URL = TokenText without the quotes.
403       Reference.URL =
404           Current->TokenText.substr(1, Current->TokenText.size() - 2);
405       if (Reference.URL.startswith(".."))
406         Reference.Category =
407             JsModuleReference::ReferenceCategory::RELATIVE_PARENT;
408       else if (Reference.URL.startswith("."))
409         Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
410       else
411         Reference.Category = JsModuleReference::ReferenceCategory::ABSOLUTE;
412     } else {
413       // w/o URL groups with "empty".
414       Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
415     }
416     return true;
417   }
418 
419   bool parseModuleBindings(const AdditionalKeywords &Keywords,
420                            JsModuleReference &Reference) {
421     if (parseStarBinding(Keywords, Reference))
422       return true;
423     return parseNamedBindings(Keywords, Reference);
424   }
425 
426   bool parseStarBinding(const AdditionalKeywords &Keywords,
427                         JsModuleReference &Reference) {
428     // * as prefix from '...';
429     if (Current->isNot(tok::star))
430       return false;
431     nextToken();
432     if (Current->isNot(Keywords.kw_as))
433       return false;
434     nextToken();
435     if (Current->isNot(tok::identifier))
436       return false;
437     Reference.Prefix = Current->TokenText;
438     nextToken();
439     return true;
440   }
441 
442   bool parseNamedBindings(const AdditionalKeywords &Keywords,
443                           JsModuleReference &Reference) {
444     // eat a potential "import X, " prefix.
445     if (Current->is(tok::identifier)) {
446       Reference.DefaultImport = Current->TokenText;
447       nextToken();
448       if (Current->is(Keywords.kw_from))
449         return true;
450       if (Current->isNot(tok::comma))
451         return false;
452       nextToken(); // eat comma.
453     }
454     if (Current->isNot(tok::l_brace))
455       return false;
456 
457     // {sym as alias, sym2 as ...} from '...';
458     Reference.SymbolsStart = Current->Tok.getEndLoc();
459     while (Current->isNot(tok::r_brace)) {
460       nextToken();
461       if (Current->is(tok::r_brace))
462         break;
463       if (!Current->isOneOf(tok::identifier, tok::kw_default))
464         return false;
465 
466       JsImportedSymbol Symbol;
467       Symbol.Symbol = Current->TokenText;
468       // Make sure to include any preceding comments.
469       Symbol.Range.setBegin(
470           Current->getPreviousNonComment()->Next->WhitespaceRange.getBegin());
471       nextToken();
472 
473       if (Current->is(Keywords.kw_as)) {
474         nextToken();
475         if (!Current->isOneOf(tok::identifier, tok::kw_default))
476           return false;
477         Symbol.Alias = Current->TokenText;
478         nextToken();
479       }
480       Symbol.Range.setEnd(Current->Tok.getLocation());
481       Reference.Symbols.push_back(Symbol);
482 
483       if (!Current->isOneOf(tok::r_brace, tok::comma))
484         return false;
485     }
486     Reference.SymbolsEnd = Current->Tok.getLocation();
487     // For named imports with a trailing comma ("import {X,}"), consider the
488     // comma to be the end of the import list, so that it doesn't get removed.
489     if (Current->Previous->is(tok::comma))
490       Reference.SymbolsEnd = Current->Previous->Tok.getLocation();
491     nextToken(); // consume r_brace
492     return true;
493   }
494 };
495 
496 tooling::Replacements sortJavaScriptImports(const FormatStyle &Style,
497                                             StringRef Code,
498                                             ArrayRef<tooling::Range> Ranges,
499                                             StringRef FileName) {
500   // FIXME: Cursor support.
501   return JavaScriptImportSorter(Environment(Code, FileName, Ranges), Style)
502       .process()
503       .first;
504 }
505 
506 } // end namespace format
507 } // end namespace clang
508