Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Format/SortJavaScriptImports.cpp
Line
Count
Source (jump to first uncovered line)
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
70
  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
70
    return Symbol == RHS.Symbol && 
Alias == RHS.Alias65
;
49
70
  }
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
103
61
bool operator<(const JsModuleReference &LHS, const JsModuleReference &RHS) {
104
61
  if (LHS.IsExport != RHS.IsExport)
105
5
    return LHS.IsExport < RHS.IsExport;
106
56
  if (LHS.Category != RHS.Category)
107
14
    return LHS.Category < RHS.Category;
108
42
  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
1
    return false;
113
  // Empty URLs sort *last* (for export {...};).
114
41
  if (LHS.URL.empty() != RHS.URL.empty())
115
1
    return LHS.URL.empty() < RHS.URL.empty();
116
40
  if (int Res = LHS.URL.compare_insensitive(RHS.URL))
117
32
    return Res < 0;
118
  // '*' imports (with prefix) sort before {a, b, ...} imports.
119
8
  if (LHS.Prefix.empty() != RHS.Prefix.empty())
120
2
    return LHS.Prefix.empty() < RHS.Prefix.empty();
121
6
  if (LHS.Prefix != RHS.Prefix)
122
0
    return LHS.Prefix > RHS.Prefix;
123
6
  return false;
124
6
}
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:
131
  JavaScriptImportSorter(const Environment &Env, const FormatStyle &Style)
132
      : TokenAnalyzer(Env, Style),
133
43
        FileContents(Env.getSourceManager().getBufferData(Env.getFileID())) {}
134
135
  std::pair<tooling::Replacements, unsigned>
136
  analyze(TokenAnnotator &Annotator,
137
          SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
138
43
          FormatTokenLexer &Tokens) override {
139
43
    tooling::Replacements Result;
140
43
    AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
141
142
43
    const AdditionalKeywords &Keywords = Tokens.getKeywords();
143
43
    SmallVector<JsModuleReference, 16> References;
144
43
    AnnotatedLine *FirstNonImportLine;
145
43
    std::tie(References, FirstNonImportLine) =
146
43
        parseModuleReferences(Keywords, AnnotatedLines);
147
148
43
    if (References.empty())
149
5
      return {Result, 0};
150
151
    // The text range of all parsed imports, to be replaced later.
152
38
    SourceRange InsertionPoint = References[0].Range;
153
38
    InsertionPoint.setEnd(References[References.size() - 1].Range.getEnd());
154
155
38
    References = sortModuleReferences(References);
156
157
38
    std::string ReferencesText;
158
124
    for (unsigned I = 0, E = References.size(); I != E; 
++I86
) {
159
86
      JsModuleReference Reference = References[I];
160
86
      appendReference(ReferencesText, Reference);
161
86
      if (I + 1 < E) {
162
        // Insert breaks between imports and exports.
163
48
        ReferencesText += "\n";
164
        // Separate imports groups with two line breaks, but keep all exports
165
        // in a single group.
166
48
        if (!Reference.IsExport &&
167
48
            
(45
Reference.IsExport != References[I + 1].IsExport45
||
168
45
             
Reference.Category != References[I + 1].Category42
))
169
9
          ReferencesText += "\n";
170
48
      }
171
86
    }
172
38
    llvm::StringRef PreviousText = getSourceText(InsertionPoint);
173
38
    if (ReferencesText == PreviousText)
174
6
      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
32
    unsigned PreviousSize = PreviousText.size();
184
147
    while (ReferencesText.size() < PreviousSize) {
185
115
      ReferencesText += " ";
186
115
    }
187
188
    // Separate references from the main code body of the file.
189
32
    if (FirstNonImportLine && FirstNonImportLine->First->NewlinesBefore < 2 &&
190
32
        
!(25
FirstNonImportLine->First->is(tok::comment)25
&&
191
25
          
FirstNonImportLine->First->TokenText.trim() == "// clang-format on"1
))
192
25
      ReferencesText += "\n";
193
194
32
    LLVM_DEBUG(llvm::dbgs() << "Replacing imports:\n"
195
32
                            << PreviousText << "\nwith:\n"
196
32
                            << ReferencesText << "\n");
197
32
    auto Err = Result.add(tooling::Replacement(
198
32
        Env.getSourceManager(), CharSourceRange::getCharRange(InsertionPoint),
199
32
        ReferencesText));
200
    // FIXME: better error handling. For now, just print error message and skip
201
    // the replacement for the release version.
202
32
    if (Err) {
203
0
      llvm::errs() << llvm::toString(std::move(Err)) << "\n";
204
0
      assert(false);
205
0
    }
206
207
0
    return {Result, 0};
208
38
  }
