-
Notifications
You must be signed in to change notification settings - Fork 27
/
TypesResolver.cpp
283 lines (247 loc) · 11.5 KB
/
TypesResolver.cpp
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#include "TypesResolver.h"
#include "Paths.h"
#include "clang-utils/ASTPrinter.h"
#include "fetchers/Fetcher.h"
#include "fetchers/FetcherUtils.h"
#include "utils/LogUtils.h"
#include <clang/AST/ASTContext.h>
#include "loguru.h"
#include "utils/path/FileSystemPath.h"
#include <vector>
TypesResolver::TypesResolver(const Fetcher *parent) : parent(parent) {
}
static bool canBeReplaced(const std::string &nameInMap, const std::string &name) {
return nameInMap.empty() && !name.empty();
}
template<class Info>
bool isCandidateToReplace(uint64_t id,
std::unordered_map<uint64_t, Info> &someMap,
std::string const &name) {
auto iterator = someMap.find(id);
if (iterator != someMap.end()) {
std::string nameInMap = iterator->second.name;
return canBeReplaced(nameInMap, name);
}
return true;
}
static size_t getRecordSize(const clang::RecordDecl *D) {
return D->getASTContext().getTypeSize(D->getASTContext().getRecordType(D));
}
static size_t getDeclAlignment(const clang::TagDecl *T) {
return T->getASTContext().getTypeAlign(T->getTypeForDecl()) / 8;
}
template<class Info>
static void addInfo(uint64_t id, std::unordered_map<uint64_t, Info> &someMap, Info info) {
auto [iterator, inserted] = someMap.emplace(id, info);
LOG_IF_S(MAX, !inserted) << "Type with id=" << id << " already existed";
if (!inserted) {
std::string nameInMap = iterator->second.name;
if (canBeReplaced(nameInMap, info.name)) {
iterator->second = info;
LOG_S(DEBUG) << "Replace unnamed type with typedef: " << info.name;
} else if (!nameInMap.empty() && info.name.empty()) {
LOG_S(MAX) << "Already replaced with typedef: " << nameInMap;
} else if (nameInMap != info.name) {
LOG_S(WARNING) << "Collision happened between: '" << nameInMap << "' and '" << info.name
<< "'";
}
}
}
std::string TypesResolver::getFullname(const clang::TagDecl *TD, const clang::QualType &canonicalType,
uint64_t id, const fs::path &sourceFilePath) {
auto pp = clang::PrintingPolicy(clang::LangOptions());
pp.SuppressTagKeyword = true;
std::string currentStructName = canonicalType.getNonReferenceType().getUnqualifiedType().getAsString(pp);
fullname.insert(std::make_pair(id, currentStructName));
if (Paths::getSourceLanguage(sourceFilePath) == utbot::Language::C) {
if (const auto *parentNode = llvm::dyn_cast<const clang::RecordDecl>(TD->getLexicalParent())) {
clang::QualType parentCanonicalType = parentNode->getASTContext().getTypeDeclType(parentNode).getCanonicalType();
uint64_t parentID = types::Type::getIdFromCanonicalType(parentCanonicalType);
if (!fullname[parentID].empty()) {
fullname[id] = fullname[parentID] + "::" + fullname[id];
}
}
}
return fullname[id];
}
void TypesResolver::resolveUnion(const clang::RecordDecl *D, const std::string &name) {
resolveStructEx(D, name, types::SubType::Union);
}
void TypesResolver::resolveStruct(const clang::RecordDecl *D, const std::string &name) {
resolveStructEx(D, name, types::SubType::Struct);
}
void TypesResolver::resolveStructEx(const clang::RecordDecl *D, const std::string &name, types::SubType subType) {
clang::ASTContext const &context = D->getASTContext();
clang::SourceManager const &sourceManager = context.getSourceManager();
clang::QualType canonicalType = context.getTypeDeclType(D).getCanonicalType();
uint64_t id = types::Type::getIdFromCanonicalType(canonicalType);
if (!isCandidateToReplace(id, parent->projectTypes->structs, name)) {
return;
}
types::StructInfo structInfo;
fs::path filename =
sourceManager.getFilename(sourceManager.getSpellingLoc(D->getLocation())).str();
fs::path sourceFilePath = sourceManager.getFileEntryForID(
sourceManager.getMainFileID())->tryGetRealPathName().str();
structInfo.filePath = Paths::getCCJsonFileFullPath(filename, parent->buildRootPath);
structInfo.name = getFullname(D, canonicalType, id, sourceFilePath);
structInfo.hasAnonymousStructOrUnion = false;
if (Paths::getSourceLanguage(sourceFilePath) == utbot::Language::CXX) {
const auto *cppD = llvm::dyn_cast<const clang::CXXRecordDecl>(D);
structInfo.isCLike = cppD != nullptr && cppD->isCLike();
}
else {
structInfo.isCLike = true;
}
if (Paths::isGtest(structInfo.filePath)) {
return;
}
std::stringstream ss;
structInfo.definition = ASTPrinter::getSourceText(D->getSourceRange(), sourceManager);
ss << "Struct: " << structInfo.name << "\n"
<< "\tFile path: " << structInfo.filePath.string() << "";
std::vector<types::Field> fields;
structInfo.longestFieldIndexForUnionInit = SIZE_MAX;
size_t i = 0;
size_t maxFieldSize = 0;
for (const clang::FieldDecl *F : D->fields()) {
if (F->isUnnamedBitfield()) {
continue;
}
structInfo.hasAnonymousStructOrUnion |= F->isAnonymousStructOrUnion();
types::Field field;
field.name = F->getNameAsString();
const clang::QualType paramType = F->getType().getCanonicalType();
field.type = types::Type(paramType, paramType.getAsString(), sourceManager);
if (field.type.isPointerToFunction()) {
structInfo.functionFields[field.name] = ParamsHandler::getFunctionPointerDeclaration(
F->getFunctionType(), field.name, sourceManager,
field.type.isArrayOfPointersToFunction());
auto returnType = F->getFunctionType()->getReturnType();
if (returnType->isPointerType() && returnType->getPointeeType()->isStructureType()) {
std::string structName =
returnType->getPointeeType().getBaseTypeIdentifier()->getName().str();
if (!CollectionUtils::containsKey((*parent->structsDeclared).at(sourceFilePath),
structName)) {
(*parent->structsToDeclare)[sourceFilePath].insert(structName);
}
}
} else if (field.type.isArrayOfPointersToFunction()) {
structInfo.functionFields[field.name] = ParamsHandler::getFunctionPointerDeclaration(
F->getType()->getPointeeType()->getPointeeType()->getAs<clang::FunctionType>(),
field.name, sourceManager, field.type.isArrayOfPointersToFunction());
}
field.size = F->isBitField() ? F->getBitWidthValue(context) : context.getTypeSize(F->getType());
field.offset = context.getFieldOffset(F);
if (LogUtils::isMaxVerbosity()) {
ss << "\n\t" << field.type.typeName() << " " << field.name << ";";
}
if (Paths::getSourceLanguage(sourceFilePath) == utbot::Language::CXX) {
switch (F->getAccess()) {
case clang::AccessSpecifier::AS_private :
field.accessSpecifier = types::Field::AS_private;
break;
case clang::AccessSpecifier::AS_protected :
field.accessSpecifier = types::Field::AS_protected;
break;
case clang::AccessSpecifier::AS_public :
field.accessSpecifier = types::Field::AS_pubic;
break;
case clang::AccessSpecifier::AS_none :
field.accessSpecifier = types::Field::AS_none;
break;
}
} else {
field.accessSpecifier = types::Field::AS_pubic;
}
fields.push_back(field);
if (subType == types::SubType::Union && maxFieldSize < field.size) {
structInfo.longestFieldIndexForUnionInit = i;
maxFieldSize = field.size;
}
++i;
}
structInfo.fields = fields;
structInfo.size = getRecordSize(D);
structInfo.alignment = getDeclAlignment(D);
structInfo.subType = subType;
addInfo(id, parent->projectTypes->structs, structInfo);
ss << "\nName: " << structInfo.name << ", id: " << id << " , size: " << structInfo.size << "\n";
updateMaximumAlignment(structInfo.alignment);
LOG_S(DEBUG) << ss.str();
}
static std::optional<std::string> getAccess(const clang::Decl *decl) {
const clang::DeclContext *pContext = decl->getDeclContext();
std::vector<std::string> result;
while (pContext != nullptr) {
if (auto pNamedDecl = llvm::dyn_cast<clang::NamedDecl>(pContext)) {
auto name = pNamedDecl->getNameAsString();
if (!name.empty()) {
result.push_back(name);
}
pContext = pContext->getParent();
} else {
break;
}
}
if (result.empty()) {
return std::nullopt;
}
return StringUtils::joinWith(llvm::reverse(result), "::");
}
void TypesResolver::resolveEnum(const clang::EnumDecl *EN, const std::string &name) {
clang::ASTContext const &context = EN->getASTContext();
clang::SourceManager const &sourceManager = context.getSourceManager();
clang::QualType canonicalType = context.getTypeDeclType(EN).getCanonicalType();
uint64_t id = types::Type::getIdFromCanonicalType(canonicalType);
if (!isCandidateToReplace(id, parent->projectTypes->enums, name)) {
return;
}
types::EnumInfo enumInfo;
fs::path sourceFilePath = sourceManager.getFileEntryForID(sourceManager.getMainFileID())->tryGetRealPathName().str();
enumInfo.name = getFullname(EN, canonicalType, id, sourceFilePath);
enumInfo.filePath = Paths::getCCJsonFileFullPath(
sourceManager.getFilename(EN->getLocation()).str(), parent->buildRootPath.string());
clang::QualType promotionType = EN->getPromotionType();
enumInfo.size = context.getTypeSize(promotionType) / 8;
enumInfo.access = getAccess(EN);
for (auto it = EN->enumerator_begin(); it != EN->enumerator_end(); ++it) {
types::EnumInfo::EnumEntry enumEntry;
std::string entryName = it->getNameAsString();
enumEntry.name = entryName;
enumEntry.value = std::to_string(it->getInitVal().getSExtValue());
enumInfo.valuesToEntries[enumEntry.value] = enumEntry;
enumInfo.namesToEntries[enumEntry.name] = enumEntry;
}
enumInfo.definition = ASTPrinter::getSourceText(EN->getSourceRange(), sourceManager);
enumInfo.alignment = getDeclAlignment(EN);
addInfo(id, parent->projectTypes->enums, enumInfo);
LOG_S(DEBUG) << "\nName: " << enumInfo.name << ", id: " << id << "\n";
updateMaximumAlignment(enumInfo.alignment);
std::stringstream ss;
ss << "EnumInfo: " << enumInfo.name << "\n"
<< "\tFile path: " << enumInfo.filePath.string();
LOG_S(DEBUG) << ss.str();
}
void TypesResolver::updateMaximumAlignment(size_t alignment) const {
size_t &maximumAlignment = *(this->parent->maximumAlignment);
maximumAlignment = std::max(maximumAlignment, alignment);
}
void TypesResolver::resolve(const clang::QualType &type) {
clang::TagDecl *tagDecl = type->getAsTagDecl();
if (tagDecl == nullptr) {
return;
}
std::string name = tagDecl->getNameAsString();
if (auto enumDecl = llvm::dyn_cast<clang::EnumDecl>(tagDecl)) {
resolveEnum(enumDecl, name);
}
if (auto recordDecl = llvm::dyn_cast<clang::RecordDecl>(tagDecl)) {
if (recordDecl->isStruct() || recordDecl->isClass()) {
resolveStruct(recordDecl, name);
}
if (recordDecl->isUnion()) {
resolveUnion(recordDecl, name);
}
}
}