clang 8.0.0

TokenAnalyzer.cpp
Go to the documentation of this file.
1 //===--- TokenAnalyzer.cpp - Analyze Token Streams --------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// This file implements an abstract TokenAnalyzer and associated helper
12 /// classes. TokenAnalyzer can be extended to generate replacements based on
13 /// an annotated and pre-processed token stream.
14 ///
15 //===----------------------------------------------------------------------===//
16
17 #include "TokenAnalyzer.h"
18 #include "AffectedRangeManager.h"
19 #include "Encoding.h"
20 #include "FormatToken.h"
21 #include "FormatTokenLexer.h"
22 #include "TokenAnnotator.h"
23 #include "UnwrappedLineParser.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/DiagnosticOptions.h"
26 #include "clang/Basic/FileManager.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Format/Format.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Support/Debug.h"
31
32 #define DEBUG_TYPE "format-formatter"
33
34 namespace clang {
35 namespace format {
36
37 Environment::Environment(StringRef Code, StringRef FileName,
38 ArrayRef<tooling::Range> Ranges,
39 unsigned FirstStartColumn, unsigned NextStartColumn,
40 unsigned LastStartColumn)
41 : VirtualSM(new SourceManagerForFile(FileName, Code)), SM(VirtualSM->get()),
42 ID(VirtualSM->get().getMainFileID()), FirstStartColumn(FirstStartColumn),
43 NextStartColumn(NextStartColumn), LastStartColumn(LastStartColumn) {
44 SourceLocation StartOfFile = SM.getLocForStartOfFile(ID);
45 for (const tooling::Range &Range : Ranges) {
46 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
47 SourceLocation End = Start.getLocWithOffset(Range.getLength());
48 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
49 }
50 }
51
52 TokenAnalyzer::TokenAnalyzer(const Environment &Env, const FormatStyle &Style)
53 : Style(Style), Env(Env),
54 AffectedRangeMgr(Env.getSourceManager(), Env.getCharRanges()),
55 UnwrappedLines(1),
56 Encoding(encoding::detectEncoding(
57 Env.getSourceManager().getBufferData(Env.getFileID()))) {
58 LLVM_DEBUG(
59 llvm::dbgs() << "File encoding: "
60 << (Encoding == encoding::Encoding_UTF8 ? "UTF8" : "unknown")
61 << "\n");
62 LLVM_DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
63 << "\n");
64 }
65
66 std::pair<tooling::Replacements, unsigned> TokenAnalyzer::process() {
67 tooling::Replacements Result;
68 FormatTokenLexer Tokens(Env.getSourceManager(), Env.getFileID(),
69 Env.getFirstStartColumn(), Style, Encoding);
70
71 UnwrappedLineParser Parser(Style, Tokens.getKeywords(),
72 Env.getFirstStartColumn(), Tokens.lex(), *this);
73 Parser.parse();
74 assert(UnwrappedLines.rbegin()->empty());
75 unsigned Penalty = 0;
76 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE; ++Run) {
77 LLVM_DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
78 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
79
80 TokenAnnotator Annotator(Style, Tokens.getKeywords());
81 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
82 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
83 Annotator.annotate(*AnnotatedLines.back());
84 }
85
86 std::pair<tooling::Replacements, unsigned> RunResult =
87 analyze(Annotator, AnnotatedLines, Tokens);
88
89 LLVM_DEBUG({
90 llvm::dbgs() << "Replacements for run " << Run << ":\n";
91 for (tooling::Replacements::const_iterator I = RunResult.first.begin(),
92 E = RunResult.first.end();
93 I != E; ++I) {
94 llvm::dbgs() << I->toString() << "\n";
95 }
96 });
97 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
98 delete AnnotatedLines[i];
99 }
100
101 Penalty += RunResult.second;
102 for (const auto &R : RunResult.first) {
103 auto Err = Result.add(R);
104 // FIXME: better error handling here. For now, simply return an empty
105 // Replacements to indicate failure.
106 if (Err) {
107 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
108 return {tooling::Replacements(), 0};
109 }
110 }
111 }
112 return {Result, Penalty};
113 }
114
115 void TokenAnalyzer::consumeUnwrappedLine(const UnwrappedLine &TheLine) {
116 assert(!UnwrappedLines.empty());
117 UnwrappedLines.back().push_back(TheLine);
118 }
119
120 void TokenAnalyzer::finishRun() {
121 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
122 }
123
124 } // end namespace format
125 } // end namespace clang
clang::SourceManager::getLocForStartOfFile
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
Definition: SourceManager.h:1067
clang::Builtin::ID
ID
Definition: Builtins.h:49
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:134
FileManager.h
Defines the clang::FileManager interface and associated types.
SourceManager.h
Defines the SourceManager interface.
AffectedRangeManager.h
AffectedRangeManager class manages affected ranges in the code.
clang::tooling::Replacements::add
llvm::Error add(const Replacement &R)
Adds a new replacement R to the current set of replacements.
Definition: Replacement.cpp:246
clang::Parser
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:58
clang::format::TokenAnalyzer::finishRun
void finishRun() override
Definition: TokenAnalyzer.cpp:120
clang::tooling::Replacements
Maintains a set of replacements that are conflict-free.
Definition: Replacement.h:210
clang::format::Environment::getCharRanges
ArrayRef< CharSourceRange > getCharRanges() const
Definition: TokenAnalyzer.h:56
clang::format::TokenAnalyzer::Env
const Environment & Env
Definition: TokenAnalyzer.h:103
Encoding.h
Contains functions for text encoding manipulation.
toString
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Definition: SanitizerArgs.cpp:775
TokenAnnotator.h
This file implements a token annotator, i.e.
clang::format::TokenAnalyzer::Style
FormatStyle Style
Definition: TokenAnalyzer.h:101
FormatTokenLexer.h
This file contains FormatTokenLexer, which tokenizes a source file into a token stream suitable for C...
clang::SourceManagerForFile
SourceManager and necessary depdencies (e.g.
Definition: SourceManager.h:1833
Diagnostic.h
Defines the Diagnostic-related interfaces.
clang::format::FormatTokenLexer
Definition: FormatTokenLexer.h:38
clang::format::TokenAnalyzer::TokenAnalyzer
TokenAnalyzer(const Environment &Env, const FormatStyle &Style)
Definition: TokenAnalyzer.cpp:52
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
llvm::ArrayRef
Definition: LLVM.h:32
clang::format::Environment::getSourceManager
const SourceManager & getSourceManager() const
Definition: TokenAnalyzer.h:54
clang::format::UnwrappedLineParser
Definition: UnwrappedLineParser.h:76
clang::tooling::Range
A source range independent of the SourceManager.
Definition: Replacement.h:45
clang::format::TokenAnnotator
Determines extra information about the tokens comprising an UnwrappedLine.
Definition: TokenAnnotator.h:150
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::format::encoding::Encoding_UTF8
Definition: Encoding.h:29
clang::format::TokenAnalyzer::consumeUnwrappedLine
void consumeUnwrappedLine(const UnwrappedLine &TheLine) override
Definition: TokenAnalyzer.cpp:115
clang::format::Environment::getFileID
FileID getFileID() const
Definition: TokenAnalyzer.h:52
clang::format::AnnotatedLine
Definition: TokenAnnotator.h:38
SM
const SourceManager & SM
Definition: Format.cpp:1490
clang::format::getLanguageName
StringRef getLanguageName(FormatStyle::LanguageKind Language)
Definition: Format.h:2050
clang::CharSourceRange::getCharRange
static CharSourceRange getCharRange(SourceRange R)
Definition: SourceLocation.h:248
clang::format::Environment::Environment
Environment(SourceManager &SM, FileID ID, ArrayRef< CharSourceRange > Ranges)
Definition: TokenAnalyzer.h:39
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:88
Format.h
Various functions to configurably format source code.
UnwrappedLineParser.h
This file contains the declaration of the UnwrappedLineParser, which turns a stream of tokens into Un...
clang::format::encoding::detectEncoding
Encoding detectEncoding(StringRef Text)
Detects encoding of the Text.
Definition: Encoding.h:35
llvm::SmallVector
Definition: LLVM.h:36
clang::format::TokenAnalyzer::analyze
virtual std::pair< tooling::Replacements, unsigned > analyze(TokenAnnotator &Annotator, SmallVectorImpl< AnnotatedLine *> &AnnotatedLines, FormatTokenLexer &Tokens)=0
clang::format::FormatStyle
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:50
clang::format::TokenAnalyzer::Encoding
encoding::Encoding Encoding
Definition: TokenAnalyzer.h:107
clang::format::FormatStyle::Language
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:1241
clang
Dataflow Directional Tag Classes.
Definition: CFGReachabilityAnalysis.h:22
clang::format::TokenAnalyzer::process
std::pair< tooling::Replacements, unsigned > process()
Definition: TokenAnalyzer.cpp:66
TokenAnalyzer.h
This file declares an abstract TokenAnalyzer, and associated helper classes.
clang::format::Environment::getFirstStartColumn
unsigned getFirstStartColumn() const
Definition: TokenAnalyzer.h:60
clang::format::TokenAnalyzer::UnwrappedLines
SmallVector< SmallVector< UnwrappedLine, 16 >, 2 > UnwrappedLines
Definition: TokenAnalyzer.h:106
DiagnosticOptions.h
clang::tooling::Replacements::const_iterator
ReplacementsImpl::const_iterator const_iterator
Definition: Replacement.h:215
FormatToken.h
This file contains the declaration of the FormatToken, a wrapper around Token with additional informa...
clang::format::Environment
Definition: TokenAnalyzer.h:37
clang::format::Encoding
const encoding::Encoding Encoding
Definition: BreakableToken.h:246
clang::format::Style
const FormatStyle & Style
Definition: BreakableToken.h:247