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