xref: /llvm-project/clang/lib/Format/SortJavaScriptImports.cpp (revision 03c59765b3eb2f2233728da8e16637f802147d66)
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/Basic/TokenKinds.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 
30 #define DEBUG_TYPE "format-formatter"
31 
32 namespace clang {
33 namespace format {
34 
35 class FormatTokenLexer;
36 
37 using clang::format::FormatStyle;
38 
39 // An imported symbol in a JavaScript ES6 import/export, possibly aliased.
40 struct JsImportedSymbol {
41   StringRef Symbol;
42   StringRef Alias;
43   SourceRange Range;
44 
45   bool operator==(const JsImportedSymbol &RHS) const {
46     // Ignore Range for comparison, it is only used to stitch code together,
47     // but imports at different code locations are still conceptually the same.
48     return Symbol == RHS.Symbol && Alias == RHS.Alias;
49   }
50 };
51 
52 // An ES6 module reference.
53 //
54 // ES6 implements a module system, where individual modules (~= source files)
55 // can reference other modules, either importing symbols from them, or exporting
56 // symbols from them:
57 //   import {foo} from 'foo';
58 //   export {foo};
59 //   export {bar} from 'bar';
60 //
61 // `export`s with URLs are syntactic sugar for an import of the symbol from the
62 // URL, followed by an export of the symbol, allowing this code to treat both
63 // statements more or less identically, with the exception being that `export`s
64 // are sorted last.
65 //
66 // imports and exports support individual symbols, but also a wildcard syntax:
67 //   import * as prefix from 'foo';
68 //   export * from 'bar';
69 //
70 // This struct represents both exports and imports to build up the information
71 // required for sorting module references.
72 struct JsModuleReference {
73   bool FormattingOff = false;
74   bool IsExport = false;
75   // Module references are sorted into these categories, in order.
76   enum ReferenceCategory {
77     SIDE_EFFECT,     // "import 'something';"
78     ABSOLUTE,        // from 'something'
79     RELATIVE_PARENT, // from '../*'
80     RELATIVE,        // from './*'
81     ALIAS,           // import X = A.B;
82   };
83   ReferenceCategory Category = ReferenceCategory::SIDE_EFFECT;
84   // The URL imported, e.g. `import .. from 'url';`. Empty for `export {a, b};`.
85   StringRef URL;
86   // Prefix from "import * as prefix". Empty for symbol imports and `export *`.
87   // Implies an empty names list.
88   StringRef Prefix;
89   // Default import from "import DefaultName from '...';".
90   StringRef DefaultImport;
91   // Symbols from `import {SymbolA, SymbolB, ...} from ...;`.
92   SmallVector<JsImportedSymbol, 1> Symbols;
93   // Whether some symbols were merged into this one. Controls if the module
94   // reference needs re-formatting.
95   bool SymbolsMerged = false;
96   // The source location just after { and just before } in the import.
97   // Extracted eagerly to allow modification of Symbols later on.
98   SourceLocation SymbolsStart, SymbolsEnd;
99   // Textual position of the import/export, including preceding and trailing
100   // comments.
101   SourceRange Range;
102 };
103 
104 bool operator<(const JsModuleReference &LHS, const JsModuleReference &RHS) {
105   if (LHS.IsExport != RHS.IsExport)
106     return LHS.IsExport < RHS.IsExport;
107   if (LHS.Category != RHS.Category)
108     return LHS.Category < RHS.Category;
109   if (LHS.Category == JsModuleReference::ReferenceCategory::SIDE_EFFECT ||
110       LHS.Category == JsModuleReference::ReferenceCategory::ALIAS)
111     // Side effect imports and aliases might be ordering sensitive. Consider
112     // them equal so that they maintain their relative order in the stable sort
113     // below. This retains transitivity because LHS.Category == RHS.Category
114     // here.
115     return false;
116   // Empty URLs sort *last* (for export {...};).
117   if (LHS.URL.empty() != RHS.URL.empty())
118     return LHS.URL.empty() < RHS.URL.empty();
119   if (int Res = LHS.URL.compare_insensitive(RHS.URL))
120     return Res < 0;
121   // '*' imports (with prefix) sort before {a, b, ...} imports.
122   if (LHS.Prefix.empty() != RHS.Prefix.empty())
123     return LHS.Prefix.empty() < RHS.Prefix.empty();
124   if (LHS.Prefix != RHS.Prefix)
125     return LHS.Prefix > RHS.Prefix;
126   return false;
127 }
128 
129 // JavaScriptImportSorter sorts JavaScript ES6 imports and exports. It is
130 // implemented as a TokenAnalyzer because ES6 imports have substantial syntactic
131 // structure, making it messy to sort them using regular expressions.
132 class JavaScriptImportSorter : public TokenAnalyzer {
133 public:
134   JavaScriptImportSorter(const Environment &Env, const FormatStyle &Style)
135       : TokenAnalyzer(Env, Style),
136         FileContents(Env.getSourceManager().getBufferData(Env.getFileID())) {}
137 
138   std::pair<tooling::Replacements, unsigned>
139   analyze(TokenAnnotator &Annotator,
140           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
141           FormatTokenLexer &Tokens) override {
142     tooling::Replacements Result;
143     AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
144 
145     const AdditionalKeywords &Keywords = Tokens.getKeywords();
146     SmallVector<JsModuleReference, 16> References;
147     AnnotatedLine *FirstNonImportLine;
148     std::tie(References, FirstNonImportLine) =
149         parseModuleReferences(Keywords, AnnotatedLines);
150 
151     if (References.empty())
152       return {Result, 0};
153 
154     // The text range of all parsed imports, to be replaced later.
155     SourceRange InsertionPoint = References[0].Range;
156     InsertionPoint.setEnd(References[References.size() - 1].Range.getEnd());
157 
158     References = sortModuleReferences(References);
159 
160     std::string ReferencesText;
161     for (unsigned I = 0, E = References.size(); I != E; ++I) {
162       JsModuleReference Reference = References[I];
163       appendReference(ReferencesText, Reference);
164       if (I + 1 < E) {
165         // Insert breaks between imports and exports.
166         ReferencesText += "\n";
167         // Separate imports groups with two line breaks, but keep all exports
168         // in a single group.
169         if (!Reference.IsExport &&
170             (Reference.IsExport != References[I + 1].IsExport ||
171              Reference.Category != References[I + 1].Category))
172           ReferencesText += "\n";
173       }
174     }
175     llvm::StringRef PreviousText = getSourceText(InsertionPoint);
176     if (ReferencesText == PreviousText)
177       return {Result, 0};
178 
179     // The loop above might collapse previously existing line breaks between
180     // import blocks, and thus shrink the file. SortIncludes must not shrink
181     // overall source length as there is currently no re-calculation of ranges
182     // after applying source sorting.
183     // This loop just backfills trailing spaces after the imports, which are
184     // harmless and will be stripped by the subsequent formatting pass.
185     // FIXME: A better long term fix is to re-calculate Ranges after sorting.
186     unsigned PreviousSize = PreviousText.size();
187     while (ReferencesText.size() < PreviousSize) {
188       ReferencesText += " ";
189     }
190 
191     // Separate references from the main code body of the file.
192     if (FirstNonImportLine && FirstNonImportLine->First->NewlinesBefore < 2 &&
193         !(FirstNonImportLine->First->is(tok::comment) &&
194           FirstNonImportLine->First->TokenText.trim() == "// clang-format on"))
195       ReferencesText += "\n";
196 
197     LLVM_DEBUG(llvm::dbgs() << "Replacing imports:\n"
198                             << PreviousText << "\nwith:\n"
199                             << ReferencesText << "\n");
200     auto Err = Result.add(tooling::Replacement(
201         Env.getSourceManager(), CharSourceRange::getCharRange(InsertionPoint),
202         ReferencesText));
203     // FIXME: better error handling. For now, just print error message and skip
204     // the replacement for the release version.
205     if (Err) {
206       llvm::errs() << llvm::toString(std::move(Err)) << "\n";
207       assert(false);
208     }
209 
210     return {Result, 0};
211   }
212 
213 private:
214   FormatToken *Current;
215   FormatToken *LineEnd;
216 
217   FormatToken invalidToken;
218 
219   StringRef FileContents;
220 
221   void skipComments() { Current = skipComments(Current); }
222 
223   FormatToken *skipComments(FormatToken *Tok) {
224     while (Tok && Tok->is(tok::comment))
225       Tok = Tok->Next;
226     return Tok;
227   }
228 
229   void nextToken() {
230     Current = Current->Next;
231     skipComments();
232     if (!Current || Current == LineEnd->Next) {
233       // Set the current token to an invalid token, so that further parsing on
234       // this line fails.
235       invalidToken.Tok.setKind(tok::unknown);
236       Current = &invalidToken;
237     }
238   }
239 
240   StringRef getSourceText(SourceRange Range) {
241     return getSourceText(Range.getBegin(), Range.getEnd());
242   }
243 
244   StringRef getSourceText(SourceLocation Begin, SourceLocation End) {
245     const SourceManager &SM = Env.getSourceManager();
246     return FileContents.substr(SM.getFileOffset(Begin),
247                                SM.getFileOffset(End) - SM.getFileOffset(Begin));
248   }
249 
250   // Sorts the given module references.
251   // Imports can have formatting disabled (FormattingOff), so the code below
252   // skips runs of "no-formatting" module references, and sorts/merges the
253   // references that have formatting enabled in individual chunks.
254   SmallVector<JsModuleReference, 16>
255   sortModuleReferences(const SmallVector<JsModuleReference, 16> &References) {
256     // Sort module references.
257     // Imports can have formatting disabled (FormattingOff), so the code below
258     // skips runs of "no-formatting" module references, and sorts other
259     // references per group.
260     const auto *Start = References.begin();
261     SmallVector<JsModuleReference, 16> ReferencesSorted;
262     while (Start != References.end()) {
263       while (Start != References.end() && Start->FormattingOff) {
264         // Skip over all imports w/ disabled formatting.
265         ReferencesSorted.push_back(*Start);
266         ++Start;
267       }
268       SmallVector<JsModuleReference, 16> SortChunk;
269       while (Start != References.end() && !Start->FormattingOff) {
270         // Skip over all imports w/ disabled formatting.
271         SortChunk.push_back(*Start);
272         ++Start;
273       }
274       llvm::stable_sort(SortChunk);
275       mergeModuleReferences(SortChunk);
276       ReferencesSorted.insert(ReferencesSorted.end(), SortChunk.begin(),
277                               SortChunk.end());
278     }
279     return ReferencesSorted;
280   }
281 
282   // Merge module references.
283   // After sorting, find all references that import named symbols from the
284   // same URL and merge their names. E.g.
285   //   import {X} from 'a';
286   //   import {Y} from 'a';
287   // should be rewritten to:
288   //   import {X, Y} from 'a';
289   // Note: this modifies the passed in ``References`` vector (by removing no
290   // longer needed references).
291   void mergeModuleReferences(SmallVector<JsModuleReference, 16> &References) {
292     if (References.empty())
293       return;
294     JsModuleReference *PreviousReference = References.begin();
295     auto *Reference = std::next(References.begin());
296     while (Reference != References.end()) {
297       // Skip:
298       //   import 'foo';
299       //   import * as foo from 'foo'; on either previous or this.
300       //   import Default from 'foo'; on either previous or this.
301       //   mismatching
302       if (Reference->Category == JsModuleReference::SIDE_EFFECT ||
303           PreviousReference->Category == JsModuleReference::SIDE_EFFECT ||
304           Reference->IsExport != PreviousReference->IsExport ||
305           !PreviousReference->Prefix.empty() || !Reference->Prefix.empty() ||
306           !PreviousReference->DefaultImport.empty() ||
307           !Reference->DefaultImport.empty() || Reference->Symbols.empty() ||
308           PreviousReference->URL != Reference->URL) {
309         PreviousReference = Reference;
310         ++Reference;
311         continue;
312       }
313       // Merge symbols from identical imports.
314       PreviousReference->Symbols.append(Reference->Symbols);
315       PreviousReference->SymbolsMerged = true;
316       // Remove the merged import.
317       Reference = References.erase(Reference);
318     }
319   }
320 
321   // Appends ``Reference`` to ``Buffer``.
322   void appendReference(std::string &Buffer, JsModuleReference &Reference) {
323     if (Reference.FormattingOff) {
324       Buffer +=
325           getSourceText(Reference.Range.getBegin(), Reference.Range.getEnd());
326       return;
327     }
328     // Sort the individual symbols within the import.
329     // E.g. `import {b, a} from 'x';` -> `import {a, b} from 'x';`
330     SmallVector<JsImportedSymbol, 1> Symbols = Reference.Symbols;
331     llvm::stable_sort(
332         Symbols, [&](const JsImportedSymbol &LHS, const JsImportedSymbol &RHS) {
333           return LHS.Symbol.compare_insensitive(RHS.Symbol) < 0;
334         });
335     if (!Reference.SymbolsMerged && Symbols == Reference.Symbols) {
336       // Symbols didn't change, just emit the entire module reference.
337       StringRef ReferenceStmt = getSourceText(Reference.Range);
338       Buffer += ReferenceStmt;
339       return;
340     }
341     // Stitch together the module reference start...
342     Buffer += getSourceText(Reference.Range.getBegin(), Reference.SymbolsStart);
343     // ... then the references in order ...
344     if (!Symbols.empty()) {
345       Buffer += getSourceText(Symbols.front().Range);
346       for (const JsImportedSymbol &Symbol : llvm::drop_begin(Symbols)) {
347         Buffer += ",";
348         Buffer += getSourceText(Symbol.Range);
349       }
350     }
351     // ... followed by the module reference end.
352     Buffer += getSourceText(Reference.SymbolsEnd, Reference.Range.getEnd());
353   }
354 
355   // Parses module references in the given lines. Returns the module references,
356   // and a pointer to the first "main code" line if that is adjacent to the
357   // affected lines of module references, nullptr otherwise.
358   std::pair<SmallVector<JsModuleReference, 16>, AnnotatedLine *>
359   parseModuleReferences(const AdditionalKeywords &Keywords,
360                         SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
361     SmallVector<JsModuleReference, 16> References;
362     SourceLocation Start;
363     AnnotatedLine *FirstNonImportLine = nullptr;
364     bool AnyImportAffected = false;
365     bool FormattingOff = false;
366     for (auto *Line : AnnotatedLines) {
367       assert(Line->First);
368       Current = Line->First;
369       LineEnd = Line->Last;
370       // clang-format comments toggle formatting on/off.
371       // This is tracked in FormattingOff here and on JsModuleReference.
372       while (Current && Current->is(tok::comment)) {
373         StringRef CommentText = Current->TokenText.trim();
374         if (CommentText == "// clang-format off") {
375           FormattingOff = true;
376         } else if (CommentText == "// clang-format on") {
377           FormattingOff = false;
378           // Special case: consider a trailing "clang-format on" line to be part
379           // of the module reference, so that it gets moved around together with
380           // it (as opposed to the next module reference, which might get sorted
381           // around).
382           if (!References.empty()) {
383             References.back().Range.setEnd(Current->Tok.getEndLoc());
384             Start = Current->Tok.getEndLoc().getLocWithOffset(1);
385           }
386         }
387         // Handle all clang-format comments on a line, e.g. for an empty block.
388         Current = Current->Next;
389       }
390       skipComments();
391       if (Start.isInvalid() || References.empty())
392         // After the first file level comment, consider line comments to be part
393         // of the import that immediately follows them by using the previously
394         // set Start.
395         Start = Line->First->Tok.getLocation();
396       if (!Current) {
397         // Only comments on this line. Could be the first non-import line.
398         FirstNonImportLine = Line;
399         continue;
400       }
401       JsModuleReference Reference;
402       Reference.FormattingOff = FormattingOff;
403       Reference.Range.setBegin(Start);
404       // References w/o a URL, e.g. export {A}, groups with RELATIVE.
405       Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
406       if (!parseModuleReference(Keywords, Reference)) {
407         if (!FirstNonImportLine)
408           FirstNonImportLine = Line; // if no comment before.
409         break;
410       }
411       FirstNonImportLine = nullptr;
412       AnyImportAffected = AnyImportAffected || Line->Affected;
413       Reference.Range.setEnd(LineEnd->Tok.getEndLoc());
414       LLVM_DEBUG({
415         llvm::dbgs() << "JsModuleReference: {"
416                      << "formatting_off: " << Reference.FormattingOff
417                      << ", is_export: " << Reference.IsExport
418                      << ", cat: " << Reference.Category
419                      << ", url: " << Reference.URL
420                      << ", prefix: " << Reference.Prefix;
421         for (const JsImportedSymbol &Symbol : Reference.Symbols)
422           llvm::dbgs() << ", " << Symbol.Symbol << " as " << Symbol.Alias;
423         llvm::dbgs() << ", text: " << getSourceText(Reference.Range);
424         llvm::dbgs() << "}\n";
425       });
426       References.push_back(Reference);
427       Start = SourceLocation();
428     }
429     // Sort imports if any import line was affected.
430     if (!AnyImportAffected)
431       References.clear();
432     return std::make_pair(References, FirstNonImportLine);
433   }
434 
435   // Parses a JavaScript/ECMAScript 6 module reference.
436   // See http://www.ecma-international.org/ecma-262/6.0/#sec-scripts-and-modules
437   // for grammar EBNF (production ModuleItem).
438   bool parseModuleReference(const AdditionalKeywords &Keywords,
439                             JsModuleReference &Reference) {
440     if (!Current || !Current->isOneOf(Keywords.kw_import, tok::kw_export))
441       return false;
442     Reference.IsExport = Current->is(tok::kw_export);
443 
444     nextToken();
445     if (Current->isStringLiteral() && !Reference.IsExport) {
446       // "import 'side-effect';"
447       Reference.Category = JsModuleReference::ReferenceCategory::SIDE_EFFECT;
448       Reference.URL =
449           Current->TokenText.substr(1, Current->TokenText.size() - 2);
450       return true;
451     }
452 
453     if (!parseModuleBindings(Keywords, Reference))
454       return false;
455 
456     if (Current->is(Keywords.kw_from)) {
457       // imports have a 'from' clause, exports might not.
458       nextToken();
459       if (!Current->isStringLiteral())
460         return false;
461       // URL = TokenText without the quotes.
462       Reference.URL =
463           Current->TokenText.substr(1, Current->TokenText.size() - 2);
464       if (Reference.URL.startswith(".."))
465         Reference.Category =
466             JsModuleReference::ReferenceCategory::RELATIVE_PARENT;
467       else if (Reference.URL.startswith("."))
468         Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
469       else
470         Reference.Category = JsModuleReference::ReferenceCategory::ABSOLUTE;
471     }
472     return true;
473   }
474 
475   bool parseModuleBindings(const AdditionalKeywords &Keywords,
476                            JsModuleReference &Reference) {
477     if (parseStarBinding(Keywords, Reference))
478       return true;
479     return parseNamedBindings(Keywords, Reference);
480   }
481 
482   bool parseStarBinding(const AdditionalKeywords &Keywords,
483                         JsModuleReference &Reference) {
484     // * as prefix from '...';
485     if (Current->isNot(tok::star))
486       return false;
487     nextToken();
488     if (Current->isNot(Keywords.kw_as))
489       return false;
490     nextToken();
491     if (Current->isNot(tok::identifier))
492       return false;
493     Reference.Prefix = Current->TokenText;
494     nextToken();
495     return true;
496   }
497 
498   bool parseNamedBindings(const AdditionalKeywords &Keywords,
499                           JsModuleReference &Reference) {
500     // eat a potential "import X, " prefix.
501     if (Current->is(tok::identifier)) {
502       Reference.DefaultImport = Current->TokenText;
503       nextToken();
504       if (Current->is(Keywords.kw_from))
505         return true;
506       // import X = A.B.C;
507       if (Current->is(tok::equal)) {
508         Reference.Category = JsModuleReference::ReferenceCategory::ALIAS;
509         nextToken();
510         while (Current->is(tok::identifier)) {
511           nextToken();
512           if (Current->is(tok::semi)) {
513             return true;
514           }
515           if (!Current->is(tok::period))
516             return false;
517           nextToken();
518         }
519       }
520       if (Current->isNot(tok::comma))
521         return false;
522       nextToken(); // eat comma.
523     }
524     if (Current->isNot(tok::l_brace))
525       return false;
526 
527     // {sym as alias, sym2 as ...} from '...';
528     Reference.SymbolsStart = Current->Tok.getEndLoc();
529     while (Current->isNot(tok::r_brace)) {
530       nextToken();
531       if (Current->is(tok::r_brace))
532         break;
533       if (!Current->isOneOf(tok::identifier, tok::kw_default))
534         return false;
535 
536       JsImportedSymbol Symbol;
537       Symbol.Symbol = Current->TokenText;
538       // Make sure to include any preceding comments.
539       Symbol.Range.setBegin(
540           Current->getPreviousNonComment()->Next->WhitespaceRange.getBegin());
541       nextToken();
542 
543       if (Current->is(Keywords.kw_as)) {
544         nextToken();
545         if (!Current->isOneOf(tok::identifier, tok::kw_default))
546           return false;
547         Symbol.Alias = Current->TokenText;
548         nextToken();
549       }
550       Symbol.Range.setEnd(Current->Tok.getLocation());
551       Reference.Symbols.push_back(Symbol);
552 
553       if (!Current->isOneOf(tok::r_brace, tok::comma))
554         return false;
555     }
556     Reference.SymbolsEnd = Current->Tok.getLocation();
557     // For named imports with a trailing comma ("import {X,}"), consider the
558     // comma to be the end of the import list, so that it doesn't get removed.
559     if (Current->Previous->is(tok::comma))
560       Reference.SymbolsEnd = Current->Previous->Tok.getLocation();
561     nextToken(); // consume r_brace
562     return true;
563   }
564 };
565 
566 tooling::Replacements sortJavaScriptImports(const FormatStyle &Style,
567                                             StringRef Code,
568                                             ArrayRef<tooling::Range> Ranges,
569                                             StringRef FileName) {
570   // FIXME: Cursor support.
571   auto Env = Environment::make(Code, FileName, Ranges);
572   if (!Env)
573     return {};
574   return JavaScriptImportSorter(*Env, Style).process().first;
575 }
576 
577 } // end namespace format
578 } // end namespace clang
579