clang 10.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"
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/Support/Debug.h"
30
31 #define DEBUG_TYPE "format-formatter"
32
33 namespace clang {
34 namespace format {
35
36 Environment::Environment(StringRef Code, StringRef FileName,
37 ArrayRef<tooling::Range> Ranges,
38 unsigned FirstStartColumn, unsigned NextStartColumn,
39 unsigned LastStartColumn)
40 : VirtualSM(new SourceManagerForFile(FileName, Code)), SM(VirtualSM->get()),
41 ID(VirtualSM->get().getMainFileID()), FirstStartColumn(FirstStartColumn),
42 NextStartColumn(NextStartColumn), LastStartColumn(LastStartColumn) {
43 SourceLocation StartOfFile = SM.getLocForStartOfFile(ID);
44 for (const tooling::Range &Range : Ranges) {
45 SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
46 SourceLocation End = Start.getLocWithOffset(Range.getLength());
47 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
48 }
49 }
50
51 TokenAnalyzer::TokenAnalyzer(const Environment &Env, const FormatStyle &Style)
52 : Style(Style), Env(Env),
53 AffectedRangeMgr(Env.getSourceManager(), Env.getCharRanges()),
54 UnwrappedLines(1),
55 Encoding(encoding::detectEncoding(
56 Env.getSourceManager().getBufferData(Env.getFileID()))) {
57 LLVM_DEBUG(
58 llvm::dbgs() << "File encoding: "
59 << (Encoding == encoding::Encoding_UTF8 ? "UTF8" : "unknown")
60 << "\n");
61 LLVM_DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
62 << "\n");
63 }
64
65 std::pair<tooling::Replacements, unsigned> TokenAnalyzer::process() {
66 tooling::Replacements Result;
67 FormatTokenLexer Tokens(Env.getSourceManager(), Env.getFileID(),
68 Env.getFirstStartColumn(), Style, Encoding);
69
70 UnwrappedLineParser Parser(Style, Tokens.getKeywords(),
71 Env.getFirstStartColumn(), Tokens.lex(), *this);
72 Parser.parse();
73 assert(UnwrappedLines.rbegin()->empty());
74 unsigned Penalty = 0;
75 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE; ++Run) {
76 LLVM_DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
77 SmallVector<AnnotatedLine *, 16> AnnotatedLines;
78
79 TokenAnnotator Annotator(Style, Tokens.getKeywords());
80 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
81 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
82 Annotator.annotate(*AnnotatedLines.back());
83 }
84
85 std::pair<tooling::Replacements, unsigned> RunResult =
86 analyze(Annotator, AnnotatedLines, Tokens);
87
88 LLVM_DEBUG({
89 llvm::dbgs() << "Replacements for run " << Run << ":\n";
90 for (tooling::Replacements::const_iterator I = RunResult.first.begin(),
91 E = RunResult.first.end();
92 I != E; ++I) {
93 llvm::dbgs() << I->toString() << "\n";
94 }
95 });
96 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
97 delete AnnotatedLines[i];
98 }
99
100 Penalty += RunResult.second;
101 for (const auto &R : RunResult.first) {
102 auto Err = Result.add(R);
103 // FIXME: better error handling here. For now, simply return an empty
104 // Replacements to indicate failure.
105 if (Err) {
106 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
107 return {tooling::Replacements(), 0};
108 }
109 }
110 }
111 return {Result, Penalty};
112 }
113
114 void TokenAnalyzer::consumeUnwrappedLine(const UnwrappedLine &TheLine) {
115 assert(!UnwrappedLines.empty());
116 UnwrappedLines.back().push_back(TheLine);
117 }
118
119 void TokenAnalyzer::finishRun() {
120 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
121 }
122
123 } // end namespace format
124 } // 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:1109
clang::Builtin::ID
ID
Definition: Builtins.h:46
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:132
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:245
clang::Parser
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:57
clang::format::TokenAnalyzer::finishRun
void finishRun() override
Definition: TokenAnalyzer.cpp:119
clang::tooling::Replacements
Maintains a set of replacements that are conflict-free.
Definition: Replacement.h:209
clang::format::Environment::getCharRanges
ArrayRef< CharSourceRange > getCharRanges() const
Definition: TokenAnalyzer.h:51
clang::format::TokenAnalyzer::Env
const Environment & Env
Definition: TokenAnalyzer.h:98
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:856
TokenAnnotator.h
This file implements a token annotator, i.e.
clang::format::TokenAnalyzer::Style
FormatStyle Style
Definition: TokenAnalyzer.h:96
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:1894
Diagnostic.h
Defines the Diagnostic-related interfaces.
clang::format::FormatTokenLexer
Definition: FormatTokenLexer.h:37
clang::format::TokenAnalyzer::TokenAnalyzer
TokenAnalyzer(const Environment &Env, const FormatStyle &Style)
Definition: TokenAnalyzer.cpp:51
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:36
llvm::ArrayRef
Definition: LLVM.h:31
clang::format::Environment::getSourceManager
const SourceManager & getSourceManager() const
Definition: TokenAnalyzer.h:49
clang::format::UnwrappedLineParser
Definition: UnwrappedLineParser.h:75
clang::tooling::Range
A source range independent of the SourceManager.
Definition: Replacement.h:44
clang::format::TokenAnnotator
Determines extra information about the tokens comprising an UnwrappedLine.
Definition: TokenAnnotator.h:157
End
SourceLocation End
Definition: USRLocFinder.cpp:166
clang::format::encoding::Encoding_UTF8
Definition: Encoding.h:28
clang::format::TokenAnalyzer::consumeUnwrappedLine
void consumeUnwrappedLine(const UnwrappedLine &TheLine) override
Definition: TokenAnalyzer.cpp:114
clang::format::Environment::getFileID
FileID getFileID() const
Definition: TokenAnalyzer.h:47
clang::format::AnnotatedLine
Definition: TokenAnnotator.h:37
SM
const SourceManager & SM
Definition: Format.cpp:1685
clang::format::getLanguageName
StringRef getLanguageName(FormatStyle::LanguageKind Language)
Definition: Format.h:2419
clang::CharSourceRange::getCharRange
static CharSourceRange getCharRange(SourceRange R)
Definition: SourceLocation.h:262
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
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:34
llvm::SmallVector
Definition: LLVM.h:35
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:49
clang::format::TokenAnalyzer::Encoding
encoding::Encoding Encoding
Definition: TokenAnalyzer.h:102
clang
Dataflow Directional Tag Classes.
Definition: CFGReachabilityAnalysis.h:21
clang::format::TokenAnalyzer::process
std::pair< tooling::Replacements, unsigned > process()
Definition: TokenAnalyzer.cpp:65
TokenAnalyzer.h
This file declares an abstract TokenAnalyzer, and associated helper classes.
clang::format::Environment::getFirstStartColumn
unsigned getFirstStartColumn() const
Definition: TokenAnalyzer.h:55
clang::format::TokenAnalyzer::UnwrappedLines
SmallVector< SmallVector< UnwrappedLine, 16 >, 2 > UnwrappedLines
Definition: TokenAnalyzer.h:101
DiagnosticOptions.h
clang::format::Environment::Environment
Environment(StringRef Code, StringRef FileName, ArrayRef< tooling::Range > Ranges, unsigned FirstStartColumn=0, unsigned NextStartColumn=0, unsigned LastStartColumn=0)
Definition: TokenAnalyzer.cpp:36
clang::tooling::Replacements::const_iterator
ReplacementsImpl::const_iterator const_iterator
Definition: Replacement.h:214
FormatToken.h
This file contains the declaration of the FormatToken, a wrapper around Token with additional informa...
clang::format::Environment
Definition: TokenAnalyzer.h:36
clang::format::Encoding
const encoding::Encoding Encoding
Definition: BreakableToken.h:241
clang::format::Style
const FormatStyle & Style
Definition: BreakableToken.h:242