TokenAnalyzer.cpp 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. //===--- TokenAnalyzer.cpp - Analyze Token Streams --------------*- 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 an abstract TokenAnalyzer and associated helper
  11. /// classes. TokenAnalyzer can be extended to generate replacements based on
  12. /// an annotated and pre-processed token stream.
  13. ///
  14. //===----------------------------------------------------------------------===//
  15. #include "TokenAnalyzer.h"
  16. #include "AffectedRangeManager.h"
  17. #include "Encoding.h"
  18. #include "FormatToken.h"
  19. #include "FormatTokenLexer.h"
  20. #include "TokenAnnotator.h"
  21. #include "UnwrappedLineParser.h"
  22. #include "clang/Basic/Diagnostic.h"
  23. #include "clang/Basic/DiagnosticOptions.h"
  24. #include "clang/Basic/FileManager.h"
  25. #include "clang/Basic/SourceManager.h"
  26. #include "clang/Format/Format.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/SmallVector.h"
  29. #include "llvm/Support/Debug.h"
  30. #include <type_traits>
  31. #define DEBUG_TYPE "format-formatter"
  32. namespace clang {
  33. namespace format {
  34. // FIXME: Instead of printing the diagnostic we should store it and have a
  35. // better way to return errors through the format APIs.
  36. class FatalDiagnosticConsumer : public DiagnosticConsumer {
  37. public:
  38. void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
  39. const Diagnostic &Info) override {
  40. if (DiagLevel == DiagnosticsEngine::Fatal) {
  41. Fatal = true;
  42. llvm::SmallVector<char, 128> Message;
  43. Info.FormatDiagnostic(Message);
  44. llvm::errs() << Message << "\n";
  45. }
  46. }
  47. bool fatalError() const { return Fatal; }
  48. private:
  49. bool Fatal = false;
  50. };
  51. std::unique_ptr<Environment>
  52. Environment::make(StringRef Code, StringRef FileName,
  53. ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
  54. unsigned NextStartColumn, unsigned LastStartColumn) {
  55. auto Env = std::make_unique<Environment>(Code, FileName, FirstStartColumn,
  56. NextStartColumn, LastStartColumn);
  57. FatalDiagnosticConsumer Diags;
  58. Env->SM.getDiagnostics().setClient(&Diags, /*ShouldOwnClient=*/false);
  59. SourceLocation StartOfFile = Env->SM.getLocForStartOfFile(Env->ID);
  60. for (const tooling::Range &Range : Ranges) {
  61. SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
  62. SourceLocation End = Start.getLocWithOffset(Range.getLength());
  63. Env->CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
  64. }
  65. // Validate that we can get the buffer data without a fatal error.
  66. Env->SM.getBufferData(Env->ID);
  67. if (Diags.fatalError())
  68. return nullptr;
  69. return Env;
  70. }
  71. Environment::Environment(StringRef Code, StringRef FileName,
  72. unsigned FirstStartColumn, unsigned NextStartColumn,
  73. unsigned LastStartColumn)
  74. : VirtualSM(new SourceManagerForFile(FileName, Code)), SM(VirtualSM->get()),
  75. ID(VirtualSM->get().getMainFileID()), FirstStartColumn(FirstStartColumn),
  76. NextStartColumn(NextStartColumn), LastStartColumn(LastStartColumn) {}
  77. TokenAnalyzer::TokenAnalyzer(const Environment &Env, const FormatStyle &Style)
  78. : Style(Style), Env(Env),
  79. AffectedRangeMgr(Env.getSourceManager(), Env.getCharRanges()),
  80. UnwrappedLines(1),
  81. Encoding(encoding::detectEncoding(
  82. Env.getSourceManager().getBufferData(Env.getFileID()))) {
  83. LLVM_DEBUG(
  84. llvm::dbgs() << "File encoding: "
  85. << (Encoding == encoding::Encoding_UTF8 ? "UTF8" : "unknown")
  86. << "\n");
  87. LLVM_DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
  88. << "\n");
  89. }
  90. std::pair<tooling::Replacements, unsigned> TokenAnalyzer::process() {
  91. tooling::Replacements Result;
  92. llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
  93. IdentifierTable IdentTable(getFormattingLangOpts(Style));
  94. FormatTokenLexer Lex(Env.getSourceManager(), Env.getFileID(),
  95. Env.getFirstStartColumn(), Style, Encoding, Allocator,
  96. IdentTable);
  97. ArrayRef<FormatToken *> Toks(Lex.lex());
  98. SmallVector<FormatToken *, 10> Tokens(Toks.begin(), Toks.end());
  99. UnwrappedLineParser Parser(Style, Lex.getKeywords(),
  100. Env.getFirstStartColumn(), Tokens, *this);
  101. Parser.parse();
  102. assert(UnwrappedLines.rbegin()->empty());
  103. unsigned Penalty = 0;
  104. for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE; ++Run) {
  105. const auto &Lines = UnwrappedLines[Run];
  106. LLVM_DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
  107. SmallVector<AnnotatedLine *, 16> AnnotatedLines;
  108. TokenAnnotator Annotator(Style, Lex.getKeywords());
  109. for (const UnwrappedLine &Line : Lines) {
  110. AnnotatedLines.push_back(new AnnotatedLine(Line));
  111. Annotator.annotate(*AnnotatedLines.back());
  112. }
  113. std::pair<tooling::Replacements, unsigned> RunResult =
  114. analyze(Annotator, AnnotatedLines, Lex);
  115. LLVM_DEBUG({
  116. llvm::dbgs() << "Replacements for run " << Run << ":\n";
  117. for (const tooling::Replacement &Fix : RunResult.first)
  118. llvm::dbgs() << Fix.toString() << "\n";
  119. });
  120. for (AnnotatedLine *Line : AnnotatedLines)
  121. delete Line;
  122. Penalty += RunResult.second;
  123. for (const auto &R : RunResult.first) {
  124. auto Err = Result.add(R);
  125. // FIXME: better error handling here. For now, simply return an empty
  126. // Replacements to indicate failure.
  127. if (Err) {
  128. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  129. return {tooling::Replacements(), 0};
  130. }
  131. }
  132. }
  133. return {Result, Penalty};
  134. }
  135. void TokenAnalyzer::consumeUnwrappedLine(const UnwrappedLine &TheLine) {
  136. assert(!UnwrappedLines.empty());
  137. UnwrappedLines.back().push_back(TheLine);
  138. }
  139. void TokenAnalyzer::finishRun() {
  140. UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
  141. }
  142. } // end namespace format
  143. } // end namespace clang