209
210
private:
211
  FormatToken *Current;
212
  FormatToken *LineEnd;
213
214
  FormatToken invalidToken;
215
216
  StringRef FileContents;
217
218
646
  void skipComments() { Current = skipComments(Current); }
219
220
646
  FormatToken *skipComments(FormatToken *Tok) {
221
650
    while (Tok && 
Tok->is(tok::comment)632
)
222
4
      Tok = Tok->Next;
223
646
    return Tok;
224
646
  }
225
226
491
  void nextToken() {
227
491
    Current = Current->Next;
228
491
    skipComments();
229
491
    if (!Current || Current == LineEnd->Next) {
230
      // Set the current token to an invalid token, so that further parsing on
231
      // this line fails.
232
0
      invalidToken.Tok.setKind(tok::unknown);
233
0
      Current = &invalidToken;
234
0
    }
235
491
  }
236
237
131
  StringRef getSourceText(SourceRange Range) {
238
131
    return getSourceText(Range.getBegin(), Range.getEnd());
239
131
  }
240
241
156
  StringRef getSourceText(SourceLocation Begin, SourceLocation End) {
242
156
    const SourceManager &SM = Env.getSourceManager();
243
156
    return FileContents.substr(SM.getFileOffset(Begin),
244
156
                               SM.getFileOffset(End) - SM.getFileOffset(Begin));
245
156
  }
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>
252
38
  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
38
    const auto *Start = References.begin();
258
38
    SmallVector<JsModuleReference, 16> ReferencesSorted;
259
77
    while (Start != References.end()) {
260
44
      while (Start != References.end() && 
Start->FormattingOff42
) {
261
        // Skip over all imports w/ disabled formatting.
262
5
        ReferencesSorted.push_back(*Start);
263
5
        Start++;
264
5
      }
265
39
      SmallVector<JsModuleReference, 16> SortChunk;
266
125
      while (Start != References.end() && 
!Start->FormattingOff87
) {
267
        // Skip over all imports w/ disabled formatting.
268
86
        SortChunk.push_back(*Start);
269
86
        Start++;
270
86
      }
271
39
      llvm::stable_sort(SortChunk);
272
39
      mergeModuleReferences(SortChunk);
273
39
      ReferencesSorted.insert(ReferencesSorted.end(), SortChunk.begin(),
274
39
                              SortChunk.end());
275
39
    }
276
38
    return ReferencesSorted;
277
38
  }
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).
288
39
  void mergeModuleReferences(SmallVector<JsModuleReference, 16> &References) {
289
39
    if (References.empty())
290
2
      return;
291
37
    JsModuleReference *PreviousReference = References.begin();
292
37
    auto *Reference = std::next(References.begin());
293
86
    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
49
      if (Reference->Category == JsModuleReference::SIDE_EFFECT ||
300
49
          
PreviousReference->Category == JsModuleReference::SIDE_EFFECT48
||
301
49
          
Reference->IsExport != PreviousReference->IsExport46
||
302
49
          
!PreviousReference->Prefix.empty()43
||
!Reference->Prefix.empty()41
||
303
49
          
!PreviousReference->DefaultImport.empty()40
||
304
49
          
!Reference->DefaultImport.empty()37
||
Reference->Symbols.empty()37
||
305
49
          
PreviousReference->URL != Reference->URL37
) {
306
44
        PreviousReference = Reference;
307
44
        ++Reference;
308
44
        continue;
309
44
      }
310
      // Merge symbols from identical imports.
311
5
      PreviousReference->Symbols.append(Reference->Symbols);
312
5
      PreviousReference->SymbolsMerged = true;
313
      // Remove the merged import.
314
5
      Reference = References.erase(Reference);
315
5
    }
