clang  6.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 /// \brief 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 // This sets up an virtual file system with file \p FileName containing \p
38 // Code.
39 std::unique_ptr<Environment>
40 Environment::CreateVirtualEnvironment(StringRef Code, StringRef FileName,
42  unsigned FirstStartColumn,
43  unsigned NextStartColumn,
44  unsigned LastStartColumn) {
45  // This is referenced by `FileMgr` and will be released by `FileMgr` when it
46  // is deleted.
49  // This is passed to `SM` as reference, so the pointer has to be referenced
50  // in `Environment` so that `FileMgr` can out-live this function scope.
51  std::unique_ptr<FileManager> FileMgr(
52  new FileManager(FileSystemOptions(), InMemoryFileSystem));
53  // This is passed to `SM` as reference, so the pointer has to be referenced
54  // by `Environment` due to the same reason above.
55  std::unique_ptr<DiagnosticsEngine> Diagnostics(new DiagnosticsEngine(
57  new DiagnosticOptions));
58  // This will be stored as reference, so the pointer has to be stored in
59  // due to the same reason above.
60  std::unique_ptr<SourceManager> VirtualSM(
61  new SourceManager(*Diagnostics, *FileMgr));
62  InMemoryFileSystem->addFile(
63  FileName, 0,
64  llvm::MemoryBuffer::getMemBuffer(Code, FileName,
65  /*RequiresNullTerminator=*/false));
66  FileID ID = VirtualSM->createFileID(FileMgr->getFile(FileName),
68  assert(ID.isValid());
69  SourceLocation StartOfFile = VirtualSM->getLocForStartOfFile(ID);
70  std::vector<CharSourceRange> CharRanges;
71  for (const tooling::Range &Range : Ranges) {
72  SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
73  SourceLocation End = Start.getLocWithOffset(Range.getLength());
74  CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
75  }
76  return llvm::make_unique<Environment>(
77  ID, std::move(FileMgr), std::move(VirtualSM), std::move(Diagnostics),
78  CharRanges, FirstStartColumn, NextStartColumn, LastStartColumn);
79 }
80 
82  : Style(Style), Env(Env),
83  AffectedRangeMgr(Env.getSourceManager(), Env.getCharRanges()),
84  UnwrappedLines(1),
85  Encoding(encoding::detectEncoding(
86  Env.getSourceManager().getBufferData(Env.getFileID()))) {
87  DEBUG(
88  llvm::dbgs() << "File encoding: "
89  << (Encoding == encoding::Encoding_UTF8 ? "UTF8" : "unknown")
90  << "\n");
91  DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
92  << "\n");
93 }
94 
95 std::pair<tooling::Replacements, unsigned> TokenAnalyzer::process() {
96  tooling::Replacements Result;
99 
100  UnwrappedLineParser Parser(Style, Tokens.getKeywords(),
101  Env.getFirstStartColumn(), Tokens.lex(), *this);
102  Parser.parse();
103  assert(UnwrappedLines.rbegin()->empty());
104  unsigned Penalty = 0;
105  for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE; ++Run) {
106  DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
107  SmallVector<AnnotatedLine *, 16> AnnotatedLines;
108 
109  TokenAnnotator Annotator(Style, Tokens.getKeywords());
110  for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
111  AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
112  Annotator.annotate(*AnnotatedLines.back());
113  }
114 
115  std::pair<tooling::Replacements, unsigned> RunResult =
116  analyze(Annotator, AnnotatedLines, Tokens);
117 
118  DEBUG({
119  llvm::dbgs() << "Replacements for run " << Run << ":\n";
120  for (tooling::Replacements::const_iterator I = RunResult.first.begin(),
121  E = RunResult.first.end();
122  I != E; ++I) {
123  llvm::dbgs() << I->toString() << "\n";
124  }
125  });
126  for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
127  delete AnnotatedLines[i];
128  }
129 
130  Penalty += RunResult.second;
131  for (const auto &R : RunResult.first) {
132  auto Err = Result.add(R);
133  // FIXME: better error handling here. For now, simply return an empty
134  // Replacements to indicate failure.
135  if (Err) {
136  llvm::errs() << llvm::toString(std::move(Err)) << "\n";
137  return {tooling::Replacements(), 0};
138  }
139  }
140  }
141  return {Result, Penalty};
142 }
143 
145  assert(!UnwrappedLines.empty());
146  UnwrappedLines.back().push_back(TheLine);
147 }
148 
151 }
152 
153 } // end namespace format
154 } // end namespace clang
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:116
Defines the clang::FileManager interface and associated types.
Defines the SourceManager interface.
AffectedRangeManager class manages affected ranges in the code.
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:205
ArrayRef< CharSourceRange > getCharRanges() const
Definition: TokenAnalyzer.h:74
const Environment & Env
Contains functions for text encoding manipulation.
This file implements a token annotator, i.e.
An in-memory file system.
This file contains FormatTokenLexer, which tokenizes a source file into a token stream suitable for C...
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:147
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:76
bool isValid() const
A source range independent of the SourceManager.
Definition: Replacement.h:42
Determines extra information about the tokens comprising an UnwrappedLine.
SourceLocation End
void consumeUnwrappedLine(const UnwrappedLine &TheLine) override
StringRef getLanguageName(FormatStyle::LanguageKind Language)
Definition: Format.h:1878
static CharSourceRange getCharRange(SourceRange R)
static std::unique_ptr< Environment > CreateVirtualEnvironment(StringRef Code, StringRef FileName, ArrayRef< tooling::Range > Ranges, unsigned FirstStartColumn=0, unsigned NextStartColumn=0, unsigned LastStartColumn=0)
Encodes a location in the source.
Various functions to configurably format source code.
Options for controlling the compiler diagnostics engine.
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:46
encoding::Encoding Encoding
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:1219
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Dataflow Directional Tag Classes.
std::pair< tooling::Replacements, unsigned > process()
Used for handling and querying diagnostic IDs.
std::string toString(const til::SExpr *E)
Keeps track of options that affect how file operations are performed.
This file declares an abstract TokenAnalyzer, and associated helper classes.
llvm::Error add(const Replacement &R)
Adds a new replacement R to the current set of replacements.
unsigned getFirstStartColumn() const
Definition: TokenAnalyzer.h:80
SmallVector< SmallVector< UnwrappedLine, 16 >, 2 > UnwrappedLines
This file contains the declaration of the FormatToken, a wrapper around Token with additional informa...
ReplacementsImpl::const_iterator const_iterator
Definition: Replacement.h:210
This class handles loading and caching of source files into memory.
const encoding::Encoding Encoding
const FormatStyle & Style