1 //===--- TokenAnalyzer.cpp - Analyze Token Streams --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
17 #include "TokenAnalyzer.h"
18 #include "AffectedRangeManager.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"
32 #define DEBUG_TYPE "format-formatter"
37 // This sets up an virtual file system with file \p FileName containing \p
39 std::unique_ptr<Environment>
40 Environment::CreateVirtualEnvironment(StringRef Code, StringRef FileName,
41 ArrayRef<tooling::Range> Ranges,
42 unsigned FirstStartColumn,
43 unsigned NextStartColumn,
44 unsigned LastStartColumn) {
45 // This is referenced by `FileMgr` and will be released by `FileMgr` when it
47 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
48 new vfs::InMemoryFileSystem);
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(
56 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
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(
64 llvm::MemoryBuffer::getMemBuffer(Code, FileName,
65 /*RequiresNullTerminator=*/false));
66 FileID ID = VirtualSM->createFileID(FileMgr->getFile(FileName),
67 SourceLocation(), clang::SrcMgr::C_User);
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));
76 return llvm::make_unique<Environment>(
77 ID, std::move(FileMgr), std::move(VirtualSM), std::move(Diagnostics),
78 CharRanges, FirstStartColumn, NextStartColumn, LastStartColumn);
81 TokenAnalyzer::TokenAnalyzer(const Environment &Env, const FormatStyle &Style)
82 : Style(Style), Env(Env),
83 AffectedRangeMgr(Env.getSourceManager(), Env.getCharRanges()),
85 Encoding(encoding::detectEncoding(
86 Env.getSourceManager().getBufferData(Env.getFileID()))) {
88 llvm::dbgs() << "File encoding: "
89 << (Encoding == encoding::Encoding_UTF8 ? "UTF8" : "unknown")
91 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
95 std::pair<tooling::Replacements, unsigned> TokenAnalyzer::process() {
96 tooling::Replacements Result;
97 FormatTokenLexer Tokens(Env.getSourceManager(), Env.getFileID(),
98 Env.getFirstStartColumn(), Style, Encoding);
100 UnwrappedLineParser Parser(Style, Tokens.getKeywords(),
101 Env.getFirstStartColumn(), Tokens.lex(), *this);
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;
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());
115 std::pair<tooling::Replacements, unsigned> RunResult =
116 analyze(Annotator, AnnotatedLines, Tokens);
119 llvm::dbgs() << "Replacements for run " << Run << ":\n";
120 for (tooling::Replacements::const_iterator I = RunResult.first.begin(),
121 E = RunResult.first.end();
123 llvm::dbgs() << I->toString() << "\n";
126 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
127 delete AnnotatedLines[i];
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.
136 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
137 return {tooling::Replacements(), 0};
141 return {Result, Penalty};
144 void TokenAnalyzer::consumeUnwrappedLine(const UnwrappedLine &TheLine) {
145 assert(!UnwrappedLines.empty());
146 UnwrappedLines.back().push_back(TheLine);
149 void TokenAnalyzer::finishRun() {
150 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
153 } // end namespace format
154 } // end namespace clang