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,
41  ArrayRef<tooling::Range> Ranges) {
42  // This is referenced by `FileMgr` and will be released by `FileMgr` when it
43  // is deleted.
46  // This is passed to `SM` as reference, so the pointer has to be referenced
47  // in `Environment` so that `FileMgr` can out-live this function scope.
48  std::unique_ptr<FileManager> FileMgr(
49  new FileManager(FileSystemOptions(), InMemoryFileSystem));
50  // This is passed to `SM` as reference, so the pointer has to be referenced
51  // by `Environment` due to the same reason above.
52  std::unique_ptr<DiagnosticsEngine> Diagnostics(new DiagnosticsEngine(
54  new DiagnosticOptions));
55  // This will be stored as reference, so the pointer has to be stored in
56  // due to the same reason above.
57  std::unique_ptr<SourceManager> VirtualSM(
58  new SourceManager(*Diagnostics, *FileMgr));
59  InMemoryFileSystem->addFile(
60  FileName, 0,
61  llvm::MemoryBuffer::getMemBuffer(Code, FileName,
62  /*RequiresNullTerminator=*/false));
63  FileID ID = VirtualSM->createFileID(FileMgr->getFile(FileName),
65  assert(ID.isValid());
66  SourceLocation StartOfFile = VirtualSM->getLocForStartOfFile(ID);
67  std::vector<CharSourceRange> CharRanges;
68  for (const tooling::Range &Range : Ranges) {
69  SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
70  SourceLocation End = Start.getLocWithOffset(Range.getLength());
71  CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
72  }
73  return llvm::make_unique<Environment>(ID, std::move(FileMgr),
74  std::move(VirtualSM),
75  std::move(Diagnostics), CharRanges);
76 }
77 
79  : Style(Style), Env(Env),
80  AffectedRangeMgr(Env.getSourceManager(), Env.getCharRanges()),
81  UnwrappedLines(1),
82  Encoding(encoding::detectEncoding(
83  Env.getSourceManager().getBufferData(Env.getFileID()))) {
84  DEBUG(
85  llvm::dbgs() << "File encoding: "
86  << (Encoding == encoding::Encoding_UTF8 ? "UTF8" : "unknown")
87  << "\n");
88  DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
89  << "\n");
90 }
91 
93  tooling::Replacements Result;
95  Encoding);
96 
97  UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(), *this);
98  Parser.parse();
99  assert(UnwrappedLines.rbegin()->empty());
100  for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE; ++Run) {
101  DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
102  SmallVector<AnnotatedLine *, 16> AnnotatedLines;
103 
104  TokenAnnotator Annotator(Style, Tokens.getKeywords());
105  for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
106  AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
107  Annotator.annotate(*AnnotatedLines.back());
108  }
109 
110  tooling::Replacements RunResult =
111  analyze(Annotator, AnnotatedLines, Tokens);
112 
113  DEBUG({
114  llvm::dbgs() << "Replacements for run " << Run << ":\n";
115  for (tooling::Replacements::const_iterator I = RunResult.begin(),
116  E = RunResult.end();
117  I != E; ++I) {
118  llvm::dbgs() << I->toString() << "\n";
119  }
120  });
121  for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
122  delete AnnotatedLines[i];
123  }
124  for (const auto &R : RunResult) {
125  auto Err = Result.add(R);
126  // FIXME: better error handling here. For now, simply return an empty
127  // Replacements to indicate failure.
128  if (Err) {
129  llvm::errs() << llvm::toString(std::move(Err)) << "\n";
130  return tooling::Replacements();
131  }
132  }
133  }
134  return Result;
135 }
136 
138  assert(!UnwrappedLines.empty());
139  UnwrappedLines.back().push_back(TheLine);
140 }
141 
144 }
145 
146 } // end namespace format
147 } // 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:58
const Environment & Env
Definition: TokenAnalyzer.h:93
Contains functions for text encoding manipulation.
This file implements a token annotator, i.e.
An in-memory file system.
virtual tooling::Replacements analyze(TokenAnnotator &Annotator, SmallVectorImpl< AnnotatedLine *> &AnnotatedLines, FormatTokenLexer &Tokens)=0
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:60
const_iterator end() const
Definition: Replacement.h:276
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
const_iterator begin() const
Definition: Replacement.h:274
tooling::Replacements process()
StringRef getLanguageName(FormatStyle::LanguageKind Language)
Definition: Format.h:1799
static CharSourceRange getCharRange(SourceRange R)
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
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:46
encoding::Encoding Encoding
Definition: TokenAnalyzer.h:97
static std::unique_ptr< Environment > CreateVirtualEnvironment(StringRef Code, StringRef FileName, ArrayRef< tooling::Range > Ranges)
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:1185
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Dataflow Directional Tag Classes.
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.
SmallVector< SmallVector< UnwrappedLine, 16 >, 2 > UnwrappedLines
Definition: TokenAnalyzer.h:96
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