Repository navigation
Expand file tree
/
Copy pathcppcodebasegenerator.cpp
More file actions
205 lines (159 loc) · 6.24 KB
/
Copy pathcppcodebasegenerator.cpp
File metadata and controls
205 lines (159 loc) · 6.24 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
// SPDX-License-Identifier: Apache-2.0
#include <scratchcpp/project.h>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include "cppcodebasegenerator.h"
#include "cppcodebuilderfactory.h"
#include "cppcompilercontext.h"
#include "../../compiler_p.h"
using namespace libscratchcpp;
namespace
{
// Creates C++ code builders and keeps the compiler contexts to collect the generated code
class RecordingFactory : public ICodeBuilderFactory
{
public:
std::shared_ptr<ICodeBuilder> create(CompilerContext *ctx, BlockPrototype *procedurePrototype, Compiler::CodeType codeType) const override
{
return CppCodeBuilderFactory::instance()->create(ctx, procedurePrototype, codeType);
}
std::shared_ptr<CompilerContext> createCtx(IEngine *engine, Target *target) const override
{
auto ctx = CppCodeBuilderFactory::instance()->createCtx(engine, target);
contexts.push_back(ctx);
return ctx;
}
mutable std::vector<std::shared_ptr<CompilerContext>> contexts;
};
bool writeFile(const std::filesystem::path &path, const std::string &content)
{
std::ofstream file(path, std::ios::binary);
if (!file.is_open()) {
std::cerr << "error: failed to write " << path.string() << std::endl;
return false;
}
file << content;
return true;
}
} // namespace
/*!
* Compiles the given project using the C++ backend and writes a CMake project to outputDir:
* - project.cpp - the generated code of all scripts
* - project_data.cpp - the embedded project file
* - main.cpp - loads and runs the embedded project
* - CMakeLists.txt
*/
bool CppCodebaseGenerator::generate(const std::string &projectFile, const std::string &outputDir, const std::string &projectName)
{
std::ifstream input(projectFile, std::ios::binary);
if (!input.is_open()) {
std::cerr << "error: failed to read " << projectFile << std::endl;
return false;
}
std::stringstream data;
data << input.rdbuf();
RecordingFactory factory;
ICodeBuilderFactory *oldFactory = CompilerPrivate::builderFactory();
CompilerPrivate::setBuilderFactory(&factory);
std::stringstream code;
bool ret;
{
Project project(projectFile);
ret = project.load();
if (ret) {
code << "// Generated by libscratchcpp, do not edit\n\n" << CppCompilerContext::prelude() << "\n";
for (auto ctx : factory.contexts)
code << "\n" << static_cast<CppCompilerContext *>(ctx.get())->moduleSource();
}
}
CompilerPrivate::setBuilderFactory(oldFactory);
if (!ret)
return false;
std::filesystem::path dir(outputDir);
std::error_code err;
std::filesystem::create_directories(dir, err);
return writeFile(dir / "project.cpp", code.str()) && writeFile(dir / "project_data.cpp", dataSource(data.str())) && writeFile(dir / "main.cpp", mainSource()) &&
writeFile(dir / "CMakeLists.txt", cmakeSource(projectName));
}
std::string CppCodebaseGenerator::mainSource()
{
return R"(// Generated by libscratchcpp, do not edit
#include <scratchcpp/project.h>
#include <filesystem>
#include <fstream>
#include <string>
extern const unsigned char scratchcpp_project_data[];
extern const unsigned long long scratchcpp_project_size;
extern "C" void cpp_use_cpp_backend();
int main(int argc, char **argv)
{
// libscratchcpp loads projects from files, so the embedded project is extracted first
std::filesystem::path path = std::filesystem::temp_directory_path() / ("scratchcpp_project_" + std::to_string(std::hash<std::string>()(argv[0])) + ".sb3");
{
std::ofstream file(path, std::ios::binary);
file.write(reinterpret_cast<const char *>(scratchcpp_project_data), scratchcpp_project_size);
}
// Scripts are compiled by the C++ backend which uses the code in project.cpp
cpp_use_cpp_backend();
libscratchcpp::Project project(path.string());
bool loaded = project.load();
std::error_code err;
std::filesystem::remove(path, err);
if (!loaded)
return 1;
project.run();
return 0;
}
)";
}
std::string CppCodebaseGenerator::dataSource(const std::string &data)
{
std::stringstream ss;
ss << "// Generated by libscratchcpp, do not edit\n\n";
ss << "extern const unsigned long long scratchcpp_project_size = " << data.size() << "ULL;\n\n";
ss << "extern const unsigned char scratchcpp_project_data[] = {";
for (size_t i = 0; i < data.size(); i++) {
if (i % 16 == 0)
ss << "\n ";
ss << " 0x" << std::hex << std::setw(2) << std::setfill('0') << (int)(unsigned char)data[i] << ",";
}
ss << std::dec << "\n 0x00\n};\n";
return ss.str();
}
std::string CppCodebaseGenerator::cmakeSource(const std::string &projectName)
{
std::string ret = R"(# Generated by libscratchcpp
cmake_minimum_required(VERSION 3.14)
project(@NAME@ LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Use either libscratchcpp sources (LIBSCRATCHCPP_SOURCE_DIR) or a prebuilt library (LIBSCRATCHCPP_INCLUDE_DIR and LIBSCRATCHCPP_LIBRARY)
set(LIBSCRATCHCPP_SOURCE_DIR "" CACHE PATH "libscratchcpp source directory")
set(LIBSCRATCHCPP_INCLUDE_DIR "" CACHE PATH "libscratchcpp include directory")
set(LIBSCRATCHCPP_LIBRARY "" CACHE FILEPATH "libscratchcpp library")
add_executable(@NAME@ main.cpp project.cpp project_data.cpp)
if(LIBSCRATCHCPP_SOURCE_DIR)
set(LIBSCRATCHCPP_BUILD_UNIT_TESTS OFF CACHE BOOL "" FORCE)
add_subdirectory(${LIBSCRATCHCPP_SOURCE_DIR} libscratchcpp)
target_link_libraries(@NAME@ PRIVATE scratchcpp)
elseif(LIBSCRATCHCPP_INCLUDE_DIR AND LIBSCRATCHCPP_LIBRARY)
target_include_directories(@NAME@ PRIVATE ${LIBSCRATCHCPP_INCLUDE_DIR})
target_link_libraries(@NAME@ PRIVATE ${LIBSCRATCHCPP_LIBRARY})
else()
message(FATAL_ERROR "Set LIBSCRATCHCPP_SOURCE_DIR or LIBSCRATCHCPP_INCLUDE_DIR and LIBSCRATCHCPP_LIBRARY")
endif()
)";
std::string name = projectName;
for (char &c : name) {
if (!std::isalnum((unsigned char)c) && c != '_' && c != '-')
c = '_';
}
size_t pos;
while ((pos = ret.find("@NAME@")) != std::string::npos)
ret.replace(pos, 6, name);
return ret;
}