316
37
  }
317
318
  // Appends ``Reference`` to ``Buffer``.
319
86
  void appendReference(std::string &Buffer, JsModuleReference &Reference) {
320
86
    if (Reference.FormattingOff) {
321
5
      Buffer +=
322
5
          getSourceText(Reference.Range.getBegin(), Reference.Range.getEnd());
323
5
      return;
324
5
    }
325
    // Sort the individual symbols within the import.
326
    // E.g. `import {b, a} from 'x';` -> `import {a, b} from 'x';`
327
81
    SmallVector<JsImportedSymbol, 1> Symbols = Reference.Symbols;
328
81
    llvm::stable_sort(
329
81
        Symbols, [&](const JsImportedSymbol &LHS, const JsImportedSymbol &RHS) {
330
18
          return LHS.Symbol.compare_insensitive(RHS.Symbol) < 0;
331
18
        });
332
81
    if (!Reference.SymbolsMerged && 
Symbols == Reference.Symbols76
) {
333
      // Symbols didn't change, just emit the entire module reference.
334
71
      StringRef ReferenceStmt = getSourceText(Reference.Range);
335
71
      Buffer += ReferenceStmt;
336
71
      return;
337
71
    }
338
    // Stitch together the module reference start...
339
10
    Buffer += getSourceText(Reference.Range.getBegin(), Reference.SymbolsStart);
340
    // ... then the references in order ...
341
32
    for (auto I = Symbols.begin(), E = Symbols.end(); I != E; 
++I22
) {
342
22
      if (I != Symbols.begin())
343
12
        Buffer += ",";
344
22
      Buffer += getSourceText(I->Range);
345
22
    }
346
    // ... followed by the module reference end.
347
10
    Buffer += getSourceText(Reference.SymbolsEnd, Reference.Range.getEnd());
348
10
  }
349
350
  // Parses module references in the given lines. Returns the module references,
351
  // and a pointer to the first "main code" line if that is adjacent to the
352
  // affected lines of module references, nullptr otherwise.
353
  std::pair<SmallVector<JsModuleReference, 16>, AnnotatedLine *>
