blob: d1dfb1fea32b6344005f64e8fbe9f9c8d1cfa9cf [file] [log] [blame]
Martin Probstc4a0dd42016-05-20 11:24:24 +00001//===--- 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"
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"
31
32#define DEBUG_TYPE "format-formatter"
33
34namespace clang {
35namespace format {
36
37// This sets up an virtual file system with file \p FileName containing \p
38// Code.
39std::unique_ptr<Environment>
40Environment::CreateVirtualEnvironment(StringRef Code, StringRef FileName,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +000041 ArrayRef<tooling::Range> Ranges,
42 unsigned FirstStartColumn,
43 unsigned NextStartColumn,
44 unsigned LastStartColumn) {
Martin Probstc4a0dd42016-05-20 11:24:24 +000045 // This is referenced by `FileMgr` and will be released by `FileMgr` when it
46 // is deleted.
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(
Manuel Klimek89628f62017-09-20 09:51:03 +000063 FileName, 0,
64 llvm::MemoryBuffer::getMemBuffer(Code, FileName,
65 /*RequiresNullTerminator=*/false));
Martin Probstc4a0dd42016-05-20 11:24:24 +000066 FileID ID = VirtualSM->createFileID(FileMgr->getFile(FileName),
67 SourceLocation(), clang::SrcMgr::C_User);
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 }
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +000076 return llvm::make_unique<Environment>(
77 ID, std::move(FileMgr), std::move(VirtualSM), std::move(Diagnostics),
78 CharRanges, FirstStartColumn, NextStartColumn, LastStartColumn);
Martin Probstc4a0dd42016-05-20 11:24:24 +000079}
80
81TokenAnalyzer::TokenAnalyzer(const Environment &Env, const FormatStyle &Style)
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
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +000095std::pair<tooling::Replacements, unsigned> TokenAnalyzer::process() {
Martin Probstc4a0dd42016-05-20 11:24:24 +000096 tooling::Replacements Result;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +000097 FormatTokenLexer Tokens(Env.getSourceManager(), Env.getFileID(),
98 Env.getFirstStartColumn(), Style, Encoding);
Martin Probstc4a0dd42016-05-20 11:24:24 +000099
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000100 UnwrappedLineParser Parser(Style, Tokens.getKeywords(),
101 Env.getFirstStartColumn(), Tokens.lex(), *this);
Martin Probstc4a0dd42016-05-20 11:24:24 +0000102 Parser.parse();
103 assert(UnwrappedLines.rbegin()->empty());
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000104 unsigned Penalty = 0;
Martin Probstc4a0dd42016-05-20 11:24:24 +0000105 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
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000115 std::pair<tooling::Replacements, unsigned> RunResult =
Martin Probsta9855af2016-09-02 14:29:48 +0000116 analyze(Annotator, AnnotatedLines, Tokens);
Martin Probstc4a0dd42016-05-20 11:24:24 +0000117
118 DEBUG({
119 llvm::dbgs() << "Replacements for run " << Run << ":\n";
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000120 for (tooling::Replacements::const_iterator I = RunResult.first.begin(),
121 E = RunResult.first.end();
Martin Probstc4a0dd42016-05-20 11:24:24 +0000122 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 }
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000129
130 Penalty += RunResult.second;
131 for (const auto &R : RunResult.first) {
Eric Liu40ef2fb2016-08-01 10:16:37 +0000132 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";
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000137 return {tooling::Replacements(), 0};
Eric Liu40ef2fb2016-08-01 10:16:37 +0000138 }
139 }
Martin Probstc4a0dd42016-05-20 11:24:24 +0000140 }
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000141 return {Result, Penalty};
Martin Probstc4a0dd42016-05-20 11:24:24 +0000142}
143
144void TokenAnalyzer::consumeUnwrappedLine(const UnwrappedLine &TheLine) {
145 assert(!UnwrappedLines.empty());
146 UnwrappedLines.back().push_back(TheLine);
147}
148
149void TokenAnalyzer::finishRun() {
150 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
151}
152
153} // end namespace format
154} // end namespace clang