Coverage Report

Created: 2023-11-11 10:31

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