clang  15.0.0git
TokenAnalyzer.cpp
Go to the documentation of this file.
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"
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 // FIXME: Instead of printing the diagnostic we should store it and have a
39 // better way to return errors through the format APIs.
41 public:
43  const Diagnostic &Info) override {
44  if (DiagLevel == DiagnosticsEngine::Fatal) {
45  Fatal = true;
47  Info.FormatDiagnostic(Message);
48  llvm::errs() << Message << "\n";
49  }
50  }
51 
52  bool fatalError() const { return Fatal; }
53 
54 private:
55  bool Fatal = false;
56 };
57 
58 std::unique_ptr<Environment>
59 Environment::make(StringRef Code, StringRef FileName,
60  ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
61  unsigned NextStartColumn, unsigned LastStartColumn) {
62  auto Env = std::make_unique<Environment>(Code, FileName, FirstStartColumn,
63  NextStartColumn, LastStartColumn);
65  Env->SM.getDiagnostics().setClient(&Diags, /*ShouldOwnClient=*/false);
66  SourceLocation StartOfFile = Env->SM.getLocForStartOfFile(Env->ID);
67  for (const tooling::Range &Range : Ranges) {
68  SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
69  SourceLocation End = Start.getLocWithOffset(Range.getLength());
70  Env->CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
71  }
72  // Validate that we can get the buffer data without a fatal error.
73  Env->SM.getBufferData(Env->ID);
74  if (Diags.fatalError())
75  return nullptr;
76  return Env;
77 }
78 
79 Environment::Environment(StringRef Code, StringRef FileName,
80  unsigned FirstStartColumn, unsigned NextStartColumn,
81  unsigned LastStartColumn)
82  : VirtualSM(new SourceManagerForFile(FileName, Code)), SM(VirtualSM->get()),
83  ID(VirtualSM->get().getMainFileID()), FirstStartColumn(FirstStartColumn),
84  NextStartColumn(NextStartColumn), LastStartColumn(LastStartColumn) {}
85 
87  : Style(Style), Env(Env),
88  AffectedRangeMgr(Env.getSourceManager(), Env.getCharRanges()),
89  UnwrappedLines(1),
90  Encoding(encoding::detectEncoding(
91  Env.getSourceManager().getBufferData(Env.getFileID()))) {
92  LLVM_DEBUG(
93  llvm::dbgs() << "File encoding: "
94  << (Encoding == encoding::Encoding_UTF8 ? "UTF8" : "unknown")
95  << "\n");
96  LLVM_DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
97  << "\n");
98 }
99 
100 std::pair<tooling::Replacements, unsigned> TokenAnalyzer::process() {
101  tooling::Replacements Result;
102  llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
105  Env.getFirstStartColumn(), Style, Encoding, Allocator,
106 
107  IdentTable);
108  ArrayRef<FormatToken *> Toks(Lex.lex());
109  SmallVector<FormatToken *, 10> Tokens(Toks.begin(), Toks.end());
111  Env.getFirstStartColumn(), Tokens, *this);
112  Parser.parse();
113  assert(UnwrappedLines.back().empty());
114  unsigned Penalty = 0;
115  for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE; ++Run) {
116  const auto &Lines = UnwrappedLines[Run];
117  LLVM_DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
118  SmallVector<AnnotatedLine *, 16> AnnotatedLines;
119  AnnotatedLines.reserve(Lines.size());
120 
121  TokenAnnotator Annotator(Style, Lex.getKeywords());
122  for (const UnwrappedLine &Line : Lines) {
123  AnnotatedLines.push_back(new AnnotatedLine(Line));
124  Annotator.annotate(*AnnotatedLines.back());
125  }
126 
127  std::pair<tooling::Replacements, unsigned> RunResult =
128  analyze(Annotator, AnnotatedLines, Lex);
129 
130  LLVM_DEBUG({
131  llvm::dbgs() << "Replacements for run " << Run << ":\n";
132  for (const tooling::Replacement &Fix : RunResult.first)
133  llvm::dbgs() << Fix.toString() << "\n";
134  });
135  for (AnnotatedLine *Line : AnnotatedLines)
136  delete Line;
137 
138  Penalty += RunResult.second;
139  for (const auto &R : RunResult.first) {
140  auto Err = Result.add(R);
141  // FIXME: better error handling here. For now, simply return an empty
142  // Replacements to indicate failure.
143  if (Err) {
144  llvm::errs() << llvm::toString(std::move(Err)) << "\n";
145  return {tooling::Replacements(), 0};
146  }
147  }
148  }
149  return {Result, Penalty};
150 }
151 
153  assert(!UnwrappedLines.empty());
154  UnwrappedLines.back().push_back(TheLine);
155 }
156 
159 }
160 
161 } // end namespace format
162 } // end namespace clang
clang::DiagnosticsEngine::Level
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:195
clang::tooling::Replacement::toString
std::string toString() const
Returns a human readable string representation.
Definition: Replacement.cpp:87
clang::format::FormatTokenLexer::lex
ArrayRef< FormatToken * > lex()
Definition: FormatTokenLexer.cpp:76
clang::format::FatalDiagnosticConsumer::HandleDiagnostic
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) override
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
Definition: TokenAnalyzer.cpp:42
clang::format::TokenAnalyzer::analyze
virtual std::pair< tooling::Replacements, unsigned > analyze(TokenAnnotator &Annotator, SmallVectorImpl< AnnotatedLine * > &AnnotatedLines, FormatTokenLexer &Tokens)=0
clang::format::TokenAnalyzer::Env
const Environment & Env
Definition: TokenAnalyzer.h:106
llvm::SmallVector
Definition: LLVM.h:38
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:134
clang::DiagnosticConsumer
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Definition: Diagnostic.h:1738
clang::tooling::Range
A source range independent of the SourceManager.
Definition: Replacement.h:44
clang::tooling::Replacements
Maintains a set of replacements that are conflict-free.
Definition: Replacement.h:209
clang::format::FormatStyle
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:54
clang::Parser
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:60
clang::format::encoding::Encoding_UTF8
@ Encoding_UTF8
Definition: Encoding.h:28
SourceManager.h
clang::format::UnwrappedLine
An unwrapped line is a sequence of Token, that we would like to put on a single line if there was no ...
Definition: UnwrappedLineParser.h:37
clang::format::TokenAnalyzer::process
std::pair< tooling::Replacements, unsigned > process()
Definition: TokenAnalyzer.cpp:100
Format.h
clang::format::Environment::getFileID
FileID getFileID() const
Definition: TokenAnalyzer.h:47
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::format::UnwrappedLineParser
Definition: UnwrappedLineParser.h:75
clang::format::encoding::detectEncoding
Encoding detectEncoding(StringRef Text)
Detects encoding of the Text.
Definition: Encoding.h:34
Encoding.h
clang::format::TokenAnalyzer::TokenAnalyzer
TokenAnalyzer(const Environment &Env, const FormatStyle &Style)
Definition: TokenAnalyzer.cpp:86
clang::format::FormatTokenLexer::getKeywords
const AdditionalKeywords & getKeywords()
Definition: FormatTokenLexer.h:48
clang::Diagnostic
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1560
TokenAnnotator.h
clang::CharSourceRange::getCharRange
static CharSourceRange getCharRange(SourceRange R)
Definition: SourceLocation.h:265
clang::format::FatalDiagnosticConsumer::fatalError
bool fatalError() const
Definition: TokenAnalyzer.cpp:52
clang::format::encoding::Encoding
Encoding
Definition: Encoding.h:27
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:90
clang::format::TokenAnalyzer::consumeUnwrappedLine
void consumeUnwrappedLine(const UnwrappedLine &TheLine) override
Definition: TokenAnalyzer.cpp:152
Diagnostic.h
clang::format::AnnotatedLine
Definition: TokenAnnotator.h:36
clang::format::TokenAnalyzer::UnwrappedLines
SmallVector< SmallVector< UnwrappedLine, 16 >, 2 > UnwrappedLines
Definition: TokenAnalyzer.h:109
clang::format::Environment::Environment
Environment(StringRef Code, StringRef FileName, unsigned FirstStartColumn=0, unsigned NextStartColumn=0, unsigned LastStartColumn=0)
Definition: TokenAnalyzer.cpp:79
clang::format::Environment
Definition: TokenAnalyzer.h:37
clang::format::getFormattingLangOpts
LangOptions getFormattingLangOpts(const FormatStyle &Style=getLLVMStyle())
Returns the LangOpts that the formatter expects you to set.
Definition: Format.cpp:3364
clang::format::TokenAnnotator
Determines extra information about the tokens comprising an UnwrappedLine.
Definition: TokenAnnotator.h:156
clang::format::TokenAnnotator::annotate
void annotate(AnnotatedLine &Line) const
Definition: TokenAnnotator.cpp:2562
clang::SourceManagerForFile
SourceManager and necessary depdencies (e.g.
Definition: SourceManager.h:1912
clang::format::TokenAnalyzer::Encoding
encoding::Encoding Encoding
Definition: TokenAnalyzer.h:110
Line
const AnnotatedLine * Line
Definition: UsingDeclarationsSorter.cpp:68
UnwrappedLineParser.h
clang::format::Environment::getSourceManager
const SourceManager & getSourceManager() const
Definition: TokenAnalyzer.h:49
clang::format::FormatStyle::Language
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:2601
clang::format::TokenAnalyzer::finishRun
void finishRun() override
Definition: TokenAnalyzer.cpp:157
llvm::ArrayRef
Definition: LLVM.h:34
clang::tooling::Replacement
A text replacement.
Definition: Replacement.h:83
clang::format::FatalDiagnosticConsumer
Definition: TokenAnalyzer.cpp:40
FormatTokenLexer.h
clang::Builtin::ID
ID
Definition: Builtins.h:51
clang
Definition: CalledOnceCheck.h:17
clang::format::getLanguageName
StringRef getLanguageName(FormatStyle::LanguageKind Language)
Definition: Format.h:4268
clang::IdentifierTable
Implements an efficient mapping from strings to IdentifierInfo nodes.
Definition: IdentifierTable.h:563
clang::format::FormatTokenLexer
Definition: FormatTokenLexer.h:39
DiagnosticOptions.h
FormatToken.h
clang::DiagnosticsEngine::Fatal
@ Fatal
Definition: Diagnostic.h:201
FileManager.h
SM
#define SM(sm)
Definition: Cuda.cpp:81
clang::Diagnostic::FormatDiagnostic
void FormatDiagnostic(SmallVectorImpl< char > &OutStr) const
Format this diagnostic into a string, substituting the formal arguments into the %0 slots.
Definition: Diagnostic.cpp:792
clang::format::TokenAnalyzer::Style
FormatStyle Style
Definition: TokenAnalyzer.h:104
clang::format::Environment::getFirstStartColumn
unsigned getFirstStartColumn() const
Definition: TokenAnalyzer.h:55
AffectedRangeManager.h
TokenAnalyzer.h
clang::format::Environment::make
static std::unique_ptr< Environment > make(StringRef Code, StringRef FileName, ArrayRef< tooling::Range > Ranges, unsigned FirstStartColumn=0, unsigned NextStartColumn=0, unsigned LastStartColumn=0)
Definition: TokenAnalyzer.cpp:59