clang  8.0.0svn
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"
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,
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 
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;
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 
116  assert(!UnwrappedLines.empty());
117  UnwrappedLines.back().push_back(TheLine);
118 }
119 
122 }
123 
124 } // end namespace format
125 } // end namespace clang
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
Defines the clang::FileManager interface and associated types.
Defines the SourceManager interface.
AffectedRangeManager class manages affected ranges in the code.
llvm::Error add(const Replacement &R)
Adds a new replacement R to the current set of replacements.
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:57
Maintains a set of replacements that are conflict-free.
Definition: Replacement.h:210
ArrayRef< CharSourceRange > getCharRanges() const
Definition: TokenAnalyzer.h:56
const Environment & Env
Contains functions for text encoding manipulation.
This file implements a token annotator, i.e.
This file contains FormatTokenLexer, which tokenizes a source file into a token stream suitable for C...
SourceManager and necessary depdencies (e.g.
Defines the Diagnostic-related interfaces.
TokenAnalyzer(const Environment &Env, const FormatStyle &Style)
An unwrapped line is a sequence of Token, that we would like to put on a single line if there was no ...
const SourceManager & getSourceManager() const
Definition: TokenAnalyzer.h:54
A source range independent of the SourceManager.
Definition: Replacement.h:45
Determines extra information about the tokens comprising an UnwrappedLine.
SourceLocation End
void consumeUnwrappedLine(const UnwrappedLine &TheLine) override
const SourceManager & SM
Definition: Format.cpp:1472
StringRef getLanguageName(FormatStyle::LanguageKind Language)
Definition: Format.h:2009
static CharSourceRange getCharRange(SourceRange R)
Environment(SourceManager &SM, FileID ID, ArrayRef< CharSourceRange > Ranges)
Definition: TokenAnalyzer.h:39
Encodes a location in the source.
Various functions to configurably format source code.
This file contains the declaration of the UnwrappedLineParser, which turns a stream of tokens into Un...
Encoding detectEncoding(StringRef Text)
Detects encoding of the Text.
Definition: Encoding.h:35
virtual std::pair< tooling::Replacements, unsigned > analyze(TokenAnnotator &Annotator, SmallVectorImpl< AnnotatedLine *> &AnnotatedLines, FormatTokenLexer &Tokens)=0
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:48
encoding::Encoding Encoding
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:1201
Dataflow Directional Tag Classes.
std::pair< tooling::Replacements, unsigned > process()
std::string toString(const til::SExpr *E)
This file declares an abstract TokenAnalyzer, and associated helper classes.
unsigned getFirstStartColumn() const
Definition: TokenAnalyzer.h:60
SmallVector< SmallVector< UnwrappedLine, 16 >, 2 > UnwrappedLines
ReplacementsImpl::const_iterator const_iterator
Definition: Replacement.h:215
This file contains the declaration of the FormatToken, a wrapper around Token with additional informa...
const encoding::Encoding Encoding
const FormatStyle & Style