#include "SortJavaScriptImports.h"
#include "TokenAnalyzer.h"
#include "TokenAnnotator.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Format/Format.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Debug.h"
#include <algorithm>
#include <string>
#define DEBUG_TYPE "format-formatter"
namespace clang {
namespace format {
class FormatTokenLexer;
using clang::format::FormatStyle;
struct JsImportedSymbol {
StringRef Symbol;
StringRef Alias;
SourceRange Range;
bool operator==(const JsImportedSymbol &RHS) const {
return Symbol == RHS.Symbol && Alias == RHS.Alias;
}
};
struct JsModuleReference {
bool FormattingOff = false;
bool IsExport = false;
enum ReferenceCategory {
SIDE_EFFECT, ABSOLUTE, RELATIVE_PARENT, RELATIVE, ALIAS, };
ReferenceCategory Category = ReferenceCategory::SIDE_EFFECT;
StringRef URL;
StringRef Prefix;
StringRef DefaultImport;
SmallVector<JsImportedSymbol, 1> Symbols;
bool SymbolsMerged = false;
SourceLocation SymbolsStart, SymbolsEnd;
SourceRange Range;
};
bool operator<(const JsModuleReference &LHS, const JsModuleReference &RHS) {
if (LHS.IsExport != RHS.IsExport)
return LHS.IsExport < RHS.IsExport;
if (LHS.Category != RHS.Category)
return LHS.Category < RHS.Category;
if (LHS.Category == JsModuleReference::ReferenceCategory::SIDE_EFFECT ||
LHS.Category == JsModuleReference::ReferenceCategory::ALIAS) {
return false;
}
if (LHS.URL.empty() != RHS.URL.empty())
return LHS.URL.empty() < RHS.URL.empty();
if (int Res = LHS.URL.compare_insensitive(RHS.URL))
return Res < 0;
if (LHS.Prefix.empty() != RHS.Prefix.empty())
return LHS.Prefix.empty() < RHS.Prefix.empty();
if (LHS.Prefix != RHS.Prefix)
return LHS.Prefix > RHS.Prefix;
return false;
}
class JavaScriptImportSorter : public TokenAnalyzer {
public:
JavaScriptImportSorter(const Environment &Env, const FormatStyle &Style)
: TokenAnalyzer(Env, Style),
FileContents(Env.getSourceManager().getBufferData(Env.getFileID())) {
invalidToken.Tok.startToken();
}
std::pair<tooling::Replacements, unsigned>
analyze(TokenAnnotator &Annotator,
SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
FormatTokenLexer &Tokens) override {
tooling::Replacements Result;
AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
const AdditionalKeywords &Keywords = Tokens.getKeywords();
SmallVector<JsModuleReference, 16> References;
AnnotatedLine *FirstNonImportLine;
std::tie(References, FirstNonImportLine) =
parseModuleReferences(Keywords, AnnotatedLines);
if (References.empty())
return {Result, 0};
SourceRange InsertionPoint = References[0].Range;
InsertionPoint.setEnd(References[References.size() - 1].Range.getEnd());
References = sortModuleReferences(References);
std::string ReferencesText;
for (unsigned I = 0, E = References.size(); I != E; ++I) {
JsModuleReference Reference = References[I];
appendReference(ReferencesText, Reference);
if (I + 1 < E) {
ReferencesText += "\n";
if (!Reference.IsExport &&
(Reference.IsExport != References[I + 1].IsExport ||
Reference.Category != References[I + 1].Category)) {
ReferencesText += "\n";
}
}
}
llvm::StringRef PreviousText = getSourceText(InsertionPoint);
if (ReferencesText == PreviousText)
return {Result, 0};
unsigned PreviousSize = PreviousText.size();
while (ReferencesText.size() < PreviousSize)
ReferencesText += " ";
if (FirstNonImportLine && FirstNonImportLine->First->NewlinesBefore < 2 &&
!(FirstNonImportLine->First->is(tok::comment) &&
FirstNonImportLine->First->TokenText.trim() ==
"// clang-format on")) {
ReferencesText += "\n";
}
LLVM_DEBUG(llvm::dbgs() << "Replacing imports:\n"
<< PreviousText << "\nwith:\n"
<< ReferencesText << "\n");
auto Err = Result.add(tooling::Replacement(
Env.getSourceManager(), CharSourceRange::getCharRange(InsertionPoint),
ReferencesText));
if (Err) {
llvm::errs() << llvm::toString(std::move(Err)) << "\n";
assert(false);
}
return {Result, 0};
}
private:
FormatToken *Current;
FormatToken *LineEnd;
FormatToken invalidToken;
StringRef FileContents;
void skipComments() { Current = skipComments(Current); }
FormatToken *skipComments(FormatToken *Tok) {
while (Tok && Tok->is(tok::comment))
Tok = Tok->Next;
return Tok;
}
void nextToken() {
Current = Current->Next;
skipComments();
if (!Current || Current == LineEnd->Next) {
Current = &invalidToken;
}
}
StringRef getSourceText(SourceRange Range) {
return getSourceText(Range.getBegin(), Range.getEnd());
}
StringRef getSourceText(SourceLocation Begin, SourceLocation End) {
const SourceManager &SM = Env.getSourceManager();
return FileContents.substr(SM.getFileOffset(Begin),
SM.getFileOffset(End) - SM.getFileOffset(Begin));
}
SmallVector<JsModuleReference, 16>
sortModuleReferences(const SmallVector<JsModuleReference, 16> &References) {
const auto *Start = References.begin();
SmallVector<JsModuleReference, 16> ReferencesSorted;
while (Start != References.end()) {
while (Start != References.end() && Start->FormattingOff) {
ReferencesSorted.push_back(*Start);
++Start;
}
SmallVector<JsModuleReference, 16> SortChunk;
while (Start != References.end() && !Start->FormattingOff) {
SortChunk.push_back(*Start);
++Start;
}
llvm::stable_sort(SortChunk);
mergeModuleReferences(SortChunk);
ReferencesSorted.insert(ReferencesSorted.end(), SortChunk.begin(),
SortChunk.end());
}
return ReferencesSorted;
}
void mergeModuleReferences(SmallVector<JsModuleReference, 16> &References) {
if (References.empty())
return;
JsModuleReference *PreviousReference = References.begin();
auto *Reference = std::next(References.begin());
while (Reference != References.end()) {
if (Reference->Category == JsModuleReference::SIDE_EFFECT ||
PreviousReference->Category == JsModuleReference::SIDE_EFFECT ||
Reference->IsExport != PreviousReference->IsExport ||
!PreviousReference->Prefix.empty() || !Reference->Prefix.empty() ||
!PreviousReference->DefaultImport.empty() ||
!Reference->DefaultImport.empty() || Reference->Symbols.empty() ||
PreviousReference->URL != Reference->URL) {
PreviousReference = Reference;
++Reference;
continue;
}
PreviousReference->Symbols.append(Reference->Symbols);
PreviousReference->SymbolsMerged = true;
Reference = References.erase(Reference);
}
}
void appendReference(std::string &Buffer, JsModuleReference &Reference) {
if (Reference.FormattingOff) {
Buffer +=
getSourceText(Reference.Range.getBegin(), Reference.Range.getEnd());
return;
}
SmallVector<JsImportedSymbol, 1> Symbols = Reference.Symbols;
llvm::stable_sort(
Symbols, [&](const JsImportedSymbol &LHS, const JsImportedSymbol &RHS) {
return LHS.Symbol.compare_insensitive(RHS.Symbol) < 0;
});
if (!Reference.SymbolsMerged && Symbols == Reference.Symbols) {
StringRef ReferenceStmt = getSourceText(Reference.Range);
Buffer += ReferenceStmt;
return;
}
Buffer += getSourceText(Reference.Range.getBegin(), Reference.SymbolsStart);
if (!Symbols.empty()) {
Buffer += getSourceText(Symbols.front().Range);
for (const JsImportedSymbol &Symbol : llvm::drop_begin(Symbols)) {
Buffer += ",";
Buffer += getSourceText(Symbol.Range);
}
}
Buffer += getSourceText(Reference.SymbolsEnd, Reference.Range.getEnd());
}
std::pair<SmallVector<JsModuleReference, 16>, AnnotatedLine *>
parseModuleReferences(const AdditionalKeywords &Keywords,
SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
SmallVector<JsModuleReference, 16> References;
SourceLocation Start;
AnnotatedLine *FirstNonImportLine = nullptr;
bool AnyImportAffected = false;
bool FormattingOff = false;
for (auto *Line : AnnotatedLines) {
assert(Line->First);
Current = Line->First;
LineEnd = Line->Last;
while (Current && Current->is(tok::comment)) {
StringRef CommentText = Current->TokenText.trim();
if (CommentText == "// clang-format off") {
FormattingOff = true;
} else if (CommentText == "// clang-format on") {
FormattingOff = false;
if (!References.empty()) {
References.back().Range.setEnd(Current->Tok.getEndLoc());
Start = Current->Tok.getEndLoc().getLocWithOffset(1);
}
}
Current = Current->Next;
}
skipComments();
if (Start.isInvalid() || References.empty()) {
Start = Line->First->Tok.getLocation();
}
if (!Current) {
FirstNonImportLine = Line;
continue;
}
JsModuleReference Reference;
Reference.FormattingOff = FormattingOff;
Reference.Range.setBegin(Start);
Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
if (!parseModuleReference(Keywords, Reference)) {
if (!FirstNonImportLine)
FirstNonImportLine = Line; break;
}
FirstNonImportLine = nullptr;
AnyImportAffected = AnyImportAffected || Line->Affected;
Reference.Range.setEnd(LineEnd->Tok.getEndLoc());
LLVM_DEBUG({
llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport
<< ", cat: " << Reference.Category
<< ", url: " << Reference.URL
<< ", prefix: " << Reference.Prefix;
for (const JsImportedSymbol &Symbol : Reference.Symbols)
llvm::dbgs() << ", " << Symbol.Symbol << " as " << Symbol.Alias;
llvm::dbgs() << ", text: " << getSourceText(Reference.Range);
llvm::dbgs() << "}\n";
});
References.push_back(Reference);
Start = SourceLocation();
}
if (!AnyImportAffected)
References.clear();
return std::make_pair(References, FirstNonImportLine);
}
bool parseModuleReference(const AdditionalKeywords &Keywords,
JsModuleReference &Reference) {
if (!Current || !Current->isOneOf(Keywords.kw_import, tok::kw_export))
return false;
Reference.IsExport = Current->is(tok::kw_export);
nextToken();
if (Current->isStringLiteral() && !Reference.IsExport) {
Reference.Category = JsModuleReference::ReferenceCategory::SIDE_EFFECT;
Reference.URL =
Current->TokenText.substr(1, Current->TokenText.size() - 2);
return true;
}
if (!parseModuleBindings(Keywords, Reference))
return false;
if (Current->is(Keywords.kw_from)) {
nextToken();
if (!Current->isStringLiteral())
return false;
Reference.URL =
Current->TokenText.substr(1, Current->TokenText.size() - 2);
if (Reference.URL.startswith("..")) {
Reference.Category =
JsModuleReference::ReferenceCategory::RELATIVE_PARENT;
} else if (Reference.URL.startswith(".")) {
Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
} else {
Reference.Category = JsModuleReference::ReferenceCategory::ABSOLUTE;
}
}
return true;
}
bool parseModuleBindings(const AdditionalKeywords &Keywords,
JsModuleReference &Reference) {
if (parseStarBinding(Keywords, Reference))
return true;
return parseNamedBindings(Keywords, Reference);
}
bool parseStarBinding(const AdditionalKeywords &Keywords,
JsModuleReference &Reference) {
if (Current->isNot(tok::star))
return false;
nextToken();
if (Current->isNot(Keywords.kw_as))
return false;
nextToken();
if (Current->isNot(tok::identifier))
return false;
Reference.Prefix = Current->TokenText;
nextToken();
return true;
}
bool parseNamedBindings(const AdditionalKeywords &Keywords,
JsModuleReference &Reference) {
if (Current->is(tok::identifier)) {
Reference.DefaultImport = Current->TokenText;
nextToken();
if (Current->is(Keywords.kw_from))
return true;
if (Current->is(tok::equal)) {
Reference.Category = JsModuleReference::ReferenceCategory::ALIAS;
nextToken();
while (Current->is(tok::identifier)) {
nextToken();
if (Current->is(tok::semi))
return true;
if (!Current->is(tok::period))
return false;
nextToken();
}
}
if (Current->isNot(tok::comma))
return false;
nextToken(); }
if (Current->isNot(tok::l_brace))
return false;
Reference.SymbolsStart = Current->Tok.getEndLoc();
while (Current->isNot(tok::r_brace)) {
nextToken();
if (Current->is(tok::r_brace))
break;
if (!Current->isOneOf(tok::identifier, tok::kw_default))
return false;
JsImportedSymbol Symbol;
Symbol.Symbol = Current->TokenText;
Symbol.Range.setBegin(
Current->getPreviousNonComment()->Next->WhitespaceRange.getBegin());
nextToken();
if (Current->is(Keywords.kw_as)) {
nextToken();
if (!Current->isOneOf(tok::identifier, tok::kw_default))
return false;
Symbol.Alias = Current->TokenText;
nextToken();
}
Symbol.Range.setEnd(Current->Tok.getLocation());
Reference.Symbols.push_back(Symbol);
if (!Current->isOneOf(tok::r_brace, tok::comma))
return false;
}
Reference.SymbolsEnd = Current->Tok.getLocation();
if (Current->Previous->is(tok::comma))
Reference.SymbolsEnd = Current->Previous->Tok.getLocation();
nextToken(); return true;
}
};
tooling::Replacements sortJavaScriptImports(const FormatStyle &Style,
StringRef Code,
ArrayRef<tooling::Range> Ranges,
StringRef FileName) {
auto Env = Environment::make(Code, FileName, Ranges);
if (!Env)
return {};
return JavaScriptImportSorter(*Env, Style).process().first;
}
} }