354
  parseModuleReferences(const AdditionalKeywords &Keywords,
355
43
                        SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
356
43
    SmallVector<JsModuleReference, 16> References;
357
43
    SourceLocation Start;
358
43
    AnnotatedLine *FirstNonImportLine = nullptr;
359
43
    bool AnyImportAffected = false;
360
43
    bool FormattingOff = false;
361
155
    for (auto *Line : AnnotatedLines) {
362
155
      Current = Line->First;
363
155
      LineEnd = Line->Last;
364
      // clang-format comments toggle formatting on/off.
365
      // This is tracked in FormattingOff here and on JsModuleReference.
366
175
      while (Current && 
Current->is(tok::comment)157
) {
367
20
        StringRef CommentText = Current->TokenText.trim();
368
20
        if (CommentText == "// clang-format off") {
369
7
          FormattingOff = true;
370
13
        } else if (CommentText == "// clang-format on") {
371
7
          FormattingOff = false;
372
          // Special case: consider a trailing "clang-format on" line to be part
373
          // of the module reference, so that it gets moved around together with
374
          // it (as opposed to the next module reference, which might get sorted
375
          // around).
376
7
          if (!References.empty()) {
377
3
            References.back().Range.setEnd(Current->Tok.getEndLoc());
378
3
            Start = Current->Tok.getEndLoc().getLocWithOffset(1);
379
3
          }
380
7
        }
381
        // Handle all clang-format comments on a line, e.g. for an empty block.
382
20
        Current = Current->Next;
383
20
      }
384
155
      skipComments();
385
155
      if (Start.isInvalid() || 
References.empty()21
)
386
        // After the first file level comment, consider line comments to be part
387
        // of the import that immediately follows them by using the previously
388
        // set Start.
389
143
        Start = Line->First->Tok.getLocation();
390
155
      if (!Current) {
391
        // Only comments on this line. Could be the first non-import line.
392
18
        FirstNonImportLine = Line;
393
18
        continue;
394
18
      }
395
137
      JsModuleReference Reference;
396
137
      Reference.FormattingOff = FormattingOff;
397
137
      Reference.Range.setBegin(Start);
398
137
      if (!parseModuleReference(Keywords, Reference)) {
399
43
        if (!FirstNonImportLine)
400
36
          FirstNonImportLine = Line; // if no comment before.
401
43
        break;
402
43
      }
403
94
      FirstNonImportLine = nullptr;
404
94
      AnyImportAffected = AnyImportAffected || 
Line->Affected41
;
405
94
      Reference.Range.setEnd(LineEnd->Tok.getEndLoc());
406
94
      LLVM_DEBUG({
407
94
        llvm::dbgs() << "JsModuleReference: {"
408
94
                     << "formatting_off: " << Reference.FormattingOff
409
94
                     << ", is_export: " << Reference.IsExport
410
94
                     << ", cat: " << Reference.Category
411
94
                     << ", url: " << Reference.URL
412
94
                     << ", prefix: " << Reference.Prefix;
413
94
        for (size_t I = 0; I < Reference.Symbols.size(); ++I)
414
94
          llvm::dbgs() << ", " << Reference.Symbols[I].Symbol << " as "
415
94
                       << Reference.Symbols[I].Alias;
416
94
        llvm::dbgs() << ", text: " << getSourceText(Reference.Range);
417
94
        llvm::dbgs() << "}\n";
418
94
      });
419
94
      References.push_back(Reference);
420
94
      Start = SourceLocation();
421
94
    }
422
    // Sort imports if any import line was affected.
423
43
    if (!AnyImportAffected)
424
5
      References.clear();
425
43
    return std::make_pair(References, FirstNonImportLine);
426
43
  }
427
428
  // Parses a JavaScript/ECMAScript 6 module reference.
429
  // See http://www.ecma-international.org/ecma-262/6.0/#sec-scripts-and-modules
430
  // for grammar EBNF (production ModuleItem).
431
  bool parseModuleReference(const AdditionalKeywords &Keywords,
432
137
                            JsModuleReference &Reference) {
433
137
    if (!Current || !Current->isOneOf(Keywords.kw_import, tok::kw_export))
434
43
      return false;
435
94
    Reference.IsExport = Current->is(tok::kw_export);
436
437
94
    nextToken();
438
94
    if (Current->isStringLiteral() && 
!Reference.IsExport3
) {
439
      // "import 'side-effect';"
440
3
      Reference.Category = JsModuleReference::ReferenceCategory::SIDE_EFFECT;
441
3
      Reference.URL =
442
3
          Current->TokenText.substr(1, Current->TokenText.size() - 2);
443
3
      return true;
444
3
    }
445
446
91
    if (!parseModuleBindings(Keywords, Reference))
447
0
      return false;
448
449
91
    if (Current->is(Keywords.kw_from)) {
450
      // imports have a 'from' clause, exports might not.
451
90
      nextToken();
452
90
      if (!Current->isStringLiteral())
453
0
        return false;
454
      // URL = TokenText without the quotes.
455
90
      Reference.URL =
456
90
          Current->TokenText.substr(1, Current->TokenText.size() - 2);
457
90
      if (Reference.URL.startswith(".."))
458
3
        Reference.Category =
459
3
            JsModuleReference::ReferenceCategory::RELATIVE_PARENT;
460
87
      else if (Reference.URL.startswith("."))
461
20
        Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
462
67
      else
463
67
        Reference.Category = JsModuleReference::ReferenceCategory::ABSOLUTE;
464
90
    } else {
465
      // w/o URL groups with "empty".
466
1
      Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
467
1
    }
468
91
    return true;
469
91
  }
