]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Format/TokenAnalyzer.cpp
Vendor import of clang trunk r338150:
[FreeBSD/FreeBSD.git] / lib / Format / TokenAnalyzer.cpp
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"
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
34 namespace clang {
35 namespace format {
36
37 Environment::Environment(StringRef Code, StringRef FileName,
38                          ArrayRef<tooling::Range> Ranges,
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
52 TokenAnalyzer::TokenAnalyzer(const Environment &Env, const FormatStyle &Style)
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;
68   FormatTokenLexer Tokens(Env.getSourceManager(), Env.getFileID(),
69                           Env.getFirstStartColumn(), Style, Encoding);
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
115 void TokenAnalyzer::consumeUnwrappedLine(const UnwrappedLine &TheLine) {
116   assert(!UnwrappedLines.empty());
117   UnwrappedLines.back().push_back(TheLine);
118 }
119
120 void TokenAnalyzer::finishRun() {
121   UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
122 }
123
124 } // end namespace format
125 } // end namespace clang