MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
SignatureCollector.cpp
Go to the documentation of this file.
2
4
5namespace {
6
7 constexpr const char* record_id = "record";
8
9 bool is_word(char c)
10 {
11 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
12 }
13
14 std::filesystem::path real_path(llvm::StringRef file)
15 {
16 llvm::SmallString<256> resolved;
17 if (llvm::sys::fs::real_path(file, resolved)) {
18 return { file.str() };
19 }
20 return { resolved.str().str() };
21 }
22
23 std::filesystem::path file_of(const clang::SourceManager& manager, clang::SourceLocation location)
24 {
25 return real_path(manager.getFilename(manager.getExpansionLoc(location)));
26 }
27
28 std::set<std::string> nested_names(const clang::CXXRecordDecl* record)
29 {
30 std::set<std::string> names;
31 for (const clang::Decl* declaration : record->decls()) {
32 if (declaration->isImplicit()) {
33 continue;
34 }
35 const bool type_like = llvm::isa<clang::CXXRecordDecl>(declaration)
36 || llvm::isa<clang::EnumDecl>(declaration)
37 || llvm::isa<clang::TypeAliasDecl>(declaration)
38 || llvm::isa<clang::TypedefDecl>(declaration);
39 if (!type_like) {
40 continue;
41 }
42 const auto* named = llvm::cast<clang::NamedDecl>(declaration);
43 if (named->getIdentifier() != nullptr) {
44 names.insert(named->getName().str());
45 }
46 }
47 return names;
48 }
49
50 std::string relative_to_root(const std::string& spelling)
51 {
52 constexpr std::string_view prefix = "MayaFlux::";
53 std::string out;
54 std::size_t cursor = 0;
55 while (cursor < spelling.size()) {
56 const std::size_t at = spelling.find(prefix, cursor);
57 if (at == std::string::npos) {
58 break;
59 }
60 out.append(spelling, cursor, at - cursor);
61 const bool starts_name = at == 0 || (!is_word(spelling[at - 1]) && spelling[at - 1] != ':');
62 if (!starts_name) {
63 out += prefix;
64 }
65 cursor = at + prefix.size();
66 }
67 out.append(spelling, cursor, std::string::npos);
68 return out;
69 }
70
71 std::string qualify_nested(std::string value, const std::string& owner, const std::set<std::string>& names)
72 {
73 std::vector<std::string> ordered(names.begin(), names.end());
74 std::ranges::sort(ordered, [](const std::string& a, const std::string& b) { return a.size() > b.size(); });
75 for (const std::string& name : ordered) {
76 std::string result;
77 std::size_t cursor = 0;
78 while (cursor < value.size()) {
79 const std::size_t at = value.find(name, cursor);
80 if (at == std::string::npos) {
81 break;
82 }
83 const std::size_t end = at + name.size();
84 const bool before = at == 0 || (!is_word(value[at - 1]) && value[at - 1] != ':');
85 const bool after = end >= value.size() || !is_word(value[end]);
86 result.append(value, cursor, at - cursor);
87 if (before && after) {
88 result += owner + "::" + name;
89 } else {
90 result += name;
91 }
92 cursor = end;
93 }
94 result.append(value, cursor, std::string::npos);
95 value = std::move(result);
96 }
97 return value;
98 }
99
100 std::string spell(clang::QualType type, const clang::ASTContext& context)
101 {
102 const clang::QualType qualified = clang::TypeName::getFullyQualifiedType(type, context, false);
103 return relative_to_root(qualified.getAsString(context.getPrintingPolicy()));
104 }
105
106 /**
107 * Gathers the headers under the source root that declare the MayaFlux types a signature
108 * names, reading the types as written so an alias contributes its own header.
109 */
110 class HeaderCollector {
111 public:
112 HeaderCollector(const clang::SourceManager& manager, std::filesystem::path source_root,
113 const std::set<std::string>& excluded, std::set<std::filesystem::path>& out)
114 : m_manager(manager)
115 , m_source_root(std::move(source_root))
116 , m_excluded(excluded)
117 , m_out(out)
118 {
119 }
120
121 void add_type(clang::QualType type)
122 {
123 type = type.getNonReferenceType();
124 while (!type.isNull() && type->getAs<clang::PointerType>() != nullptr) {
125 type = type->getAs<clang::PointerType>()->getPointeeType();
126 }
127 if (type.isNull()) {
128 return;
129 }
130 type = clang::QualType(type->getBaseElementTypeUnsafe(), 0);
131
132 if (const auto* alias = type->getAs<clang::TypedefType>()) {
133 add_declaration(alias->getDecl());
134 return;
135 }
136 if (const auto* specialization = type->getAs<clang::TemplateSpecializationType>()) {
137 for (const clang::TemplateArgument& argument : specialization->template_arguments()) {
138 if (argument.getKind() == clang::TemplateArgument::Type) {
139 add_type(argument.getAsType());
140 }
141 }
142 return;
143 }
144 if (const auto* function = type->getAs<clang::FunctionProtoType>()) {
145 add_type(function->getReturnType());
146 for (const clang::QualType parameter : function->param_types()) {
147 add_type(parameter);
148 }
149 return;
150 }
151 if (const clang::TagDecl* tag = type->getAsTagDecl()) {
152 add_tag(tag);
153 }
154 }
155
156 void add_value(const clang::ValueDecl* value)
157 {
158 if (const auto* enumerator = llvm::dyn_cast<clang::EnumConstantDecl>(value)) {
159 if (const auto* owner = llvm::dyn_cast<clang::EnumDecl>(enumerator->getDeclContext())) {
160 add_tag(owner);
161 }
162 return;
163 }
164 if (const auto* owner = llvm::dyn_cast<clang::TagDecl>(value->getDeclContext())) {
165 add_tag(owner);
166 }
167 }
168
169 private:
170 void add_tag(const clang::TagDecl* tag)
171 {
172 if (m_excluded.contains(tag->getQualifiedNameAsString())) {
173 return;
174 }
175 add_declaration(tag);
176 }
177
178 void add_declaration(const clang::Decl* declaration)
179 {
180 const std::filesystem::path relative
181 = file_of(m_manager, declaration->getLocation()).lexically_relative(m_source_root);
182 if (relative.empty() || *relative.begin() != "MayaFlux" || relative.extension() != ".hpp") {
183 return;
184 }
185 m_out.insert(relative);
186 }
187
188 const clang::SourceManager& m_manager;
189 std::filesystem::path m_source_root;
190 const std::set<std::string>& m_excluded;
191 std::set<std::filesystem::path>& m_out;
192 };
193
194 /** Visits a default argument and reports the types and enumerators it names. */
195 class DefaultArgumentVisitor : public clang::RecursiveASTVisitor<DefaultArgumentVisitor> {
196 public:
197 explicit DefaultArgumentVisitor(HeaderCollector& headers)
198 : m_headers(headers)
199 {
200 }
201
202 bool VisitExpr(clang::Expr* expression)
203 {
204 m_headers.add_type(expression->getType());
205 return true;
206 }
207
208 bool VisitDeclRefExpr(clang::DeclRefExpr* reference)
209 {
210 m_headers.add_value(reference->getDecl());
211 return true;
212 }
213
214 private:
215 HeaderCollector& m_headers;
216 };
217
218 std::string argument_text(const clang::ParmVarDecl* parameter, const clang::ASTContext& context)
219 {
220 const clang::SourceManager& manager = context.getSourceManager();
221 const clang::CharSourceRange range = manager.getExpansionRange(parameter->getDefaultArg()->getSourceRange());
222 bool invalid = false;
223 const llvm::StringRef text = clang::Lexer::getSourceText(range, manager, context.getLangOpts(), &invalid);
224 std::string spelling = invalid ? std::string {} : text.str();
225 if (spelling.starts_with('=')) {
226 const std::size_t start = spelling.find_first_not_of(" \t", 1);
227 spelling = start == std::string::npos ? std::string {} : spelling.substr(start);
228 }
229 return spelling;
230 }
231
232}
233
234SignatureCollector::SignatureCollector(std::vector<SignatureEntry> entries, std::filesystem::path source_root)
235 : m_entries(std::move(entries))
236 , m_source_root(std::move(source_root))
237 , m_found(m_entries.size())
238{
239 for (const SignatureEntry& entry : m_entries) {
240 m_simple_names.insert(entry.type_name.substr(entry.type_name.rfind("::") + 2));
241 m_excluded.insert(entry.type_name);
242 }
243 m_excluded.insert("MayaFlux::Nodes::Node");
244 m_excluded.insert("MayaFlux::Nodes::Network::NodeNetwork");
245 m_excluded.insert("MayaFlux::Core::VKImage");
246}
247
248void SignatureCollector::attach(clang::ast_matchers::MatchFinder& finder)
249{
250 using namespace clang::ast_matchers;
251 finder.addMatcher(cxxRecordDecl(isDefinition()).bind(record_id), this);
252}
253
254void SignatureCollector::run(const clang::ast_matchers::MatchFinder::MatchResult& result)
255{
256 const auto* record = result.Nodes.getNodeAs<clang::CXXRecordDecl>(record_id);
257 if (record == nullptr || record->getIdentifier() == nullptr || record->isDependentContext()
258 || !m_simple_names.contains(record->getName().str())) {
259 return;
260 }
261
262 const std::string qualified = record->getQualifiedNameAsString();
263 const auto entry = std::ranges::find(m_entries, qualified, &SignatureEntry::type_name);
264 if (entry == m_entries.end()) {
265 return;
266 }
267 std::optional<SignatureClass>& slot = m_found[static_cast<std::size_t>(entry - m_entries.begin())];
268 if (slot) {
269 return;
270 }
271
272 const clang::ASTContext& context = *result.Context;
273 const clang::SourceManager& manager = *result.SourceManager;
274
275 SignatureClass info;
276 info.entry = *entry;
277 info.entry.header = file_of(manager, record->getLocation());
278 info.abstract = record->isAbstract();
279 if (info.abstract) {
280 slot = std::move(info);
281 return;
282 }
283
284 const std::set<std::string> nested = nested_names(record);
285 HeaderCollector headers(manager, m_source_root, m_excluded, info.includes);
286
287 for (const clang::Decl* declaration : record->decls()) {
288 if (const auto* declared_template = llvm::dyn_cast<clang::FunctionTemplateDecl>(declaration)) {
289 if (llvm::isa<clang::CXXConstructorDecl>(declared_template->getTemplatedDecl())) {
290 m_errors.push_back(entry->name + ": constructor template needs explicit generator support");
291 return;
292 }
293 continue;
294 }
295 const auto* constructor = llvm::dyn_cast<clang::CXXConstructorDecl>(declaration);
296 if (constructor == nullptr || constructor->isImplicit() || constructor->isDeleted()
297 || constructor->getAccess() != clang::AS_public) {
298 continue;
299 }
300
302 unsigned number = 0;
303 for (const clang::ParmVarDecl* parameter : constructor->parameters()) {
305 item.type = spell(parameter->getType(), context);
306 if (item.type.find("(*)") != std::string::npos || item.type.find("(&)") != std::string::npos) {
307 m_errors.push_back(entry->name + ": cannot spell parameter " + std::to_string(number)
308 + " as a method parameter");
309 return;
310 }
311 item.name = parameter->getNameAsString();
312 if (item.name.empty()) {
313 item.name = "arg" + std::to_string(number);
314 }
315
316 headers.add_type(parameter->getType());
317 if (parameter->hasDefaultArg() && !parameter->hasUnparsedDefaultArg()
318 && !parameter->hasUninstantiatedDefaultArg()) {
319 const std::string text = argument_text(parameter, context);
320 if (text.empty()) {
321 m_errors.push_back(entry->name + ": cannot recover default for parameter " + std::to_string(number));
322 return;
323 }
324 item.default_value = qualify_nested(text, relative_to_root(qualified), nested);
325 DefaultArgumentVisitor visitor(headers);
326 visitor.TraverseStmt(const_cast<clang::Expr*>(parameter->getDefaultArg()));
327 }
328 built.parameters.push_back(std::move(item));
329 ++number;
330 }
331 info.constructors.push_back(std::move(built));
332 }
333
334 if (info.constructors.empty()) {
335 m_errors.push_back(entry->name + ": no public source-declared constructor found");
336 return;
337 }
338 slot = std::move(info);
339}
340
341std::vector<SignatureClass> SignatureCollector::classes() const
342{
343 std::vector<SignatureClass> found;
344 for (const auto& slot : m_found) {
345 if (slot) {
346 found.push_back(*slot);
347 }
348 }
349 return found;
350}
351
352std::vector<std::string> SignatureCollector::missing() const
353{
354 std::vector<std::string> names;
355 for (std::size_t i = 0; i < m_entries.size(); ++i) {
356 if (!m_found[i]) {
357 names.push_back(m_entries[i].name);
358 }
359 }
360 return names;
361}
362
363}
void run(const clang::ast_matchers::MatchFinder::MatchResult &result) override
std::vector< SignatureClass > classes() const
The registered classes that were found, in registry order.
SignatureCollector(std::vector< SignatureEntry > entries, std::filesystem::path source_root)
std::unordered_set< std::string > m_simple_names
std::vector< std::string > missing() const
Registered classes the scan never reached a definition of.
std::vector< std::optional< SignatureClass > > m_found
void attach(clang::ast_matchers::MatchFinder &finder)
Registers the matcher for class definitions on finder.
std::vector< double > range(std::span< const double > data, size_t n_windows, uint32_t hop_size, uint32_t window_size)
Value range (max - min) per window.
Definition Analysis.cpp:473
auto at(const B &anchor, F &&factory, Args &&... args) -> decltype(std::forward< F >(factory)(Kinesis::bounds_of(anchor), std::forward< Args >(args)...))
Call a bounds-taking factory with an anchor's region.
Definition Geometry.hpp:154
void move(EditableText &s, int n)
Move the cursor by n codepoints.
Definition TextEdit.cpp:113
std::pair< std::shared_ptr< Kriya::BufferPipeline >, std::shared_ptr< Buffers::AudioBuffer > > record(const std::shared_ptr< Kakshya::DynamicSoundStream > &stream, uint32_t input_channel, double seconds, std::optional< uint32_t > monitor, uint32_t channel)
Record a live input channel into a stream for a number of seconds.
Definition Rigs.cpp:262
std::vector< SignatureParameter > parameters
One public constructor a Creator method is generated from.
std::vector< ConstructorSignature > constructors
std::set< std::filesystem::path > includes
A registered class as the scan found it.
One class of the Creator registry: the method name, its qualified type and its header.
One constructor parameter: its fully qualified type, its name and its default argument text.