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