|
1 | 1 | // SPDX-License-Identifier: Apache-2.0 |
2 | 2 |
|
3 | | -#include <iostream> |
4 | 3 | #include <optional> |
| 4 | +#include <unordered_set> |
5 | 5 |
|
6 | 6 | #include "cppcodegenerator.h" |
7 | 7 | #include "cppassignment.h" |
@@ -43,7 +43,61 @@ CppCodeGenerator::CppCodeGenerator() : |
43 | 43 |
|
44 | 44 | CppCodeGenerator::~CppCodeGenerator() |
45 | 45 | { |
46 | | - std::cout << m_codeStream.code() << std::endl; |
| 46 | +} |
| 47 | + |
| 48 | +std::string CppCodeGenerator::finalize() |
| 49 | +{ |
| 50 | + static unsigned int scriptCount = 0; |
| 51 | + |
| 52 | + const std::string scriptName = "Script" + std::to_string(scriptCount++); |
| 53 | + |
| 54 | + std::ostringstream source; |
| 55 | + source << "#include \"script" + std::to_string(scriptCount++) + ".h\"\n"; |
| 56 | + |
| 57 | + for (Header header : m_includedHeaders) { |
| 58 | + source << "#include " << m_headers.at(header) << "\n"; |
| 59 | + } |
| 60 | + |
| 61 | + source << "\nnamespace libscratchcpp\n{\n\n"; |
| 62 | + source << "void " << scriptName << "::runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists)\n{\n"; |
| 63 | + |
| 64 | + std::unordered_set<const CppIdentifier *> declared; |
| 65 | + const auto declare = [&](const CppIdentifier *identifier) { |
| 66 | + if (!identifier || !identifier->isNamed() || !declared.insert(identifier).second) |
| 67 | + return; |
| 68 | + |
| 69 | + const auto *named = static_cast<const CppNamedIdentifier *>(identifier); |
| 70 | + |
| 71 | + source << " " << identifier->typeString(); |
| 72 | + source << " " << named->name << ";\n"; |
| 73 | + }; |
| 74 | + |
| 75 | + for (const auto &entry : m_identifiers) |
| 76 | + declare(entry.second.get()); |
| 77 | + |
| 78 | + for (const auto &identifier : m_internalIdentifiers) |
| 79 | + declare(identifier.get()); |
| 80 | + |
| 81 | + for (const auto &identifier : m_strings) |
| 82 | + declare(identifier.get()); |
| 83 | + |
| 84 | + if (!m_strings.empty()) { |
| 85 | + for (size_t i = 0; i < m_strings.size(); ++i) |
| 86 | + source << " StringPtr " << m_strings[i]->name << "Storage;\n"; |
| 87 | + |
| 88 | + source << " StringPtr *" << m_stringArray.name << "[" << m_strings.size() << "] = { "; |
| 89 | + |
| 90 | + for (size_t i = 0; i < m_strings.size(); ++i) { |
| 91 | + if (i) |
| 92 | + source << ", "; |
| 93 | + source << "&" << m_strings[i]->name << "Storage"; |
| 94 | + } |
| 95 | + source << " };\n"; |
| 96 | + } |
| 97 | + |
| 98 | + source << m_codeStream.code(); |
| 99 | + source << "}\n\n} // namespace libscratchcpp\n"; |
| 100 | + return source.str(); |
47 | 101 | } |
48 | 102 |
|
49 | 103 | const CppIdentifier *CppCodeGenerator::castValue(CppValue *value, Compiler::StaticType targetType) |
|
0 commit comments