xref: /llvm-project/clang/lib/Format/SortJavaScriptImports.cpp (revision d079995dd032e991bac295fb1a879efd32f20460)
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     // FormatToken.Tok starts out in an uninitialized state.
138     invalidToken.Tok.startToken();
139   }
140 
141   std::pair<tooling::Replacements, unsigned>
142   analyze(TokenAnnotator &Annotator,
143           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
144           FormatTokenLexer &Tokens) override {
145     tooling::Replacements Result;
146     AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
147 
148     const AdditionalKeywords &Keywords = Tokens.getKeywords();
149     SmallVector<JsModuleReference, 16> References;
150     AnnotatedLine *FirstNonImportLine;
151     std::tie(References, FirstNonImportLine) =
152         parseModuleReferences(Keywords, AnnotatedLines);
153 
154     if (References.empty())
155       return {Result, 0};
156 
157     // The text range of all parsed imports, to be replaced later.
158     SourceRange InsertionPoint = References[0].Range;
159     InsertionPoint.setEnd(References[References.size() - 1].Range.getEnd());
160 
161     References = sortModuleReferences(References);
162 
163     std::string ReferencesText;
164     for (unsigned I = 0, E = References.size(); I != E; ++I) {
165       JsModuleReference Reference = References[I];
166       appendReference(ReferencesText, Reference);
167       if (I + 1 < E) {
168         // Insert breaks between imports and exports.
169         ReferencesText += "\n";
170         // Separate imports groups with two line breaks, but keep all exports
171         // in a single group.
172         if (!Reference.IsExport &&
173             (Reference.IsExport != References[I + 1].IsExport ||
174              Reference.Category != References[I + 1].Category))
175           ReferencesText += "\n";
176       }
177     }
178     llvm::StringRef PreviousText = getSourceText(InsertionPoint);
179     if (ReferencesText == PreviousText)
180       return {Result, 0};
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 = PreviousText.size();
190     while (ReferencesText.size() < PreviousSize)
191       ReferencesText += " ";
192 
193     // Separate references from the main code body of the file.
194     if (FirstNonImportLine && FirstNonImportLine->First->NewlinesBefore < 2 &&
195         !(FirstNonImportLine->First->is(tok::comment) &&
196           FirstNonImportLine->First->TokenText.trim() == "// clang-format on"))
197       ReferencesText += "\n";
198 
199     LLVM_DEBUG(llvm::dbgs() << "Replacing imports:\n"
200                             << PreviousText << "\nwith:\n"
201                             << ReferencesText << "\n");
202     auto Err = Result.add(tooling::Replacement(
203         Env.getSourceManager(), CharSourceRange::getCharRange(InsertionPoint),
204         ReferencesText));
205     // FIXME: better error handling. For now, just print error message and skip
206     // the replacement for the release version.
207     if (Err) {
208       llvm::errs() << llvm::toString(std::move(Err)) << "\n";
209       assert(false);
210     }
211 
212     return {Result, 0};
213   }
214 
215 private:
216   FormatToken *Current;
217   FormatToken *LineEnd;
218 
219   FormatToken invalidToken;
220 
221   StringRef FileContents;
222 
223   void skipComments() { Current = skipComments(Current); }
224 
225   FormatToken *skipComments(FormatToken *Tok) {
226     while (Tok && Tok->is(tok::comment))
227       Tok = Tok->Next;
228     return Tok;
229   }
230 
231   void nextToken() {
232     Current = Current->Next;
233     skipComments();
234     if (!Current || Current == LineEnd->Next) {
235       // Set the current token to an invalid token, so that further parsing on
236       // this line fails.
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   // Sorts the given module references.
252   // Imports can have formatting disabled (FormattingOff), so the code below
253   // skips runs of "no-formatting" module references, and sorts/merges the
254   // references that have formatting enabled in individual chunks.
255   SmallVector<JsModuleReference, 16>
256   sortModuleReferences(const SmallVector<JsModuleReference, 16> &References) {
257     // Sort module references.
258     // Imports can have formatting disabled (FormattingOff), so the code below
259     // skips runs of "no-formatting" module references, and sorts other
260     // references per group.
261     const auto *Start = References.begin();
262     SmallVector<JsModuleReference, 16> ReferencesSorted;
263     while (Start != References.end()) {
264       while (Start != References.end() && Start->FormattingOff) {
265         // Skip over all imports w/ disabled formatting.
266         ReferencesSorted.push_back(*Start);
267         ++Start;
268       }
269       SmallVector<JsModuleReference, 16> SortChunk;
270       while (Start != References.end() && !Start->FormattingOff) {
271         // Skip over all imports w/ disabled formatting.
272         SortChunk.push_back(*Start);
273         ++Start;
274       }
275       llvm::stable_sort(SortChunk);
276       mergeModuleReferences(SortChunk);
277       ReferencesSorted.insert(ReferencesSorted.end(), SortChunk.begin(),
278                               SortChunk.end());
279     }
280     return ReferencesSorted;
281   }
282 
283   // Merge module references.
284   // After sorting, find all references that import named symbols from the
285   // same URL and merge their names. E.g.
286   //   import {X} from 'a';
287   //   import {Y} from 'a';
288   // should be rewritten to:
289   //   import {X, Y} from 'a';
290   // Note: this modifies the passed in ``References`` vector (by removing no
291   // longer needed references).
292   void mergeModuleReferences(SmallVector<JsModuleReference, 16> &References) {
293     if (References.empty())
294       return;
295     JsModuleReference *PreviousReference = References.begin();
296     auto *Reference = std::next(References.begin());
297     while (Reference != References.end()) {
298       // Skip:
299       //   import 'foo';
300       //   import * as foo from 'foo'; on either previous or this.
301       //   import Default from 'foo'; on either previous or this.
302       //   mismatching
303       if (Reference->Category == JsModuleReference::SIDE_EFFECT ||
304           PreviousReference->Category == JsModuleReference::SIDE_EFFECT ||
305           Reference->IsExport != PreviousReference->IsExport ||
306           !PreviousReference->Prefix.empty() || !Reference->Prefix.empty() ||
307           !PreviousReference->DefaultImport.empty() ||
308           !Reference->DefaultImport.empty() || Reference->Symbols.empty() ||
309           PreviousReference->URL != Reference->URL) {
310         PreviousReference = Reference;
311         ++Reference;
312         continue;
313       }
314       // Merge symbols from identical imports.
315       PreviousReference->Symbols.append(Reference->Symbols);
316       PreviousReference->SymbolsMerged = true;
317       // Remove the merged import.
318       Reference = References.erase(Reference);
319     }
320   }
321 
322   // Appends ``Reference`` to ``Buffer``.
323   void appendReference(std::string &Buffer, JsModuleReference &Reference) {
324     if (Reference.FormattingOff) {
325       Buffer +=
326           getSourceText(Reference.Range.getBegin(), Reference.Range.getEnd());
327       return;
328     }
329     // Sort the individual symbols within the import.
330     // E.g. `import {b, a} from 'x';` -> `import {a, b} from 'x';`
331     SmallVector<JsImportedSymbol, 1> Symbols = Reference.Symbols;
332     llvm::stable_sort(
333         Symbols, [&](const JsImportedSymbol &LHS, const JsImportedSymbol &RHS) {
334           return LHS.Symbol.compare_insensitive(RHS.Symbol) < 0;
335         });
336     if (!Reference.SymbolsMerged && Symbols == Reference.Symbols) {
337       // Symbols didn't change, just emit the entire module reference.
338       StringRef ReferenceStmt = getSourceText(Reference.Range);
339       Buffer += ReferenceStmt;
340       return;
341     }
342     // Stitch together the module reference start...
343     Buffer += getSourceText(Reference.Range.getBegin(), Reference.SymbolsStart);
344     // ... then the references in order ...
345     if (!Symbols.empty()) {
346       Buffer += getSourceText(Symbols.front().Range);
347       for (const JsImportedSymbol &Symbol : llvm::drop_begin(Symbols)) {
348         Buffer += ",";
349         Buffer += getSourceText(Symbol.Range);
350       }
351     }
352     // ... followed by the module reference end.
353     Buffer += getSourceText(Reference.SymbolsEnd, Reference.Range.getEnd());
354   }
355 
356   // Parses module references in the given lines. Returns the module references,
357   // and a pointer to the first "main code" line if that is adjacent to the
358   // affected lines of module references, nullptr otherwise.
359   std::pair<SmallVector<JsModuleReference, 16>, AnnotatedLine *>
360   parseModuleReferences(const AdditionalKeywords &Keywords,
361                         SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
362     SmallVector<JsModuleReference, 16> References;
363     SourceLocation Start;
364     AnnotatedLine *FirstNonImportLine = nullptr;
365     bool AnyImportAffected = false;
366     bool FormattingOff = false;
367     for (auto *Line : AnnotatedLines) {
368       assert(Line->First);
369       Current = Line->First;
370       LineEnd = Line->Last;
371       // clang-format comments toggle formatting on/off.
372       // This is tracked in FormattingOff here and on JsModuleReference.
373       while (Current && Current->is(tok::comment)) {
374         StringRef CommentText = Current->TokenText.trim();
375         if (CommentText == "// clang-format off") {
376           FormattingOff = true;
377         } else if (CommentText == "// clang-format on") {
378           FormattingOff = false;
379           // Special case: consider a trailing "clang-format on" line to be part
380           // of the module reference, so that it gets moved around together with
381           // it (as opposed to the next module reference, which might get sorted
382           // around).
383           if (!References.empty()) {
384             References.back().Range.setEnd(Current->Tok.getEndLoc());
385             Start = Current->Tok.getEndLoc().getLocWithOffset(1);
386           }
387         }
388         // Handle all clang-format comments on a line, e.g. for an empty block.
389         Current = Current->Next;
390       }
391       skipComments();
392       if (Start.isInvalid() || References.empty())
393         // After the first file level comment, consider line comments to be part
394         // of the import that immediately follows them by using the previously
395         // set Start.
396         Start = Line->First->Tok.getLocation();
397       if (!Current) {
398         // Only comments on this line. Could be the first non-import line.
399         FirstNonImportLine = Line;
400         continue;
401       }
402       JsModuleReference Reference;
403       Reference.FormattingOff = FormattingOff;
404       Reference.Range.setBegin(Start);
405       // References w/o a URL, e.g. export {A}, groups with RELATIVE.
406       Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
407       if (!parseModuleReference(Keywords, Reference)) {
408         if (!FirstNonImportLine)
409           FirstNonImportLine = Line; // if no comment before.
410         break;
411       }
412       FirstNonImportLine = nullptr;
413       AnyImportAffected = AnyImportAffected || Line->Affected;
414       Reference.Range.setEnd(LineEnd->Tok.getEndLoc());
415       LLVM_DEBUG({
416         llvm::dbgs() << "JsModuleReference: {"
417                      << "formatting_off: " << Reference.FormattingOff
418                      << ", is_export: " << Reference.IsExport
419                      << ", cat: " << Reference.Category
420                      << ", url: " << Reference.URL
421                      << ", prefix: " << Reference.Prefix;
422         for (const JsImportedSymbol &Symbol : Reference.Symbols)
423           llvm::dbgs() << ", " << Symbol.Symbol << " as " << Symbol.Alias;
424         llvm::dbgs() << ", text: " << getSourceText(Reference.Range);
425         llvm::dbgs() << "}\n";
426       });
427       References.push_back(Reference);
428       Start = SourceLocation();
429     }
430     // Sort imports if any import line was affected.
431     if (!AnyImportAffected)
432       References.clear();
433     return std::make_pair(References, FirstNonImportLine);
434   }
435 
436   // Parses a JavaScript/ECMAScript 6 module reference.
437   // See http://www.ecma-international.org/ecma-262/6.0/#sec-scripts-and-modules
438   // for grammar EBNF (production ModuleItem).
439   bool parseModuleReference(const AdditionalKeywords &Keywords,
440                             JsModuleReference &Reference) {
441     if (!Current || !Current->isOneOf(Keywords.kw_import, tok::kw_export))
442       return false;
443     Reference.IsExport = Current->is(tok::kw_export);
444 
445     nextToken();
446     if (Current->isStringLiteral() && !Reference.IsExport) {
447       // "import 'side-effect';"
448       Reference.Category = JsModuleReference::ReferenceCategory::SIDE_EFFECT;
449       Reference.URL =
450           Current->TokenText.substr(1, Current->TokenText.size() - 2);
451       return true;
452     }
453 
454     if (!parseModuleBindings(Keywords, Reference))
455       return false;
456 
457     if (Current->is(Keywords.kw_from)) {
458       // imports have a 'from' clause, exports might not.
459       nextToken();
460       if (!Current->isStringLiteral())
461         return false;
462       // URL = TokenText without the quotes.
463       Reference.URL =
464           Current->TokenText.substr(1, Current->TokenText.size() - 2);
465       if (Reference.URL.startswith(".."))
466         Reference.Category =
467             JsModuleReference::ReferenceCategory::RELATIVE_PARENT;
468       else if (Reference.URL.startswith("."))
469         Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
470       else
471         Reference.Category = JsModuleReference::ReferenceCategory::ABSOLUTE;
472     }
473     return true;
474   }
475 
476   bool parseModuleBindings(const AdditionalKeywords &Keywords,
477                            JsModuleReference &Reference) {
478     if (parseStarBinding(Keywords, Reference))
479       return true;
480     return parseNamedBindings(Keywords, Reference);
481   }
482 
483   bool parseStarBinding(const AdditionalKeywords &Keywords,
484                         JsModuleReference &Reference) {
485     // * as prefix from '...';
486     if (Current->isNot(tok::star))
487       return false;
488     nextToken();
489     if (Current->isNot(Keywords.kw_as))
490       return false;
491     nextToken();
492     if (Current->isNot(tok::identifier))
493       return false;
494     Reference.Prefix = Current->TokenText;
495     nextToken();
496     return true;
497   }
498 
499   bool parseNamedBindings(const AdditionalKeywords &Keywords,
500                           JsModuleReference &Reference) {
501     // eat a potential "import X, " prefix.
502     if (Current->is(tok::identifier)) {
503       Reference.DefaultImport = Current->TokenText;
504       nextToken();
505       if (Current->is(Keywords.kw_from))
506         return true;
507       // import X = A.B.C;
508       if (Current->is(tok::equal)) {
509         Reference.Category = JsModuleReference::ReferenceCategory::ALIAS;
510         nextToken();
511         while (Current->is(tok::identifier)) {
512           nextToken();
513           if (Current->is(tok::semi))
514             return true;
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