1 //===--- SortJavaScriptImports.h - Sort ES6 Imports -------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements a sort operation for JavaScript ES6 imports.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "SortJavaScriptImports.h"
16 #include "SortJavaScriptImports.h"
17 #include "TokenAnalyzer.h"
18 #include "TokenAnnotator.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/DiagnosticOptions.h"
21 #include "clang/Basic/LLVM.h"
22 #include "clang/Basic/SourceLocation.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Format/Format.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Support/Debug.h"
28 #include <algorithm>
29 #include <string>
30 
31 #define DEBUG_TYPE "format-formatter"
32 
33 namespace clang {
34 namespace format {
35 
36 class FormatTokenLexer;
37 
38 using clang::format::FormatStyle;
39 
40 // An imported symbol in a JavaScript ES6 import/export, possibly aliased.
41 struct JsImportedSymbol {
42   StringRef Symbol;
43   StringRef Alias;
44   SourceRange Range;
45 
46   bool operator==(const JsImportedSymbol &RHS) const {
47     // Ignore Range for comparison, it is only used to stitch code together,
48     // but imports at different code locations are still conceptually the same.
49     return Symbol == RHS.Symbol && Alias == RHS.Alias;
50   }
51 };
52 
53 // An ES6 module reference.
54 //
55 // ES6 implements a module system, where individual modules (~= source files)
56 // can reference other modules, either importing symbols from them, or exporting
57 // symbols from them:
58 //   import {foo} from 'foo';
59 //   export {foo};
60 //   export {bar} from 'bar';
61 //
62 // `export`s with URLs are syntactic sugar for an import of the symbol from the
63 // URL, followed by an export of the symbol, allowing this code to treat both
64 // statements more or less identically, with the exception being that `export`s
65 // are sorted last.
66 //
67 // imports and exports support individual symbols, but also a wildcard syntax:
68 //   import * as prefix from 'foo';
69 //   export * from 'bar';
70 //
71 // This struct represents both exports and imports to build up the information
72 // required for sorting module references.
73 struct JsModuleReference {
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   // Symbols from `import {SymbolA, SymbolB, ...} from ...;`.
89   SmallVector<JsImportedSymbol, 1> Symbols;
90   // Textual position of the import/export, including preceding and trailing
91   // comments.
92   SourceRange Range;
93 };
94 
95 bool operator<(const JsModuleReference &LHS, const JsModuleReference &RHS) {
96   if (LHS.IsExport != RHS.IsExport)
97     return LHS.IsExport < RHS.IsExport;
98   if (LHS.Category != RHS.Category)
99     return LHS.Category < RHS.Category;
100   if (LHS.Category == JsModuleReference::ReferenceCategory::SIDE_EFFECT)
101     // Side effect imports might be ordering sensitive. Consider them equal so
102     // that they maintain their relative order in the stable sort below.
103     // This retains transitivity because LHS.Category == RHS.Category here.
104     return false;
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_lower(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 
127   tooling::Replacements
128   analyze(TokenAnnotator &Annotator,
129           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
130           FormatTokenLexer &Tokens) override {
131     tooling::Replacements Result;
132     AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
133                                           AnnotatedLines.end());
134 
135     const AdditionalKeywords &Keywords = Tokens.getKeywords();
136     SmallVector<JsModuleReference, 16> References;
137     AnnotatedLine *FirstNonImportLine;
138     std::tie(References, FirstNonImportLine) =
139         parseModuleReferences(Keywords, AnnotatedLines);
140 
141     if (References.empty())
142       return Result;
143 
144     SmallVector<unsigned, 16> Indices;
145     for (unsigned i = 0, e = References.size(); i != e; ++i)
146       Indices.push_back(i);
147     std::stable_sort(Indices.begin(), Indices.end(),
148                      [&](unsigned LHSI, unsigned RHSI) {
149                        return References[LHSI] < References[RHSI];
150                      });
151     bool ReferencesInOrder = std::is_sorted(Indices.begin(), Indices.end());
152 
153     std::string ReferencesText;
154     bool SymbolsInOrder = true;
155     for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
156       JsModuleReference Reference = References[Indices[i]];
157       if (appendReference(ReferencesText, Reference))
158         SymbolsInOrder = false;
159       if (i + 1 < e) {
160         // Insert breaks between imports and exports.
161         ReferencesText += "\n";
162         // Separate imports groups with two line breaks, but keep all exports
163         // in a single group.
164         if (!Reference.IsExport &&
165             (Reference.IsExport != References[Indices[i + 1]].IsExport ||
166              Reference.Category != References[Indices[i + 1]].Category))
167           ReferencesText += "\n";
168       }
169     }
170 
171     if (ReferencesInOrder && SymbolsInOrder)
172       return Result;
173 
174     SourceRange InsertionPoint = References[0].Range;
175     InsertionPoint.setEnd(References[References.size() - 1].Range.getEnd());
176 
177     // The loop above might collapse previously existing line breaks between
178     // import blocks, and thus shrink the file. SortIncludes must not shrink
179     // overall source length as there is currently no re-calculation of ranges
180     // after applying source sorting.
181     // This loop just backfills trailing spaces after the imports, which are
182     // harmless and will be stripped by the subsequent formatting pass.
183     // FIXME: A better long term fix is to re-calculate Ranges after sorting.
184     unsigned PreviousSize = getSourceText(InsertionPoint).size();
185     while (ReferencesText.size() < PreviousSize) {
186       ReferencesText += " ";
187     }
188 
189     // Separate references from the main code body of the file.
190     if (FirstNonImportLine && FirstNonImportLine->First->NewlinesBefore < 2)
191       ReferencesText += "\n";
192 
193     DEBUG(llvm::dbgs() << "Replacing imports:\n"
194                        << getSourceText(InsertionPoint) << "\nwith:\n"
195                        << ReferencesText << "\n");
196     auto Err = Result.add(tooling::Replacement(
197         Env.getSourceManager(), CharSourceRange::getCharRange(InsertionPoint),
198         ReferencesText));
199     // FIXME: better error handling. For now, just print error message and skip
200     // the replacement for the release version.
201     if (Err)
202       llvm::errs() << llvm::toString(std::move(Err)) << "\n";
203     assert(!Err);
204 
205     return Result;
206   }
207 
208 private:
209   FormatToken *Current;
210   FormatToken *LineEnd;
211 
212   FormatToken invalidToken;
213 
214   StringRef FileContents;
215 
216   void skipComments() { Current = skipComments(Current); }
217 
218   FormatToken *skipComments(FormatToken *Tok) {
219     while (Tok && Tok->is(tok::comment))
220       Tok = Tok->Next;
221     return Tok;
222   }
223 
224   void nextToken() {
225     Current = Current->Next;
226     skipComments();
227     if (!Current || Current == LineEnd->Next) {
228       // Set the current token to an invalid token, so that further parsing on
229       // this line fails.
230       invalidToken.Tok.setKind(tok::unknown);
231       Current = &invalidToken;
232     }
233   }
234 
235   StringRef getSourceText(SourceRange Range) {
236     return getSourceText(Range.getBegin(), Range.getEnd());
237   }
238 
239   StringRef getSourceText(SourceLocation Begin, SourceLocation End) {
240     const SourceManager &SM = Env.getSourceManager();
241     return FileContents.substr(SM.getFileOffset(Begin),
242                                SM.getFileOffset(End) - SM.getFileOffset(Begin));
243   }
244 
245   // Appends ``Reference`` to ``Buffer``, returning true if text within the
246   // ``Reference`` changed (e.g. symbol order).
247   bool appendReference(std::string &Buffer, JsModuleReference &Reference) {
248     // Sort the individual symbols within the import.
249     // E.g. `import {b, a} from 'x';` -> `import {a, b} from 'x';`
250     SmallVector<JsImportedSymbol, 1> Symbols = Reference.Symbols;
251     std::stable_sort(
252         Symbols.begin(), Symbols.end(),
253         [&](const JsImportedSymbol &LHS, const JsImportedSymbol &RHS) {
254           return LHS.Symbol.compare_lower(RHS.Symbol) < 0;
255         });
256     if (Symbols == Reference.Symbols) {
257       // No change in symbol order.
258       StringRef ReferenceStmt = getSourceText(Reference.Range);
259       Buffer += ReferenceStmt;
260       return false;
261     }
262     // Stitch together the module reference start...
263     SourceLocation SymbolsStart = Reference.Symbols.front().Range.getBegin();
264     SourceLocation SymbolsEnd = Reference.Symbols.back().Range.getEnd();
265     Buffer += getSourceText(Reference.Range.getBegin(), SymbolsStart);
266     // ... then the references in order ...
267     for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) {
268       if (I != Symbols.begin())
269         Buffer += ",";
270       Buffer += getSourceText(I->Range);
271     }
272     // ... followed by the module reference end.
273     Buffer += getSourceText(SymbolsEnd, Reference.Range.getEnd());
274     return true;
275   }
276 
277   // Parses module references in the given lines. Returns the module references,
278   // and a pointer to the first "main code" line if that is adjacent to the
279   // affected lines of module references, nullptr otherwise.
280   std::pair<SmallVector<JsModuleReference, 16>, AnnotatedLine*>
281   parseModuleReferences(const AdditionalKeywords &Keywords,
282                         SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
283     SmallVector<JsModuleReference, 16> References;
284     SourceLocation Start;
285     AnnotatedLine *FirstNonImportLine = nullptr;
286     bool AnyImportAffected = false;
287     for (auto Line : AnnotatedLines) {
288       Current = Line->First;
289       LineEnd = Line->Last;
290       skipComments();
291       if (Start.isInvalid() || References.empty())
292         // After the first file level comment, consider line comments to be part
293         // of the import that immediately follows them by using the previously
294         // set Start.
295         Start = Line->First->Tok.getLocation();
296       if (!Current)
297         continue; // Only comments on this line.
298       JsModuleReference Reference;
299       Reference.Range.setBegin(Start);
300       if (!parseModuleReference(Keywords, Reference)) {
301         FirstNonImportLine = Line;
302         break;
303       }
304       AnyImportAffected = AnyImportAffected || Line->Affected;
305       Reference.Range.setEnd(LineEnd->Tok.getEndLoc());
306       DEBUG({
307         llvm::dbgs() << "JsModuleReference: {"
308                      << "is_export: " << Reference.IsExport
309                      << ", cat: " << Reference.Category
310                      << ", url: " << Reference.URL
311                      << ", prefix: " << Reference.Prefix;
312         for (size_t i = 0; i < Reference.Symbols.size(); ++i)
313           llvm::dbgs() << ", " << Reference.Symbols[i].Symbol << " as "
314                        << Reference.Symbols[i].Alias;
315         llvm::dbgs() << ", text: " << getSourceText(Reference.Range);
316         llvm::dbgs() << "}\n";
317       });
318       References.push_back(Reference);
319       Start = SourceLocation();
320     }
321     // Sort imports if any import line was affected.
322     if (!AnyImportAffected)
323       References.clear();
324     return std::make_pair(References, FirstNonImportLine);
325   }
326 
327   // Parses a JavaScript/ECMAScript 6 module reference.
328   // See http://www.ecma-international.org/ecma-262/6.0/#sec-scripts-and-modules
329   // for grammar EBNF (production ModuleItem).
330   bool parseModuleReference(const AdditionalKeywords &Keywords,
331                             JsModuleReference &Reference) {
332     if (!Current || !Current->isOneOf(Keywords.kw_import, tok::kw_export))
333       return false;
334     Reference.IsExport = Current->is(tok::kw_export);
335 
336     nextToken();
337     if (Current->isStringLiteral() && !Reference.IsExport) {
338       // "import 'side-effect';"
339       Reference.Category = JsModuleReference::ReferenceCategory::SIDE_EFFECT;
340       Reference.URL =
341           Current->TokenText.substr(1, Current->TokenText.size() - 2);
342       return true;
343     }
344 
345     if (!parseModuleBindings(Keywords, Reference))
346       return false;
347 
348     if (Current->is(Keywords.kw_from)) {
349       // imports have a 'from' clause, exports might not.
350       nextToken();
351       if (!Current->isStringLiteral())
352         return false;
353       // URL = TokenText without the quotes.
354       Reference.URL =
355           Current->TokenText.substr(1, Current->TokenText.size() - 2);
356       if (Reference.URL.startswith(".."))
357         Reference.Category =
358             JsModuleReference::ReferenceCategory::RELATIVE_PARENT;
359       else if (Reference.URL.startswith("."))
360         Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
361       else
362         Reference.Category = JsModuleReference::ReferenceCategory::ABSOLUTE;
363     } else {
364       // w/o URL groups with "empty".
365       Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
366     }
367     return true;
368   }
369 
370   bool parseModuleBindings(const AdditionalKeywords &Keywords,
371                            JsModuleReference &Reference) {
372     if (parseStarBinding(Keywords, Reference))
373       return true;
374     return parseNamedBindings(Keywords, Reference);
375   }
376 
377   bool parseStarBinding(const AdditionalKeywords &Keywords,
378                         JsModuleReference &Reference) {
379     // * as prefix from '...';
380     if (Current->isNot(tok::star))
381       return false;
382     nextToken();
383     if (Current->isNot(Keywords.kw_as))
384       return false;
385     nextToken();
386     if (Current->isNot(tok::identifier))
387       return false;
388     Reference.Prefix = Current->TokenText;
389     nextToken();
390     return true;
391   }
392 
393   bool parseNamedBindings(const AdditionalKeywords &Keywords,
394                           JsModuleReference &Reference) {
395     if (Current->is(tok::identifier)) {
396       nextToken();
397       if (Current->is(Keywords.kw_from))
398         return true;
399       if (Current->isNot(tok::comma))
400         return false;
401       nextToken(); // eat comma.
402     }
403     if (Current->isNot(tok::l_brace))
404       return false;
405 
406     // {sym as alias, sym2 as ...} from '...';
407     while (Current->isNot(tok::r_brace)) {
408       nextToken();
409       if (Current->is(tok::r_brace))
410         break;
411       if (Current->isNot(tok::identifier))
412         return false;
413 
414       JsImportedSymbol Symbol;
415       Symbol.Symbol = Current->TokenText;
416       // Make sure to include any preceding comments.
417       Symbol.Range.setBegin(
418           Current->getPreviousNonComment()->Next->WhitespaceRange.getBegin());
419       nextToken();
420 
421       if (Current->is(Keywords.kw_as)) {
422         nextToken();
423         if (Current->isNot(tok::identifier))
424           return false;
425         Symbol.Alias = Current->TokenText;
426         nextToken();
427       }
428       Symbol.Range.setEnd(Current->Tok.getLocation());
429       Reference.Symbols.push_back(Symbol);
430 
431       if (!Current->isOneOf(tok::r_brace, tok::comma))
432         return false;
433     }
434     nextToken(); // consume r_brace
435     return true;
436   }
437 };
438 
439 tooling::Replacements sortJavaScriptImports(const FormatStyle &Style,
440                                             StringRef Code,
441                                             ArrayRef<tooling::Range> Ranges,
442                                             StringRef FileName) {
443   // FIXME: Cursor support.
444   std::unique_ptr<Environment> Env =
445       Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
446   JavaScriptImportSorter Sorter(*Env, Style);
447   return Sorter.process();
448 }
449 
450 } // end namespace format
451 } // end namespace clang
452