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