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 <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 };
44 
45 // An ES6 module reference.
46 //
47 // ES6 implements a module system, where individual modules (~= source files)
48 // can reference other modules, either importing symbols from them, or exporting
49 // symbols from them:
50 //   import {foo} from 'foo';
51 //   export {foo};
52 //   export {bar} from 'bar';
53 //
54 // `export`s with URLs are syntactic sugar for an import of the symbol from the
55 // URL, followed by an export of the symbol, allowing this code to treat both
56 // statements more or less identically, with the exception being that `export`s
57 // are sorted last.
58 //
59 // imports and exports support individual symbols, but also a wildcard syntax:
60 //   import * as prefix from 'foo';
61 //   export * from 'bar';
62 //
63 // This struct represents both exports and imports to build up the information
64 // required for sorting module references.
65 struct JsModuleReference {
66   bool IsExport = false;
67   // Module references are sorted into these categories, in order.
68   enum ReferenceCategory {
69     SIDE_EFFECT,     // "import 'something';"
70     ABSOLUTE,        // from 'something'
71     RELATIVE_PARENT, // from '../*'
72     RELATIVE,        // from './*'
73   };
74   ReferenceCategory Category = ReferenceCategory::SIDE_EFFECT;
75   // The URL imported, e.g. `import .. from 'url';`. Empty for `export {a, b};`.
76   StringRef URL;
77   // Prefix from "import * as prefix". Empty for symbol imports and `export *`.
78   // Implies an empty names list.
79   StringRef Prefix;
80   // Symbols from `import {SymbolA, SymbolB, ...} from ...;`.
81   SmallVector<JsImportedSymbol, 1> Symbols;
82   // Textual position of the import/export, including preceding and trailing
83   // comments.
84   SourceRange Range;
85 };
86 
87 bool operator<(const JsModuleReference &LHS, const JsModuleReference &RHS) {
88   if (LHS.IsExport != RHS.IsExport)
89     return LHS.IsExport < RHS.IsExport;
90   if (LHS.Category != RHS.Category)
91     return LHS.Category < RHS.Category;
92   if (LHS.Category == JsModuleReference::ReferenceCategory::SIDE_EFFECT)
93     // Side effect imports might be ordering sensitive. Consider them equal so
94     // that they maintain their relative order in the stable sort below.
95     // This retains transitivity because LHS.Category == RHS.Category here.
96     return false;
97   // Empty URLs sort *last* (for export {...};).
98   if (LHS.URL.empty() != RHS.URL.empty())
99     return LHS.URL.empty() < RHS.URL.empty();
100   if (LHS.URL != RHS.URL)
101     return LHS.URL < RHS.URL;
102   // '*' imports (with prefix) sort before {a, b, ...} imports.
103   if (LHS.Prefix.empty() != RHS.Prefix.empty())
104     return LHS.Prefix.empty() < RHS.Prefix.empty();
105   if (LHS.Prefix != RHS.Prefix)
106     return LHS.Prefix > RHS.Prefix;
107   return false;
108 }
109 
110 // JavaScriptImportSorter sorts JavaScript ES6 imports and exports. It is
111 // implemented as a TokenAnalyzer because ES6 imports have substantial syntactic
112 // structure, making it messy to sort them using regular expressions.
113 class JavaScriptImportSorter : public TokenAnalyzer {
114 public:
115   JavaScriptImportSorter(const Environment &Env, const FormatStyle &Style)
116       : TokenAnalyzer(Env, Style),
117         FileContents(Env.getSourceManager().getBufferData(Env.getFileID())) {}
118 
119   tooling::Replacements
120   analyze(TokenAnnotator &Annotator,
121           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
122           FormatTokenLexer &Tokens, tooling::Replacements &Result) override {
123     AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
124                                           AnnotatedLines.end());
125 
126     const AdditionalKeywords &Keywords = Tokens.getKeywords();
127     SmallVector<JsModuleReference, 16> References;
128     AnnotatedLine *FirstNonImportLine;
129     std::tie(References, FirstNonImportLine) =
130         parseModuleReferences(Keywords, AnnotatedLines);
131 
132     if (References.empty())
133       return Result;
134 
135     SmallVector<unsigned, 16> Indices;
136     for (unsigned i = 0, e = References.size(); i != e; ++i)
137       Indices.push_back(i);
138     std::stable_sort(Indices.begin(), Indices.end(),
139                      [&](unsigned LHSI, unsigned RHSI) {
140                        return References[LHSI] < References[RHSI];
141                      });
142     // FIXME: Pull this into a common function.
143     bool OutOfOrder = false;
144     for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
145       if (i != Indices[i]) {
146         OutOfOrder = true;
147         break;
148       }
149     }
150     if (!OutOfOrder)
151       return Result;
152 
153     // Replace all existing import/export statements.
154     std::string ReferencesText;
155     for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
156       JsModuleReference Reference = References[Indices[i]];
157       StringRef ReferenceStmt = getSourceText(Reference.Range);
158       ReferencesText += ReferenceStmt;
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     // Separate references from the main code body of the file.
171     if (FirstNonImportLine && FirstNonImportLine->First->NewlinesBefore < 2)
172       ReferencesText += "\n";
173 
174     SourceRange InsertionPoint = References[0].Range;
175     InsertionPoint.setEnd(References[References.size() - 1].Range.getEnd());
176     DEBUG(llvm::dbgs() << "Replacing imports:\n"
177                        << getSourceText(InsertionPoint) << "\nwith:\n"
178                        << ReferencesText << "\n");
179     Result.insert(tooling::Replacement(
180         Env.getSourceManager(), CharSourceRange::getCharRange(InsertionPoint),
181         ReferencesText));
182 
183     return Result;
184   }
185 
186 private:
187   FormatToken *Current;
188   FormatToken *LineEnd;
189 
190   FormatToken invalidToken;
191 
192   StringRef FileContents;
193 
194   void skipComments() { Current = skipComments(Current); }
195 
196   FormatToken *skipComments(FormatToken *Tok) {
197     while (Tok && Tok->is(tok::comment))
198       Tok = Tok->Next;
199     return Tok;
200   }
201 
202   void nextToken() {
203     Current = Current->Next;
204     skipComments();
205     if (!Current || Current == LineEnd->Next) {
206       // Set the current token to an invalid token, so that further parsing on
207       // this line fails.
208       invalidToken.Tok.setKind(tok::unknown);
209       Current = &invalidToken;
210     }
211   }
212 
213   StringRef getSourceText(SourceRange Range) {
214     const SourceManager &SM = Env.getSourceManager();
215     return FileContents.substr(SM.getFileOffset(Range.getBegin()),
216                                SM.getFileOffset(Range.getEnd()) -
217                                    SM.getFileOffset(Range.getBegin()));
218   }
219 
220   // Parses module references in the given lines. Returns the module references,
221   // and a pointer to the first "main code" line if that is adjacent to the
222   // affected lines of module references, nullptr otherwise.
223   std::pair<SmallVector<JsModuleReference, 16>, AnnotatedLine*>
224   parseModuleReferences(const AdditionalKeywords &Keywords,
225                         SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
226     SmallVector<JsModuleReference, 16> References;
227     SourceLocation Start;
228     bool FoundLines = false;
229     AnnotatedLine *FirstNonImportLine = nullptr;
230     for (auto Line : AnnotatedLines) {
231       if (!Line->Affected) {
232         // Only sort the first contiguous block of affected lines.
233         if (FoundLines)
234           break;
235         else
236           continue;
237       }
238       Current = Line->First;
239       LineEnd = Line->Last;
240       skipComments();
241       if (Start.isInvalid() || References.empty())
242         // After the first file level comment, consider line comments to be part
243         // of the import that immediately follows them by using the previously
244         // set Start.
245         Start = Line->First->Tok.getLocation();
246       if (!Current)
247         continue; // Only comments on this line.
248       FoundLines = true;
249       JsModuleReference Reference;
250       Reference.Range.setBegin(Start);
251       if (!parseModuleReference(Keywords, Reference)) {
252         FirstNonImportLine = Line;
253         break;
254       }
255       Reference.Range.setEnd(LineEnd->Tok.getEndLoc());
256       DEBUG({
257         llvm::dbgs() << "JsModuleReference: {"
258                      << "is_export: " << Reference.IsExport
259                      << ", cat: " << Reference.Category
260                      << ", url: " << Reference.URL
261                      << ", prefix: " << Reference.Prefix;
262         for (size_t i = 0; i < Reference.Symbols.size(); ++i)
263           llvm::dbgs() << ", " << Reference.Symbols[i].Symbol << " as "
264                        << Reference.Symbols[i].Alias;
265         llvm::dbgs() << ", text: " << getSourceText(Reference.Range);
266         llvm::dbgs() << "}\n";
267       });
268       References.push_back(Reference);
269       Start = SourceLocation();
270     }
271     return std::make_pair(References, FirstNonImportLine);
272   }
273 
274   // Parses a JavaScript/ECMAScript 6 module reference.
275   // See http://www.ecma-international.org/ecma-262/6.0/#sec-scripts-and-modules
276   // for grammar EBNF (production ModuleItem).
277   bool parseModuleReference(const AdditionalKeywords &Keywords,
278                             JsModuleReference &Reference) {
279     if (!Current || !Current->isOneOf(Keywords.kw_import, tok::kw_export))
280       return false;
281     Reference.IsExport = Current->is(tok::kw_export);
282 
283     nextToken();
284     if (Current->isStringLiteral() && !Reference.IsExport) {
285       // "import 'side-effect';"
286       Reference.Category = JsModuleReference::ReferenceCategory::SIDE_EFFECT;
287       Reference.URL =
288           Current->TokenText.substr(1, Current->TokenText.size() - 2);
289       return true;
290     }
291 
292     if (!parseModuleBindings(Keywords, Reference))
293       return false;
294     nextToken();
295 
296     if (Current->is(Keywords.kw_from)) {
297       // imports have a 'from' clause, exports might not.
298       nextToken();
299       if (!Current->isStringLiteral())
300         return false;
301       // URL = TokenText without the quotes.
302       Reference.URL =
303           Current->TokenText.substr(1, Current->TokenText.size() - 2);
304       if (Reference.URL.startswith(".."))
305         Reference.Category =
306             JsModuleReference::ReferenceCategory::RELATIVE_PARENT;
307       else if (Reference.URL.startswith("."))
308         Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
309       else
310         Reference.Category = JsModuleReference::ReferenceCategory::ABSOLUTE;
311     } else {
312       // w/o URL groups with "empty".
313       Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
314     }
315     return true;
316   }
317 
318   bool parseModuleBindings(const AdditionalKeywords &Keywords,
319                            JsModuleReference &Reference) {
320     if (parseStarBinding(Keywords, Reference))
321       return true;
322     return parseNamedBindings(Keywords, Reference);
323   }
324 
325   bool parseStarBinding(const AdditionalKeywords &Keywords,
326                         JsModuleReference &Reference) {
327     // * as prefix from '...';
328     if (Current->isNot(tok::star))
329       return false;
330     nextToken();
331     if (Current->isNot(Keywords.kw_as))
332       return false;
333     nextToken();
334     if (Current->isNot(tok::identifier))
335       return false;
336     Reference.Prefix = Current->TokenText;
337     return true;
338   }
339 
340   bool parseNamedBindings(const AdditionalKeywords &Keywords,
341                           JsModuleReference &Reference) {
342     if (Current->isNot(tok::l_brace))
343       return false;
344 
345     // {sym as alias, sym2 as ...} from '...';
346     nextToken();
347     while (true) {
348       if (Current->isNot(tok::identifier))
349         return false;
350 
351       JsImportedSymbol Symbol;
352       Symbol.Symbol = Current->TokenText;
353       nextToken();
354 
355       if (Current->is(Keywords.kw_as)) {
356         nextToken();
357         if (Current->isNot(tok::identifier))
358           return false;
359         Symbol.Alias = Current->TokenText;
360         nextToken();
361       }
362       Reference.Symbols.push_back(Symbol);
363 
364       if (Current->is(tok::r_brace))
365         return true;
366       if (Current->isNot(tok::comma))
367         return false;
368       nextToken();
369     }
370   }
371 };
372 
373 tooling::Replacements sortJavaScriptImports(const FormatStyle &Style,
374                                             StringRef Code,
375                                             ArrayRef<tooling::Range> Ranges,
376                                             StringRef FileName) {
377   // FIXME: Cursor support.
378   std::unique_ptr<Environment> Env =
379       Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
380   JavaScriptImportSorter Sorter(*Env, Style);
381   return Sorter.process();
382 }
383 
384 } // end namespace format
385 } // end namespace clang
386