-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathppmacrocallback.cpp
More file actions
267 lines (216 loc) · 7.62 KB
/
ppmacrocallback.cpp
File metadata and controls
267 lines (216 loc) · 7.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#include <parser/sourcemanager.h>
#include <util/odbtransaction.h>
#include <cppparser/filelocutil.h>
#include "ppmacrocallback.h"
namespace cc
{
namespace parser
{
PPMacroCallback::PPMacroCallback(
ParserContext& ctx_,
clang::ASTContext& astContext_,
EntityCache& entityCache_,
clang::Preprocessor& pp_) :
_ctx(ctx_),
_pp(pp_),
_cppSourceType("CPP"),
_clangSrcMgr(astContext_.getSourceManager()),
_fileLocUtil(astContext_.getSourceManager()),
_entityCache(entityCache_)
{
}
PPMacroCallback::~PPMacroCallback()
{
_ctx.srcMgr.persistFiles();
(util::OdbTransaction(_ctx.db))([this]{
util::persistAll(_astNodes, _ctx.db);
util::persistAll(_macros, _ctx.db);
util::persistAll(_macrosExpansion, _ctx.db);
});
}
void PPMacroCallback::MacroExpands(
const clang::Token& macroNameTok_,
const clang::MacroDefinition& md_,
clang::SourceRange range_,
const clang::MacroArgs*)
{
if (_disabled)
return;
clang::SourceLocation loc = macroNameTok_.getLocation();
if (loc.isInvalid() || !loc.isFileID())
return;
const clang::MacroInfo* mi = md_.getMacroInfo();
if (!mi || getUSR(mi).empty())
return;
const char* begin = _clangSrcMgr.getCharacterData(range_.getBegin());
int len = _clangSrcMgr.getCharacterData(range_.getEnd()) - begin +
clang::Lexer::MeasureTokenLength(
range_.getEnd(), _clangSrcMgr, _pp.getLangOpts());
std::string copy(begin, len);
begin = copy.c_str();
clang::Lexer lex(loc, _pp.getLangOpts(), begin, begin, begin + len);
std::vector<clang::Token> tokens;
// Lex all the tokens in raw mode, to avoid entering #includes or expanding
// macros.
clang::Token tok;
do
{
lex.LexFromRawLexer(tok);
// If this is a # at the start of a line, discard it from the token stream.
// We don't want the re-preprocess step to see #defines, #includes or other
// preprocessor directives.
if (tok.is(clang::tok::hash) && tok.isAtStartOfLine())
continue;
// If this is a ## token, change its kind to unknown so that repreprocessing
// it will not produce an error.
if (tok.is(clang::tok::hashhash))
tok.setKind(clang::tok::unknown);
// If this raw token is an identifier, the raw lexer won't have looked up
// the corresponding identifier info for it. Do this now so that it will be
// macro expanded when we re-preprocess it.
if (tok.is(clang::tok::raw_identifier))
_pp.LookUpIdentifierInfo(tok);
tokens.push_back(tok);
} while (!tok.is(clang::tok::eof));
// Temporarily change the diagnostics object so that we ignore any generated
// diagnostics from this pass.
clang::DiagnosticsEngine TmpDiags(
_pp.getDiagnostics().getDiagnosticIDs(),
&_pp.getDiagnostics().getDiagnosticOptions(),
new clang::IgnoringDiagConsumer);
TmpDiags.setSourceManager(&_clangSrcMgr);
_disabled = true;
clang::DiagnosticsEngine *OldDiags = &_pp.getDiagnostics();
_pp.setDiagnostics(TmpDiags);
_pp.EnterTokenStream(tokens, false, false);
std::string expansion;
_pp.Lex(tok);
while (tok.isNot(clang::tok::eof))
{
// If the tokens were already space separated, or if they must be to avoid
// them being implicitly pasted, add a space between them.
if (tok.hasLeadingSpace())
expansion += ' ';
// Escape any special characters in the token text.
if (!tok.isAnnotation())
// getSpelling calls getLength() on the token, which is not viable if the
// token isAnnotation().
// FIXME: Revise how the preprocessor/lexer of Clang could be improved to
// handle annotation expansions properly, if possible.
expansion += _pp.getSpelling(tok);
else
{
expansion += "/*< FIXME: ";
expansion += tok.getName();
expansion += " token not expanded. >*/";
}
_pp.Lex(tok);
}
_pp.setDiagnostics(*OldDiags);
_disabled = false;
model::CppAstNodePtr astNode = createMacroAstNode(macroNameTok_, mi);
astNode->astType = model::CppAstNode::AstType::Usage;
addFileLoc(astNode, macroNameTok_.getLocation(), macroNameTok_.getLastLoc());
astNode->id = model::createIdentifier(*astNode);
if (_entityCache.insert(*astNode))
{
_astNodes.push_back(astNode);
model::CppMacroExpansionPtr mExp(new model::CppMacroExpansion);
mExp->astNodeId = astNode->id;
mExp->expansion = expansion;
_macrosExpansion.push_back(mExp);
}
}
void PPMacroCallback::MacroDefined(
const clang::Token& macroNameTok_,
const clang::MacroDirective* md_)
{
const clang::MacroInfo* mi = md_->getMacroInfo();
if (!mi || isBuiltInMacro(mi) || getUSR(mi).empty())
return;
model::CppAstNodePtr astNode = createMacroAstNode(macroNameTok_, mi);
astNode->astType = model::CppAstNode::AstType::Definition;
addFileLoc(astNode, mi->getDefinitionLoc(), mi->getDefinitionEndLoc());
astNode->id = model::createIdentifier(*astNode);
if (_entityCache.insert(*astNode))
{
_astNodes.push_back(astNode);
model::CppMacroPtr macro = std::make_shared<model::CppMacro>();
macro->astNodeId = astNode->id;
macro->entityHash = astNode->entityHash;
macro->name = astNode->astValue;
macro->qualifiedName = astNode->astValue;
_macros.push_back(macro);
}
}
void PPMacroCallback::MacroUndefined(
const clang::Token& macroNameTok_,
const clang::MacroDefinition& md_,
const clang::MacroDirective* /*undef_*/)
{
const clang::MacroInfo* mi = md_.getMacroInfo();
if (!mi || isBuiltInMacro(mi) || getUSR(mi).empty())
return;
auto astNode = createMacroAstNode(macroNameTok_, mi);
astNode->astType = model::CppAstNode::AstType::UnDefinition;
addFileLoc(astNode, macroNameTok_.getLocation(), macroNameTok_.getLastLoc());
astNode->id = model::createIdentifier(*astNode);
if (_entityCache.insert(*astNode))
_astNodes.push_back(astNode);
}
model::CppAstNodePtr PPMacroCallback::createMacroAstNode(
const clang::Token& macroNameTok_,
const clang::MacroInfo* mi_)
{
model::CppAstNodePtr astNode(new model::CppAstNode);
astNode->astValue = macroNameTok_.getIdentifierInfo()->getName().str();
astNode->entityHash = util::fnvHash(getUSR(mi_));
astNode->symbolType = model::CppAstNode::SymbolType::Macro;
return astNode;
}
void PPMacroCallback::addFileLoc(
model::CppAstNodePtr& astNode_,
const clang::SourceLocation& start_,
const clang::SourceLocation& end_)
{
if (start_.isInvalid() || end_.isInvalid())
return;
model::FileLoc fileLoc;
_fileLocUtil.setRange(start_, end_, fileLoc.range);
fileLoc.file = _ctx.srcMgr.getFile(_fileLocUtil.getFilePath(start_));
if (fileLoc.file)
{
const std::string& type = fileLoc.file.load()->type;
if (type != model::File::DIRECTORY_TYPE && type != _cppSourceType)
{
fileLoc.file->type = _cppSourceType;
_ctx.srcMgr.updateFile(*fileLoc.file);
}
astNode_->location = fileLoc;
}
}
bool PPMacroCallback::isBuiltInMacro(const clang::MacroInfo* mi_) const
{
clang::PresumedLoc presLoc = _clangSrcMgr.getPresumedLoc(
_clangSrcMgr.getExpansionLoc(mi_->getDefinitionLoc()));
if (presLoc.isInvalid())
return true;
std::string fileName = presLoc.getFilename();
return fileName == "<built-in>" || fileName == "<command line>";
}
std::string PPMacroCallback::getUSR(const clang::MacroInfo* mi_)
{
clang::PresumedLoc presLoc = _clangSrcMgr.getPresumedLoc(
_clangSrcMgr.getExpansionLoc(mi_->getDefinitionLoc()));
if (presLoc.isInvalid())
return std::string();
std::string locStr
= std::to_string(presLoc.getLine()) + ":" +
std::to_string(presLoc.getColumn()) + ":";
return locStr
+ (isBuiltInMacro(mi_)
? presLoc.getFilename()
: std::to_string(_ctx.srcMgr.getFile(presLoc.getFilename())->id));
}
} // parser
} // cc