470
471
  bool parseModuleBindings(const AdditionalKeywords &Keywords,
472
91
                           JsModuleReference &Reference) {
473
91
    if (parseStarBinding(Keywords, Reference))
474
3
      return true;
475
88
    return parseNamedBindings(Keywords, Reference);
476
91
  }
477
478
  bool parseStarBinding(const AdditionalKeywords &Keywords,
479
91
                        JsModuleReference &Reference) {
480
    // * as prefix from '...';
481
91
    if (Current->isNot(tok::star))
482
88
      return false;
483
3
    nextToken();
484
3
    if (Current->isNot(Keywords.kw_as))
485
0
      return false;
486
3
    nextToken();
487
3
    if (Current->isNot(tok::identifier))
488
0
      return false;
489
3
    Reference.Prefix = Current->TokenText;
490
3
    nextToken();
491
3
    return true;
492
3
  }
493
494
  bool parseNamedBindings(const AdditionalKeywords &Keywords,
495
88
                          JsModuleReference &Reference) {
496
    // eat a potential "import X, " prefix.
497
88
    if (Current->is(tok::identifier)) {
498
5
      Reference.DefaultImport = Current->TokenText;
499
5
      nextToken();
500
5
      if (Current->is(Keywords.kw_from))
501
3
        return true;
502
2
      if (Current->isNot(tok::comma))
503
0
        return false;
504
2
      nextToken(); // eat comma.
505
2
    }
506
85
    if (Current->isNot(tok::l_brace))
507
0
      return false;
508
509
    // {sym as alias, sym2 as ...} from '...';
510
85
    Reference.SymbolsStart = Current->Tok.getEndLoc();
511
181
    while (Current->isNot(tok::r_brace)) {
512
98
      nextToken();
513
98
      if (Current->is(tok::r_brace))
514
2
        break;
515
96
      if (!Current->isOneOf(tok::identifier, tok::kw_default))
516
0
        return false;
517
518
96
      JsImportedSymbol Symbol;
519
96
      Symbol.Symbol = Current->TokenText;
520
      // Make sure to include any preceding comments.
521
96
      Symbol.Range.setBegin(
522
96
          Current->getPreviousNonComment()->Next->WhitespaceRange.getBegin());
523
96
      nextToken();
524
525
96
      if (Current->is(Keywords.kw_as)) {
526
6
        nextToken();
527
6
        if (!Current->isOneOf(tok::identifier, tok::kw_default))
528
0
          return false;
529
6
        Symbol.Alias = Current->TokenText;
530
6
        nextToken();
531
6
      }
532
96
      Symbol.Range.setEnd(Current->Tok.getLocation());
533
96
      Reference.Symbols.push_back(Symbol);
534
535
96
      if (!Current->isOneOf(tok::r_brace, tok::comma))
536
0
        return false;
537
96
    }
538
85
    Reference.SymbolsEnd = Current->Tok.getLocation();
539
    // For named imports with a trailing comma ("import {X,}"), consider the
540
    // comma to be the end of the import list, so that it doesn't get removed.
541
85
    if (Current->Previous->is(tok::comma))
542
1
      Reference.SymbolsEnd = Current->Previous->Tok.getLocation();
543
85
    nextToken(); // consume r_brace
544
85
    return true;
545
85
  }
546
};
547
548
tooling::Replacements sortJavaScriptImports(const FormatStyle &Style,
549
                                            StringRef Code,
550
                                            ArrayRef<tooling::Range> Ranges,
551
43
                                            StringRef FileName) {
552
  // FIXME: Cursor support.
553
43
  return JavaScriptImportSorter(Environment(Code, FileName, Ranges), Style)
554
43
      .process()
555
43
      .first;
556
43
}
557
558
} // end namespace format
559
} // end namespace clang