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