From 209fca409696db2e81c046f1dc5d05f2c35f736e Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:54:28 +0100 Subject: [PATCH 1/3] Print CppCodeGenerator errors Proper error handling will be implemented later. --- src/engine/internal/codegen/cpp/cppcodebuilder.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp index f973fb16..56332c80 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp @@ -48,8 +48,12 @@ std::shared_ptr CppCodeBuilder::build() // Build recorded instructions CppInstruction *ins = m_instructions.first(); - while (ins) - ins = m_instructionBuilder.process(ins); + try { + while (ins) + ins = m_instructionBuilder.process(ins); + } catch (std::exception &e) { + std::cerr << e.what() << std::endl; + } std::cout << m_codeGen.finalize(); From d1c4dae43608a5250ee8456b9715707364056d0f Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:30:08 +0100 Subject: [PATCH 2/3] Implement basic C++ code saving --- include/scratchcpp/compiler.h | 1 + include/scratchcpp/iengine.h | 3 + include/scratchcpp/project.h | 2 + src/engine/compiler.cpp | 11 +++ .../internal/codegen/cpp/CMakeLists.txt | 2 + .../internal/codegen/cpp/cppcodebuilder.cpp | 9 ++- .../internal/codegen/cpp/cppcodebuilder.h | 1 + .../internal/codegen/cpp/cppcodegenerator.cpp | 41 ++++++++-- .../internal/codegen/cpp/cppcodegenerator.h | 8 +- .../internal/codegen/cpp/cppcodesaver.cpp | 81 +++++++++++++++++++ .../internal/codegen/cpp/cppcodesaver.h | 21 +++++ src/engine/internal/codegen/icodebuilder.h | 1 + .../internal/codegen/llvm/llvmcodebuilder.cpp | 7 ++ .../internal/codegen/llvm/llvmcodebuilder.h | 1 + src/engine/internal/engine.cpp | 36 ++++++++- src/engine/internal/engine.h | 2 + src/project.cpp | 7 ++ src/project_p.cpp | 6 ++ src/project_p.h | 1 + test/codegen/cpp/cppcodegenerator_test.cpp | 44 ++++++++++ test/compiler/compiler_test.cpp | 8 ++ test/mocks/codebuildermock.h | 1 + test/mocks/enginemock.h | 1 + test/project/project_test.cpp | 44 ++++++++++ 24 files changed, 327 insertions(+), 12 deletions(-) create mode 100644 src/engine/internal/codegen/cpp/cppcodesaver.cpp create mode 100644 src/engine/internal/codegen/cpp/cppcodesaver.h diff --git a/include/scratchcpp/compiler.h b/include/scratchcpp/compiler.h index a0bbe68f..613003e8 100644 --- a/include/scratchcpp/compiler.h +++ b/include/scratchcpp/compiler.h @@ -61,6 +61,7 @@ class LIBSCRATCHCPP_EXPORT Compiler Block *block() const; std::shared_ptr compile(Block *startBlock, CodeType codeType = CodeType::Script); + void save(const std::string &destination); void preoptimize(); CompilerValue *addFunctionCall(const std::string &functionName, StaticType returnType = StaticType::Void, const ArgTypes &argTypes = {}, const Args &args = {}); diff --git a/include/scratchcpp/iengine.h b/include/scratchcpp/iengine.h index 821615f4..10e89e3f 100644 --- a/include/scratchcpp/iengine.h +++ b/include/scratchcpp/iengine.h @@ -51,6 +51,9 @@ class LIBSCRATCHCPP_EXPORT IEngine */ virtual void compile() = 0; + /*! Saves the compiled project to the given destination directory. */ + virtual void save(const std::string &destination) = 0; + /*! * Calls all "when green flag clicked" blocks. * \note Nothing will happen until the event loop is started. diff --git a/include/scratchcpp/project.h b/include/scratchcpp/project.h index 10a3e365..52b88671 100644 --- a/include/scratchcpp/project.h +++ b/include/scratchcpp/project.h @@ -4,6 +4,7 @@ #include #include +#include #include "spimpl.h" #include "global.h" @@ -29,6 +30,7 @@ class LIBSCRATCHCPP_EXPORT Project Project(const Project &) = delete; bool load(); + void save(const std::string &destination); void stopLoading(); void start(); diff --git a/src/engine/compiler.cpp b/src/engine/compiler.cpp index a1f9ac3b..fd432f64 100644 --- a/src/engine/compiler.cpp +++ b/src/engine/compiler.cpp @@ -125,6 +125,17 @@ std::shared_ptr Compiler::compile(Block *startBlock, CodeType co return impl->builder->build(); } +/*! Saves the generated code to the given destination directory. */ +void Compiler::save(const std::string &destination) +{ + if (!impl->builder) { + std::cerr << "error: cannot save code before compiling it" << std::endl; + return; + } + + impl->builder->save(destination); +} + /*! * Optimizes all compiled scripts before they're called for the first time. * \note Call this only after compiling all scripts. diff --git a/src/engine/internal/codegen/cpp/CMakeLists.txt b/src/engine/internal/codegen/cpp/CMakeLists.txt index 28f7593c..ca97d041 100644 --- a/src/engine/internal/codegen/cpp/CMakeLists.txt +++ b/src/engine/internal/codegen/cpp/CMakeLists.txt @@ -12,6 +12,8 @@ target_sources(scratchcpp cppconstant.h cppcodebuilder.cpp cppcodebuilder.h + cppcodesaver.cpp + cppcodesaver.h cppcodegenerator.cpp cppcodegenerator.h cppcodestream.h diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp index 56332c80..2e3f65c2 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp @@ -3,8 +3,10 @@ #include #include #include +#include #include "cppcodebuilder.h" +#include "cppcodesaver.h" #include "cppcompilercontext.h" #include "cppexecutablecode.h" #include "cppinstruction.h" @@ -55,11 +57,14 @@ std::shared_ptr CppCodeBuilder::build() std::cerr << e.what() << std::endl; } - std::cout << m_codeGen.finalize(); - return std::make_shared(m_ctx); } +void CppCodeBuilder::save(const std::string &destination) +{ + CppCodeSaver::save(m_codeGen, m_ctx, destination); +} + CompilerValue *CppCodeBuilder::addFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) { assert(argTypes.size() == args.size()); diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.h b/src/engine/internal/codegen/cpp/cppcodebuilder.h index 4bd476ea..39a52e1d 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.h +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.h @@ -23,6 +23,7 @@ class CppCodeBuilder : public ICodeBuilder CppCodeBuilder(CppCompilerContext *ctx, BlockPrototype *procedurePrototype = nullptr, Compiler::CodeType codeType = Compiler::CodeType::Script); std::shared_ptr build() override; + void save(const std::string &destination) override; CompilerValue *addFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) override; CompilerValue *addTargetFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) override; diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp index 8871ee2d..cb21c308 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -45,22 +45,20 @@ CppCodeGenerator::~CppCodeGenerator() { } -std::string CppCodeGenerator::finalize() +std::string CppCodeGenerator::finalize(const std::string &headerName) { - static unsigned int scriptCount = 0; - - const std::string scriptNumber = std::to_string(scriptCount++); - const std::string scriptName = "Script" + scriptNumber; + ensureScriptName(); + const std::string generatedHeaderName = headerName.empty() ? m_generatedFileName + ".h" : headerName; std::ostringstream source; - source << "#include \"script" << scriptNumber << ".h\"\n"; + source << "#include \"" << generatedHeaderName << "\"\n"; for (Header header : m_includedHeaders) { source << "#include " << m_headers.at(header) << "\n"; } source << "\nnamespace libscratchcpp\n{\n\n"; - source << scriptName << "::" << scriptName << "(CppCompilerContext *ctx) :\n"; + source << m_scriptName << "::" << m_scriptName << "(CppCompilerContext *ctx) :\n"; source << " CppExecutableCode(ctx, {"; for (size_t i = 0; i < m_objectPointers.size(); ++i) { @@ -92,7 +90,17 @@ std::string CppCodeGenerator::finalize() } source << "})\n{\n}\n\n"; - source << "void " << scriptName << "::runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects)\n{\n"; + source << "void " << m_scriptName << "::runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects)\n{\n"; + + std::ostringstream declaration; + declaration << "namespace libscratchcpp\n{\n\n"; + declaration << "class " << m_scriptName << " : public CppExecutableCode\n{\n"; + declaration << " public:\n"; + declaration << " explicit " << m_scriptName << "(CppCompilerContext *ctx);\n\n"; + declaration << " protected:\n"; + declaration << " void runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects) override;\n"; + declaration << "};\n\n} // namespace libscratchcpp\n"; + m_generatedClassDeclaration = declaration.str(); std::unordered_set declared; const auto declare = [&](const CppIdentifier *identifier) { @@ -136,6 +144,23 @@ std::string CppCodeGenerator::finalize() return source.str(); } +const std::string &CppCodeGenerator::generatedFileName() +{ + ensureScriptName(); + return m_generatedFileName; +} + +void CppCodeGenerator::ensureScriptName() +{ + if (!m_scriptName.empty()) + return; + + static unsigned int scriptCount = 0; + const std::string scriptNumber = std::to_string(scriptCount++); + m_scriptName = "Script" + scriptNumber; + m_generatedFileName = "script" + scriptNumber; +} + const CppIdentifier *CppCodeGenerator::castValue(CppValue *value, Compiler::StaticType targetType) { if (auto *pointerValue = dynamic_cast(value)) diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.h b/src/engine/internal/codegen/cpp/cppcodegenerator.h index b68f0931..d40e6681 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.h +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.h @@ -27,7 +27,9 @@ class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator const CppIdentifier *castValue(CppValue *value, Compiler::StaticType targetType); - std::string finalize(); + std::string finalize(const std::string &headerName = ""); + const std::string &generatedFileName(); + const std::string &generatedClassDeclaration() const { return m_generatedClassDeclaration; } void createCall(const std::string &name, bool ctxArg, bool targetArg, const std::vector &args); void createCall(const std::string &name, CppIdentifier::Type retType, CppValue *retValue, bool ctxArg, bool targetArg, const std::vector &args); @@ -59,6 +61,7 @@ class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator const CppIdentifier *addPointerValue(CppValue *value, const CppObjectPointerDescriptor &descriptor); std::string getNewIdentifierName(const std::string &name); void includeHeader(Header header); + void ensureScriptName(); inline bool identifierExists(CppValue *value) const { return m_identifiers.find(value) != m_identifiers.cend(); } @@ -86,6 +89,9 @@ class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator std::vector> m_internalIdentifiers; std::vector> m_constants; std::vector m_objectPointers; + std::string m_scriptName; + std::string m_generatedFileName; + std::string m_generatedClassDeclaration; CppNamedIdentifier m_stringArray; std::vector> m_strings; diff --git a/src/engine/internal/codegen/cpp/cppcodesaver.cpp b/src/engine/internal/codegen/cpp/cppcodesaver.cpp new file mode 100644 index 00000000..82b150b7 --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppcodesaver.cpp @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include +#include +#include + +#include "cppcodesaver.h" +#include "cppcodegenerator.h" +#include "cppcompilercontext.h" + +using namespace libscratchcpp; + +namespace +{ + +std::mutex outputMutex; + +std::filesystem::path targetOutputDirectory(const std::filesystem::path &root, const CppCompilerContext *ctx) +{ + std::filesystem::path directory = root / "src"; + Target *target = ctx ? ctx->target() : nullptr; + + if (!target || target->isStage()) + return directory / "stage"; + + size_t spriteIndex = 0; + + if (IEngine *engine = ctx->engine()) { + for (const auto &engineTarget : engine->targets()) { + if (engineTarget->isStage()) + continue; + + if (engineTarget.get() == target) + return directory / "sprites" / ("sprite" + std::to_string(spriteIndex)); + + ++spriteIndex; + } + } + + return directory / "sprites" / ("sprite" + std::to_string(spriteIndex)); +} + +} // namespace + +void CppCodeSaver::save(CppCodeGenerator &codeGenerator, CppCompilerContext *ctx, const std::string &destination) +{ + std::lock_guard lock(outputMutex); + + if (destination.empty()) { + std::cerr << "error: C++ output destination cannot be empty" << std::endl; + return; + } + + const std::filesystem::path outputDirectory = targetOutputDirectory(std::filesystem::path(destination), ctx); + const std::string baseName = codeGenerator.generatedFileName(); + const std::filesystem::path sourcePath = outputDirectory / (baseName + ".cpp"); + const std::filesystem::path headerPath = outputDirectory / (baseName + ".h"); + std::error_code error; + std::filesystem::create_directories(outputDirectory, error); + + if (error) { + std::cerr << "error: could not create C++ output directory '" << outputDirectory.string() << "': " << error.message() << std::endl; + return; + } + + std::ofstream sourceFile(sourcePath, std::ios::trunc); + std::ofstream headerFile(headerPath, std::ios::trunc); + + if (!sourceFile || !headerFile) { + std::cerr << "error: could not write generated C++ files for '" << baseName << "'" << std::endl; + return; + } + + headerFile << "#pragma once\n\n#include \"cppexecutablecode.h\"\n\n"; + + sourceFile << codeGenerator.finalize(headerPath.filename().string()); + headerFile << codeGenerator.generatedClassDeclaration() << "\n"; +} diff --git a/src/engine/internal/codegen/cpp/cppcodesaver.h b/src/engine/internal/codegen/cpp/cppcodesaver.h new file mode 100644 index 00000000..4a05b6aa --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppcodesaver.h @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include + +#include "test_export.h" + +namespace libscratchcpp +{ + +class CppCodeGenerator; +class CppCompilerContext; + +class LIBSCRATCHCPP_TEST_EXPORT CppCodeSaver +{ + public: + static void save(CppCodeGenerator &codeGenerator, CppCompilerContext *ctx, const std::string &destination); +}; + +} // namespace libscratchcpp diff --git a/src/engine/internal/codegen/icodebuilder.h b/src/engine/internal/codegen/icodebuilder.h index 72b859da..c4edf346 100644 --- a/src/engine/internal/codegen/icodebuilder.h +++ b/src/engine/internal/codegen/icodebuilder.h @@ -19,6 +19,7 @@ class ICodeBuilder virtual ~ICodeBuilder() { } virtual std::shared_ptr build() = 0; + virtual void save(const std::string &destination) = 0; virtual CompilerValue *addFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) = 0; virtual CompilerValue *addTargetFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) = 0; diff --git a/src/engine/internal/codegen/llvm/llvmcodebuilder.cpp b/src/engine/internal/codegen/llvm/llvmcodebuilder.cpp index ce7c4a84..169c9b4f 100644 --- a/src/engine/internal/codegen/llvm/llvmcodebuilder.cpp +++ b/src/engine/internal/codegen/llvm/llvmcodebuilder.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include #include #include @@ -100,6 +101,12 @@ std::shared_ptr LLVMCodeBuilder::build() return std::make_shared(m_ctx, m_utils.scriptFunctionId(), m_function->getName().str(), m_ctx->coroutineResumeFunction()->getName().str(), m_codeType); } +void LLVMCodeBuilder::save(const std::string &destination) +{ + (void)destination; + std::cerr << "error: saving generated C++ code is not supported by the LLVM backend" << std::endl; +} + CompilerValue *LLVMCodeBuilder::addFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) { assert(argTypes.size() == args.size()); diff --git a/src/engine/internal/codegen/llvm/llvmcodebuilder.h b/src/engine/internal/codegen/llvm/llvmcodebuilder.h index 0f85ae1a..932cd00a 100644 --- a/src/engine/internal/codegen/llvm/llvmcodebuilder.h +++ b/src/engine/internal/codegen/llvm/llvmcodebuilder.h @@ -33,6 +33,7 @@ class LIBSCRATCHCPP_TEST_EXPORT LLVMCodeBuilder : public ICodeBuilder LLVMCodeBuilder(LLVMCompilerContext *ctx, BlockPrototype *procedurePrototype = nullptr, Compiler::CodeType codeType = Compiler::CodeType::Script); std::shared_ptr build() override; + void save(const std::string &destination) override; CompilerValue *addFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) override; CompilerValue *addTargetFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) override; diff --git a/src/engine/internal/engine.cpp b/src/engine/internal/engine.cpp index 9ec5a0dd..2d84bc5b 100644 --- a/src/engine/internal/engine.cpp +++ b/src/engine/internal/engine.cpp @@ -24,6 +24,9 @@ #include #include #include +#ifdef CODEGEN_BACKEND_CPP +#include +#endif #include "engine.h" #include "timer.h" @@ -286,8 +289,15 @@ void Engine::compile() m_scripts[block.get()] = script; script->setCode(compiler.compile(block.get())); - if (block->hatPredicateCompileFunction()) + if (!m_saveDestination.empty()) + compiler.save(m_saveDestination); + + if (block->hatPredicateCompileFunction()) { script->setHatPredicateCode(compiler.compile(block.get(), Compiler::CodeType::HatPredicate)); + + if (!m_saveDestination.empty()) + compiler.save(m_saveDestination); + } } else { std::cout << "warning: unsupported top level block: " << block->opcode() << std::endl; m_unsupportedBlocks.insert(block->opcode()); @@ -312,6 +322,28 @@ void Engine::compile() compileMonitor(monitor); } +void Engine::save(const std::string &destination) +{ + if (destination.empty()) { + std::cerr << "error: output destination cannot be empty" << std::endl; + return; + } + +#ifdef CODEGEN_BACKEND_CPP + std::error_code error; + std::filesystem::remove_all(std::filesystem::path(destination) / "src", error); + + if (error) { + std::cerr << "error: could not clear generated C++ output: " << error.message() << std::endl; + return; + } +#endif + + m_saveDestination = destination; + compile(); + m_saveDestination.clear(); +} + void Engine::start() { stop(); @@ -1828,6 +1860,8 @@ void Engine::compileMonitor(std::shared_ptr monitor) monitor->setScript(script); auto code = compiler.compile(block.get(), Compiler::CodeType::Reporter); script->setCode(code); + if (!m_saveDestination.empty()) + compiler.save(m_saveDestination); m_monitorCompilerContexts[monitor.get()] = ctx; const auto &unsupportedBlocks = compiler.unsupportedBlocks(); diff --git a/src/engine/internal/engine.h b/src/engine/internal/engine.h index 8d10ba7a..0a4715ba 100644 --- a/src/engine/internal/engine.h +++ b/src/engine/internal/engine.h @@ -33,6 +33,7 @@ class LIBSCRATCHCPP_TEST_EXPORT Engine : public IEngine void clear() override; void resolveIds(); void compile() override; + void save(const std::string &destination) override; void start() override; void stop() override; @@ -301,6 +302,7 @@ class LIBSCRATCHCPP_TEST_EXPORT Engine : public IEngine sigslot::signal m_questionAnswered; std::unordered_set m_unsupportedBlocks; + std::string m_saveDestination; }; } // namespace libscratchcpp diff --git a/src/project.cpp b/src/project.cpp index 80bac15b..7dccf761 100644 --- a/src/project.cpp +++ b/src/project.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include #include #include "project_p.h" @@ -29,6 +30,12 @@ bool Project::load() return impl->load(); } +/*! Saves the project as generated C++ source code. */ +void Project::save(const std::string &destination) +{ + impl->save(destination); +} + /*! Cancels project loading if loading in another thread. */ void Project::stopLoading() { diff --git a/src/project_p.cpp b/src/project_p.cpp index 20359165..e46ffd71 100644 --- a/src/project_p.cpp +++ b/src/project_p.cpp @@ -43,6 +43,12 @@ bool ProjectPrivate::load() return false; } +void ProjectPrivate::save(const std::string &destination) +{ + if (engine) + engine->save(destination); +} + bool ProjectPrivate::tryLoad(IProjectReader *reader) { stopLoading = false; diff --git a/src/project_p.h b/src/project_p.h index 1836ec60..f5cda5b8 100644 --- a/src/project_p.h +++ b/src/project_p.h @@ -23,6 +23,7 @@ class LIBSCRATCHCPP_TEST_EXPORT ProjectPrivate ProjectPrivate(const ProjectPrivate &) = delete; bool load(); + void save(const std::string &destination); bool tryLoad(IProjectReader *reader); void loadingAborted(); diff --git a/test/codegen/cpp/cppcodegenerator_test.cpp b/test/codegen/cpp/cppcodegenerator_test.cpp index a6805ac5..90740acb 100644 --- a/test/codegen/cpp/cppcodegenerator_test.cpp +++ b/test/codegen/cpp/cppcodegenerator_test.cpp @@ -1,9 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include +#include +#include #include +#include +#include #include +#include +#include +#include using namespace libscratchcpp; @@ -46,3 +54,39 @@ TEST(CppCodeGeneratorTest, ReporterCanBeConvertedAndBoxedWithoutChangingItsOrigi EXPECT_NE(source.find("value0.type = ValueType::Number;"), std::string::npos) << source; EXPECT_NE(source.find("test_print_unknown(value0)"), std::string::npos) << source; } + +TEST(CppCodeSaverTest, WritesOnePairOfFilesPerScriptInTargetDirectories) +{ + const std::filesystem::path destination = std::filesystem::temp_directory_path() / "libscratchcpp-cpp-code-saver-test"; + std::filesystem::remove_all(destination); + + EngineMock engine; + auto stage = std::make_shared(); + auto sprite0 = std::make_shared(); + auto sprite1 = std::make_shared(); + const std::vector> targets = { stage, sprite0, sprite1 }; + EXPECT_CALL(engine, targets()).WillRepeatedly(testing::ReturnRef(targets)); + + CppCompilerContext stageContext(&engine, stage.get()); + CppCompilerContext sprite0Context(&engine, sprite0.get()); + CppCompilerContext sprite1Context(&engine, sprite1.get()); + CppCodeGenerator stageCode; + CppCodeGenerator sprite0Code; + CppCodeGenerator sprite1Code; + const std::string stageFileName = stageCode.generatedFileName(); + const std::string sprite0FileName = sprite0Code.generatedFileName(); + const std::string sprite1FileName = sprite1Code.generatedFileName(); + + CppCodeSaver::save(stageCode, &stageContext, destination.string()); + CppCodeSaver::save(sprite0Code, &sprite0Context, destination.string()); + CppCodeSaver::save(sprite1Code, &sprite1Context, destination.string()); + + EXPECT_TRUE(std::filesystem::exists(destination / "src/stage" / (stageFileName + ".cpp"))); + EXPECT_TRUE(std::filesystem::exists(destination / "src/stage" / (stageFileName + ".h"))); + EXPECT_TRUE(std::filesystem::exists(destination / "src/sprites/sprite0" / (sprite0FileName + ".cpp"))); + EXPECT_TRUE(std::filesystem::exists(destination / "src/sprites/sprite0" / (sprite0FileName + ".h"))); + EXPECT_TRUE(std::filesystem::exists(destination / "src/sprites/sprite1" / (sprite1FileName + ".cpp"))); + EXPECT_TRUE(std::filesystem::exists(destination / "src/sprites/sprite1" / (sprite1FileName + ".h"))); + + std::filesystem::remove_all(destination); +} diff --git a/test/compiler/compiler_test.cpp b/test/compiler/compiler_test.cpp index c3cfa4b8..139d8753 100644 --- a/test/compiler/compiler_test.cpp +++ b/test/compiler/compiler_test.cpp @@ -71,6 +71,14 @@ TEST_F(CompilerTest, Engine) ASSERT_EQ(m_compiler->engine(), &m_engine); } +TEST_F(CompilerTest, SaveDelegatesToCodeBuilder) +{ + compile(m_compiler.get(), nullptr); + + EXPECT_CALL(*m_builder, save("output-directory")).Times(1); + m_compiler->save("output-directory"); +} + TEST_F(CompilerTest, Target) { ASSERT_EQ(m_compiler->target(), &m_target); diff --git a/test/mocks/codebuildermock.h b/test/mocks/codebuildermock.h index 3c0afdb8..567beff0 100644 --- a/test/mocks/codebuildermock.h +++ b/test/mocks/codebuildermock.h @@ -9,6 +9,7 @@ class CodeBuilderMock : public ICodeBuilder { public: MOCK_METHOD(std::shared_ptr, build, (), (override)); + MOCK_METHOD(void, save, (const std::string &), (override)); MOCK_METHOD(CompilerValue *, addFunctionCall, (const std::string &, Compiler::StaticType, const Compiler::ArgTypes &, const Compiler::Args &), (override)); MOCK_METHOD(CompilerValue *, addTargetFunctionCall, (const std::string &, Compiler::StaticType, const Compiler::ArgTypes &, const Compiler::Args &), (override)); MOCK_METHOD(CompilerValue *, addFunctionCallWithCtx, (const std::string &, Compiler::StaticType, const Compiler::ArgTypes &, const Compiler::Args &), (override)); diff --git a/test/mocks/enginemock.h b/test/mocks/enginemock.h index f7378f51..516ed7ee 100644 --- a/test/mocks/enginemock.h +++ b/test/mocks/enginemock.h @@ -13,6 +13,7 @@ class EngineMock : public IEngine public: MOCK_METHOD(void, clear, (), (override)); MOCK_METHOD(void, compile, (), (override)); + MOCK_METHOD(void, save, (const std::string &), (override)); MOCK_METHOD(void, start, (), (override)); MOCK_METHOD(void, stop, (), (override)); diff --git a/test/project/project_test.cpp b/test/project/project_test.cpp index c2961942..d408ea6b 100644 --- a/test/project/project_test.cpp +++ b/test/project/project_test.cpp @@ -1,7 +1,17 @@ #include +#include +#include +#include +#include #include #include #include +#include +#include +#include +#include +#include +#include #include "project_p.h" #include "../common.h" @@ -73,6 +83,40 @@ TEST_F(ProjectTest, Load) testing::Mock::AllowLeak(m_engine.get()); } +TEST_F(ProjectTest, SaveDelegatesThroughEngineAndCodeBuilder) +{ + Project project; + auto engine = std::dynamic_pointer_cast(project.engine()); + ASSERT_TRUE(engine); + + auto target = std::make_shared(); + auto stage = std::make_shared(); + auto block = std::make_shared("save-script", "save_test"); + target->addBlock(block); + engine->setTargets({ stage, target }); + + ExtensionMock extension; + engine->addCompileFunction(&extension, "save_test", [](Compiler *) -> CompilerValue * { return nullptr; }); + + CodeBuilderFactoryMock builderFactory; + auto stageCompilerContext = std::make_shared(engine.get(), stage.get()); + auto targetCompilerContext = std::make_shared(engine.get(), target.get()); + auto codeBuilder = std::make_shared(); + const std::filesystem::path destination = std::filesystem::temp_directory_path() / "libscratchcpp-project-save-test"; + CompilerPrivate::setBuilderFactory(&builderFactory); + + EXPECT_CALL(builderFactory, createCtx(engine.get(), stage.get(), testing::_)).WillOnce(testing::Return(stageCompilerContext)); + EXPECT_CALL(builderFactory, createCtx(engine.get(), target.get(), testing::_)).WillOnce(testing::Return(targetCompilerContext)); + EXPECT_CALL(builderFactory, create(targetCompilerContext.get(), nullptr, Compiler::CodeType::Script)).WillOnce(testing::Return(codeBuilder)); + EXPECT_CALL(*codeBuilder, build()).WillOnce(testing::Return(std::shared_ptr())); + EXPECT_CALL(*codeBuilder, save(destination.string())).Times(1); + + project.save(destination.string()); + + CompilerPrivate::setBuilderFactory(nullptr); + std::filesystem::remove_all(destination); +} + TEST_F(ProjectTest, Start) { ProjectPrivate p("default_project.sb3"); From 6511fd75d601784886d8f070ed8c5b7621ef7fd5 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:41:45 +0100 Subject: [PATCH 3/3] Generate C++ code for tests --- .../internal/codegen/cpp/cppcodebuilder.cpp | 66 +++++ .../internal/codegen/cpp/cppcodebuilder.h | 2 + .../internal/codegen/cpp/cppcodegenerator.cpp | 238 +++++++++++++++++- .../internal/codegen/cpp/cppcodegenerator.h | 15 +- .../codegen/cpp/cppcompilercontext.cpp | 41 +++ .../internal/codegen/cpp/cppcompilercontext.h | 25 ++ src/engine/internal/codegen/cpp/cppswitch.h | 6 + test/blocks/util.cpp | 2 + test/codegen/CMakeLists.txt | 95 ++++++- test/codegen/codebuilder_test.cpp | 11 + test/codegen/cpp/cppcodegenerator_test.cpp | 48 +++- test/codegen/cpp/testcodegenlistener.h | 35 +++ test/codegen/cpp/testscriptgenerator.cpp | 147 +++++++++++ test/codegen/main.cpp | 20 ++ test/codegen/testfunctions.h | 2 + test/common.h | 4 +- 16 files changed, 738 insertions(+), 19 deletions(-) create mode 100644 test/codegen/cpp/testcodegenlistener.h create mode 100644 test/codegen/cpp/testscriptgenerator.cpp diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp index 2e3f65c2..afd97c3d 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp @@ -4,6 +4,10 @@ #include #include #include +#include +#include +#include +#include #include "cppcodebuilder.h" #include "cppcodesaver.h" @@ -17,6 +21,7 @@ using namespace libscratchcpp; CppCodeBuilder::CppCodeBuilder(CppCompilerContext *ctx, BlockPrototype *procedurePrototype, Compiler::CodeType codeType) : m_ctx(ctx), + m_testCodeId(ctx->testCodeId().empty() ? CppCompilerContext::nextTestCodeId() : ctx->testCodeId()), m_procedurePrototype(procedurePrototype), m_codeType(codeType), m_instructionBuilder(m_codeGen), @@ -26,6 +31,13 @@ CppCodeBuilder::CppCodeBuilder(CppCompilerContext *ctx, BlockPrototype *procedur std::shared_ptr CppCodeBuilder::build() { + if (m_ctx->generatedCodeFactory()) { + if (auto generatedCode = m_ctx->generatedCodeFactory()(m_testCodeId, m_ctx)) + return generatedCode; + + throw std::runtime_error("No generated C++ test script for '" + m_testCodeId + "'"); + } + if (!m_warp) { // Do not create coroutine if there are no yield instructions nor non-warp procedure calls if (!m_instructions.containsInstruction([](const CppInstruction *ins) { @@ -57,11 +69,64 @@ std::shared_ptr CppCodeBuilder::build() std::cerr << e.what() << std::endl; } + CppInstruction *lastInstruction = m_instructions.last(); + CppValue *returnValue = lastInstruction ? lastInstruction->getFunctionReturnReg() : m_lastConstValue; + + if (returnValue && !returnValue->isConst() && !m_codeGen.hasIdentifier(returnValue)) + returnValue = nullptr; + + m_codeGen.setCodeType(m_codeType, returnValue); + + if (!m_testCodeId.empty() && !CppCompilerContext::testGenerationDirectory().empty()) { + std::string suffix; + + for (unsigned char character : m_testCodeId) + suffix += std::isalnum(character) ? static_cast(character) : '_'; + + const std::string uniqueSuffix = suffix + "_" + std::to_string(std::hash{}(m_testCodeId)); + const std::string className = "Script_" + uniqueSuffix; + const std::string fileName = "script_" + uniqueSuffix; + m_codeGen.setGeneratedName(className, fileName); + + try { + const std::filesystem::path destination = CppCompilerContext::testGenerationDirectory(); + CppCodeSaver::save(m_codeGen, m_ctx, destination.string()); + + const std::string sourceFileName = fileName + ".cpp"; + std::filesystem::path generatedSource; + + for (const auto &file : std::filesystem::recursive_directory_iterator(destination)) { + if (file.path().filename() == sourceFileName) { + generatedSource = file.path(); + break; + } + } + + if (generatedSource.empty()) + throw std::runtime_error("generated test source file was not written"); + + std::ofstream manifest(destination / "test_scripts.txt", std::ios::app); + manifest.exceptions(std::ios::failbit | std::ios::badbit); + manifest << m_testCodeId << '\t' << className << '\t' + << std::filesystem::relative(generatedSource, destination).generic_string() << '\n'; + manifest.close(); + } catch (const std::exception &e) { + throw std::runtime_error("Could not generate C++ test script '" + m_testCodeId + "': " + e.what()); + } + } + return std::make_shared(m_ctx); } void CppCodeBuilder::save(const std::string &destination) { + CppInstruction *lastInstruction = m_instructions.last(); + CppValue *returnValue = lastInstruction ? lastInstruction->getFunctionReturnReg() : m_lastConstValue; + + if (returnValue && !returnValue->isConst() && !m_codeGen.hasIdentifier(returnValue)) + returnValue = nullptr; + + m_codeGen.setCodeType(m_codeType, returnValue); CppCodeSaver::save(m_codeGen, m_ctx, destination); } @@ -108,6 +173,7 @@ CompilerConstant *CppCodeBuilder::addConstValue(const Value &value) { auto constValue = std::make_shared(TypeUtils::mapType(value.type()), value); auto genericValue = std::static_pointer_cast(constValue); + m_lastConstValue = genericValue.get(); return static_cast(static_cast(addValue(genericValue, nullptr))); } diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.h b/src/engine/internal/codegen/cpp/cppcodebuilder.h index 39a52e1d..9cf8c1f6 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.h +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.h @@ -128,10 +128,12 @@ class CppCodeBuilder : public ICodeBuilder CppValue *createOp(const CppInstruction &ins, Compiler::StaticType retType, const Compiler::ArgTypes &argTypes = {}, const Compiler::Args &args = {}); CppCompilerContext *m_ctx = nullptr; + std::string m_testCodeId; BlockPrototype *m_procedurePrototype = nullptr; Compiler::CodeType m_codeType = Compiler::CodeType::Script; std::vector> m_values; + CppValue *m_lastConstValue = nullptr; std::vector> m_localVars; CppInstructionList m_instructions; CppCodeGenerator m_codeGen; diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp index cb21c308..f3aecbe9 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -24,9 +24,11 @@ const std::unordered_map CppCodeGener const std::unordered_map CppCodeGenerator::m_headers = { { Header::Limits, "" }, { Header::Value, "" }, + { Header::StringPtr, "" }, { Header::ValueData, "" }, { Header::ValueFunctions, "" }, - { Header::ExecutionContext, "" } + { Header::ExecutionContext, "" }, + { Header::Target, "" } }; const std::unordered_map CppCodeGenerator::m_funcParams = { @@ -45,10 +47,40 @@ CppCodeGenerator::~CppCodeGenerator() { } +CppIdentifier::Type CppCodeGenerator::getType(Compiler::StaticType type) const +{ + return m_valueTypeMap.at(TypeUtils::isSingleType(type) ? type : Compiler::StaticType::Unknown); +} + std::string CppCodeGenerator::finalize(const std::string &headerName) { ensureScriptName(); const std::string generatedHeaderName = headerName.empty() ? m_generatedFileName + ".h" : headerName; + const CppIdentifier *returnIdentifier = nullptr; + + if (m_returnValue) { + switch (m_codeType) { + case Compiler::CodeType::Reporter: + returnIdentifier = castValue(m_returnValue, Compiler::StaticType::Unknown); + break; + + case Compiler::CodeType::HatPredicate: + returnIdentifier = castValue(m_returnValue, Compiler::StaticType::Bool); + break; + + case Compiler::CodeType::Script: + break; + } + } + + if (!m_strings.empty()) + includeHeader(Header::StringPtr); + + if (m_codeType == Compiler::CodeType::Reporter) + includeHeader(Header::ValueData); + + if (m_codeType == Compiler::CodeType::Reporter && returnIdentifier) + includeHeader(Header::ValueFunctions); std::ostringstream source; source << "#include \"" << generatedHeaderName << "\"\n"; @@ -58,6 +90,13 @@ std::string CppCodeGenerator::finalize(const std::string &headerName) } source << "\nnamespace libscratchcpp\n{\n\n"; + + for (const auto &entry : m_functionDeclarations) + source << "extern \"C\" " << entry.second << "\n"; + + if (!m_functionDeclarations.empty()) + source << "\n"; + source << m_scriptName << "::" << m_scriptName << "(CppCompilerContext *ctx) :\n"; source << " CppExecutableCode(ctx, {"; @@ -90,7 +129,18 @@ std::string CppCodeGenerator::finalize(const std::string &headerName) } source << "})\n{\n}\n\n"; - source << "void " << m_scriptName << "::runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects)\n{\n"; + const char *methodName = "runScript"; + const char *returnType = "void"; + + if (m_codeType == Compiler::CodeType::Reporter) { + methodName = "runReporter"; + returnType = "ValueData"; + } else if (m_codeType == Compiler::CodeType::HatPredicate) { + methodName = "runPredicate"; + returnType = "bool"; + } + + source << returnType << " " << m_scriptName << "::" << methodName << "(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects)\n{\n"; std::ostringstream declaration; declaration << "namespace libscratchcpp\n{\n\n"; @@ -98,7 +148,7 @@ std::string CppCodeGenerator::finalize(const std::string &headerName) declaration << " public:\n"; declaration << " explicit " << m_scriptName << "(CppCompilerContext *ctx);\n\n"; declaration << " protected:\n"; - declaration << " void runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects) override;\n"; + declaration << " " << returnType << " " << methodName << "(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects) override;\n"; declaration << "};\n\n} // namespace libscratchcpp\n"; m_generatedClassDeclaration = declaration.str(); @@ -140,10 +190,43 @@ std::string CppCodeGenerator::finalize(const std::string &headerName) } source << m_codeStream.code(); + + if (m_codeType == Compiler::CodeType::Reporter) { + if (returnIdentifier) { + source << " ValueData returnValue{};\n"; + source << " value_assign_copy(&returnValue, &" << static_cast(returnIdentifier)->name << ");\n"; + source << " return returnValue;\n"; + } else + source << " return ValueData();\n"; + } else if (m_codeType == Compiler::CodeType::HatPredicate) { + source << " return "; + + if (!returnIdentifier) + source << "false"; + else if (returnIdentifier->isConst()) + source << toCppConstant(static_cast(returnIdentifier)->value); + else + source << static_cast(returnIdentifier)->name; + + source << ";\n"; + } + source << "}\n\n} // namespace libscratchcpp\n"; return source.str(); } +void CppCodeGenerator::setCodeType(Compiler::CodeType codeType, CppValue *returnValue) +{ + m_codeType = codeType; + m_returnValue = returnValue; +} + +void CppCodeGenerator::setGeneratedName(const std::string &className, const std::string &fileName) +{ + m_scriptName = className; + m_generatedFileName = fileName; +} + const std::string &CppCodeGenerator::generatedFileName() { ensureScriptName(); @@ -242,7 +325,7 @@ const CppIdentifier *CppCodeGenerator::castValue(CppValue *value, Compiler::Stat m_codeStream.beginLine(); CppAssignment boolAssignment(m_codeStream, result); - m_codeStream.addToLine("value_boolToStringPtr(" + source->name + ".boolValue)"); + m_codeStream.addToLine("const_cast(value_boolToStringPtr(" + source->name + ".boolValue))"); boolAssignment.close(); m_codeStream.endLine(); m_codeStream.beginLine(); @@ -287,13 +370,19 @@ const CppIdentifier *CppCodeGenerator::addPointerValue(CppValue *value, const Cp void CppCodeGenerator::createCall(const std::string &name, bool ctxArg, bool targetArg, const std::vector &args) { + const auto preparedArgs = prepareCallArgs(name, args); + addFunctionDeclaration(name, CppIdentifier::Type::Pointer, false, true, ctxArg, targetArg, preparedArgs); m_codeStream.beginLine(); - createCall(name, nullptr, ctxArg, targetArg, args); + createCall(name, nullptr, ctxArg, targetArg, preparedArgs); + m_codeStream.addToLine(";"); m_codeStream.endLine(); } void CppCodeGenerator::createCall(const std::string &name, CppIdentifier::Type retType, CppValue *retValue, bool ctxArg, bool targetArg, const std::vector &args) { + if (retType == CppIdentifier::Type::ValueData) + includeHeader(Header::ValueData); + if (identifierExists(retValue)) { throw std::runtime_error("assigning to existing return value identifier when calling function: " + name); } @@ -309,6 +398,9 @@ void CppCodeGenerator::createCall(const std::string &name, CppIdentifier::Type r m_identifiers[retValue] = m_strings.back(); } + const auto preparedArgs = prepareCallArgs(name, args); + addFunctionDeclaration(name, retType, retType == CppIdentifier::Type::StringPtr, false, ctxArg, targetArg, preparedArgs); + m_codeStream.beginLine(); std::unique_ptr strAssignment; @@ -317,10 +409,12 @@ void CppCodeGenerator::createCall(const std::string &name, CppIdentifier::Type r strAssignment = std::make_unique(m_codeStream, getNamedIdentifier(retValue, retType, "ret", true)); } - createCall(name, strRet, ctxArg, targetArg, args); + createCall(name, strRet, ctxArg, targetArg, preparedArgs); if (strAssignment) strAssignment->close(); + else + m_codeStream.addToLine(";"); m_codeStream.endLine(); } @@ -340,13 +434,18 @@ void CppCodeGenerator::createCall(const std::string &name, const CppNamedIdentif for (const CppIdentifier *arg : args) { try { - if (arg->isConst()) { + if (arg->isConst()) call.param(toCppConstant(static_cast(arg)->value)); - } else if (arg->isNamed()) { - call.param(static_cast(arg)); - } else { - throw std::runtime_error("unsupported identifier when calling function: " + name); + else if (arg->isNamed()) { + const auto *named = static_cast(arg); + + if (named->type == CppIdentifier::Type::ValueData) + call.param("&" + named->name); + else + call.param(named); } + else + throw std::runtime_error("unsupported identifier when calling function: " + name); } catch (std::exception &e) { throw std::runtime_error("error when creating call of function '" + name + "': " + e.what()); } @@ -355,6 +454,121 @@ void CppCodeGenerator::createCall(const std::string &name, const CppNamedIdentif call.close(); } +std::vector CppCodeGenerator::prepareCallArgs(const std::string &name, const std::vector &args) +{ + std::vector preparedArgs; + preparedArgs.reserve(args.size()); + + for (const CppIdentifier *arg : args) { + try { + if (!arg->isConst()) { + preparedArgs.push_back(arg); + continue; + } + + const auto *constant = static_cast(arg); + + if (constant->type != CppIdentifier::Type::StringPtr) { + preparedArgs.push_back(arg); + continue; + } + + includeHeader(Header::Value); + includeHeader(Header::ValueFunctions); + const CppNamedIdentifier *value = createNamedIdentifier(CppIdentifier::Type::Value, "constant", true); + const CppNamedIdentifier *string = addStringAlloca(); + + m_codeStream.beginLine(); + CppAssignment valueAssignment(m_codeStream, value); + m_codeStream.addToLine("Value(" + toCppConstant(constant->value) + ")"); + valueAssignment.close(); + m_codeStream.endLine(); + + m_codeStream.beginLine(); + CppFunctionCall stringCall(m_codeStream, "value_toStringPtr"); + stringCall.param("&" + value->name + ".data()").param(string->name); + stringCall.close(); + m_codeStream.addToLine(";"); + m_codeStream.endLine(); + preparedArgs.push_back(string); + } catch (std::exception &e) { + throw std::runtime_error("error when creating call of function '" + name + "': " + e.what()); + } + } + + return preparedArgs; +} + +void CppCodeGenerator::addFunctionDeclaration(const std::string &name, CppIdentifier::Type returnType, bool stringReturn, bool voidReturn, bool ctxArg, bool targetArg, const std::vector &args) +{ + // Test helper declarations are provided by their test support headers. + if (name.rfind("test_", 0) == 0) + return; + + const auto typeName = [&name](CppIdentifier::Type type, bool argument) { + switch (type) { + case CppIdentifier::Type::Double: + return std::string("double"); + case CppIdentifier::Type::Bool: + return std::string("bool"); + case CppIdentifier::Type::StringPtr: + return argument ? std::string("const StringPtr *") : std::string("StringPtr *"); + case CppIdentifier::Type::Pointer: + return argument ? std::string("const void *") : std::string("void *"); + case CppIdentifier::Type::ValueData: + return argument ? std::string("const ValueData *") : std::string("ValueData"); + case CppIdentifier::Type::ContextPointer: + return std::string("ExecutionContext *"); + case CppIdentifier::Type::TargetPointer: + return std::string("Target *"); + default: + throw std::runtime_error("unsupported function parameter type when declaring '" + name + "'"); + } + }; + + std::vector parameterTypes; + + if (stringReturn) { + includeHeader(Header::StringPtr); + parameterTypes.emplace_back("StringPtr *"); + } + + if (ctxArg) { + includeHeader(Header::ExecutionContext); + parameterTypes.emplace_back("ExecutionContext *"); + } + + if (targetArg) { + includeHeader(Header::Target); + parameterTypes.emplace_back("Target *"); + } + + for (const CppIdentifier *arg : args) { + if (arg->type == CppIdentifier::Type::StringPtr) + includeHeader(Header::StringPtr); + else if (arg->type == CppIdentifier::Type::ValueData) + includeHeader(Header::ValueData); + else if (arg->type == CppIdentifier::Type::ContextPointer) + includeHeader(Header::ExecutionContext); + else if (arg->type == CppIdentifier::Type::TargetPointer) + includeHeader(Header::Target); + + parameterTypes.push_back(typeName(arg->type, true)); + } + + std::string declaration = stringReturn || voidReturn ? "void" : typeName(returnType, false); + declaration += " " + name + "("; + + for (size_t i = 0; i < parameterTypes.size(); ++i) { + if (i) + declaration += ", "; + declaration += parameterTypes[i]; + } + + declaration += ");"; + m_functionDeclarations.emplace(name, std::move(declaration)); +} + const CppNamedIdentifier *CppCodeGenerator::getParam(FuncParam param) { return &m_funcParams.at(param); @@ -515,7 +729,7 @@ const CppNamedIdentifier *CppCodeGenerator::castRawValue(CppValue *value, Compil expression = string->name; } else if (value->type() == Compiler::StaticType::Bool) { - expression = "value_boolToStringPtr(" + source->name + ")"; + expression = "const_cast(value_boolToStringPtr(" + source->name + "))"; } } diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.h b/src/engine/internal/codegen/cpp/cppcodegenerator.h index d40e6681..5d147c13 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.h +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.h @@ -23,10 +23,14 @@ class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator CppCodeGenerator(); ~CppCodeGenerator(); - inline CppIdentifier::Type getType(Compiler::StaticType type) const { return m_valueTypeMap.at(type); } + CppIdentifier::Type getType(Compiler::StaticType type) const; const CppIdentifier *castValue(CppValue *value, Compiler::StaticType targetType); + void setCodeType(Compiler::CodeType codeType, CppValue *returnValue = nullptr); + void setGeneratedName(const std::string &className, const std::string &fileName); + bool hasIdentifier(CppValue *value) const { return m_identifiers.find(value) != m_identifiers.cend(); } + std::string finalize(const std::string &headerName = ""); const std::string &generatedFileName(); const std::string &generatedClassDeclaration() const { return m_generatedClassDeclaration; } @@ -39,9 +43,11 @@ class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator { Limits, Value, + StringPtr, ValueData, ValueFunctions, - ExecutionContext + ExecutionContext, + Target }; enum class FuncParam @@ -53,6 +59,8 @@ class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator }; void createCall(const std::string &name, const CppNamedIdentifier *strRet, bool ctxArg, bool targetArg, const std::vector &args); + std::vector prepareCallArgs(const std::string &name, const std::vector &args); + void addFunctionDeclaration(const std::string &name, CppIdentifier::Type returnType, bool stringReturn, bool voidReturn, bool ctxArg, bool targetArg, const std::vector &args); const CppNamedIdentifier *getParam(FuncParam param); const CppIdentifier *getIdentifier(CppValue *value); @@ -83,6 +91,7 @@ class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator CppCodeStream m_codeStream; std::unordered_map> m_identifiers; + std::unordered_map m_functionDeclarations; std::unordered_map m_valueDataIdentifiers; std::unordered_map m_identifierNameCounts; std::unordered_set
m_includedHeaders; @@ -92,6 +101,8 @@ class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator std::string m_scriptName; std::string m_generatedFileName; std::string m_generatedClassDeclaration; + Compiler::CodeType m_codeType = Compiler::CodeType::Script; + CppValue *m_returnValue = nullptr; CppNamedIdentifier m_stringArray; std::vector> m_strings; diff --git a/src/engine/internal/codegen/cpp/cppcompilercontext.cpp b/src/engine/internal/codegen/cpp/cppcompilercontext.cpp index 5837fa65..87450aa8 100644 --- a/src/engine/internal/codegen/cpp/cppcompilercontext.cpp +++ b/src/engine/internal/codegen/cpp/cppcompilercontext.cpp @@ -2,9 +2,50 @@ #include "cppcompilercontext.h" +#include + using namespace libscratchcpp; +namespace +{ + +CppCompilerContext::GeneratedCodeFactory defaultGeneratedCodeFactory; +CppCompilerContext::TestCodeIdProvider testCodeIdProvider; +std::string testGenerationDirectory; + +} // namespace + CppCompilerContext::CppCompilerContext(IEngine *engine, Target *target, const std::unordered_set &unsafeConstants) : CompilerContext(engine, target, unsafeConstants) { } + +const CppCompilerContext::GeneratedCodeFactory &CppCompilerContext::generatedCodeFactory() const +{ + return m_generatedCodeFactory ? m_generatedCodeFactory : defaultGeneratedCodeFactory; +} + +void CppCompilerContext::setDefaultGeneratedCodeFactory(GeneratedCodeFactory factory) +{ + defaultGeneratedCodeFactory = std::move(factory); +} + +void CppCompilerContext::setTestCodeIdProvider(TestCodeIdProvider provider) +{ + testCodeIdProvider = std::move(provider); +} + +std::string CppCompilerContext::nextTestCodeId() +{ + return testCodeIdProvider ? testCodeIdProvider() : std::string(); +} + +void CppCompilerContext::setTestGenerationDirectory(const std::string &directory) +{ + ::testGenerationDirectory = directory; +} + +const std::string &CppCompilerContext::testGenerationDirectory() +{ + return ::testGenerationDirectory; +} diff --git a/src/engine/internal/codegen/cpp/cppcompilercontext.h b/src/engine/internal/codegen/cpp/cppcompilercontext.h index 15b62cd8..c7584f86 100644 --- a/src/engine/internal/codegen/cpp/cppcompilercontext.h +++ b/src/engine/internal/codegen/cpp/cppcompilercontext.h @@ -4,15 +4,40 @@ #include +#include +#include +#include +#include + #include "test_export.h" namespace libscratchcpp { +class ExecutableCode; + class LIBSCRATCHCPP_TEST_EXPORT CppCompilerContext : public CompilerContext { public: + using GeneratedCodeFactory = std::function(const std::string &, CppCompilerContext *)>; + using TestCodeIdProvider = std::function; + CppCompilerContext(IEngine *engine, Target *target, const std::unordered_set &unsafeConstants = {}); + + void setTestCodeId(const std::string &id) { m_testCodeId = id; } + const std::string &testCodeId() const { return m_testCodeId; } + void setGeneratedCodeFactory(GeneratedCodeFactory factory) { m_generatedCodeFactory = std::move(factory); } + const GeneratedCodeFactory &generatedCodeFactory() const; + + static void setDefaultGeneratedCodeFactory(GeneratedCodeFactory factory); + static void setTestCodeIdProvider(TestCodeIdProvider provider); + static std::string nextTestCodeId(); + static void setTestGenerationDirectory(const std::string &directory); + static const std::string &testGenerationDirectory(); + + private: + std::string m_testCodeId; + GeneratedCodeFactory m_generatedCodeFactory; }; } // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/cppswitch.h b/src/engine/internal/codegen/cpp/cppswitch.h index d0411e0a..8c1c0378 100644 --- a/src/engine/internal/codegen/cpp/cppswitch.h +++ b/src/engine/internal/codegen/cpp/cppswitch.h @@ -18,6 +18,7 @@ class CppSwitch m_out.addToLine("switch ("); m_out.addToLine(identifier->name); m_out.addToLine(") {"); + m_out.endLine(); m_out.indent(); } @@ -42,6 +43,7 @@ class CppSwitch m_out.addToLine("case "); m_out.addToLine(value); m_out.addToLine(":"); + m_out.endLine(); m_out.indent(); @@ -57,6 +59,7 @@ class CppSwitch m_out.beginLine(); m_out.addToLine("default:"); + m_out.endLine(); m_out.indent(); return *this; @@ -69,6 +72,9 @@ class CppSwitch m_closed = true; m_out.dedent(); + m_out.beginLine(); + m_out.addToLine("}"); + m_out.endLine(); } private: diff --git a/test/blocks/util.cpp b/test/blocks/util.cpp index 0de19290..f8064e8d 100644 --- a/test/blocks/util.cpp +++ b/test/blocks/util.cpp @@ -68,9 +68,11 @@ extern "C" bool test_condition() return conditionReturnValue; } +#if !defined(LIBSCRATCHCPP_CPP_TEST_GENERATOR) && !defined(LIBSCRATCHCPP_CPP_TEST_GENERATED_CODE) extern "C" void test_const_string(StringPtr *ret, const StringPtr *str) { string_assign(ret, str); } +#endif } // namespace libscratchcpp diff --git a/test/codegen/CMakeLists.txt b/test/codegen/CMakeLists.txt index 26ddb465..b6327d52 100644 --- a/test/codegen/CMakeLists.txt +++ b/test/codegen/CMakeLists.txt @@ -1,5 +1,12 @@ +if (LIBSCRATCHCPP_CODEGEN_BACKEND STREQUAL "cpp") + set(CODEGEN_TEST_FUNCTIONS_TYPE OBJECT) +else() + # LLVM resolves these helper symbols dynamically from the shared library. + set(CODEGEN_TEST_FUNCTIONS_TYPE SHARED) +endif() + add_library( - codegen_test_functions SHARED + codegen_test_functions ${CODEGEN_TEST_FUNCTIONS_TYPE} testfunctions.cpp testfunctions.h testmock.h @@ -7,10 +14,9 @@ add_library( target_link_libraries( codegen_test_functions - GTest::gtest_main - GTest::gmock_main scratchcpp scratchcpp_mocks + GTest::gmock ) add_executable( @@ -64,6 +70,21 @@ if (NOT LIBSCRATCHCPP_CODEGEN_BACKEND STREQUAL "cpp") ) endif() +if (LIBSCRATCHCPP_CODEGEN_BACKEND STREQUAL "cpp") + set(CPP_EXTRA_TEST_SOURCES + "${CMAKE_CURRENT_SOURCE_DIR}/../engine/engine_test.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/../blocks/util.cpp" + ) + foreach(CPP_BLOCK_EXTENSION motion looks sound event control sensing operator variable list custom) + string(TOUPPER "${CPP_BLOCK_EXTENSION}" CPP_BLOCK_EXTENSION_UPPER) + if (LIBSCRATCHCPP_ENABLE_${CPP_BLOCK_EXTENSION_UPPER}_BLOCKS) + list(APPEND CPP_EXTRA_TEST_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/../blocks/${CPP_BLOCK_EXTENSION}_blocks_test.cpp") + endif() + endforeach() + target_sources(codegen_test PRIVATE ${CPP_EXTRA_TEST_SOURCES}) + target_include_directories(codegen_test PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../blocks") +endif() + target_link_libraries( codegen_test GTest::gtest_main @@ -78,5 +99,73 @@ gtest_discover_tests(codegen_test) if (LIBSCRATCHCPP_CODEGEN_BACKEND STREQUAL "llvm") add_subdirectory(llvm) elseif (LIBSCRATCHCPP_CODEGEN_BACKEND STREQUAL "cpp") + set(CPP_GENERATED_TEST_DIR "${CMAKE_CURRENT_BINARY_DIR}/generated_cpp_test_code") + set(CPP_GENERATED_TEST_SOURCE "${CPP_GENERATED_TEST_DIR}/generated_cpp_test_code.cpp") + set(CPP_GENERATED_TEST_HEADER "${CPP_GENERATED_TEST_DIR}/generated_cpp_test_code.h") + set(CPP_GENERATED_TEST_CHUNKS) + set(CPP_GENERATED_TEST_OUTPUTS "${CPP_GENERATED_TEST_SOURCE}" "${CPP_GENERATED_TEST_HEADER}") + + foreach(CPP_CHUNK_INDEX RANGE 0 63) + set(CPP_CHUNK_SOURCE "${CPP_GENERATED_TEST_DIR}/generated_cpp_test_code_${CPP_CHUNK_INDEX}.cpp") + list(APPEND CPP_GENERATED_TEST_CHUNKS "${CPP_CHUNK_SOURCE}") + list(APPEND CPP_GENERATED_TEST_OUTPUTS "${CPP_CHUNK_SOURCE}") + endforeach() + + get_target_property(CPP_TEST_CASE_SOURCES codegen_test SOURCES) + list(REMOVE_ITEM CPP_TEST_CASE_SOURCES main.cpp) + + # Keep the original test sources associated with codegen_test in IDE test + # discovery. The generator compiles them through generated translation units. + set(CPP_TEST_GENERATOR_SOURCES) + set(CPP_TEST_CASE_INDEX 0) + foreach(CPP_TEST_CASE_SOURCE IN LISTS CPP_TEST_CASE_SOURCES) + if (CPP_TEST_CASE_SOURCE MATCHES "\\.cpp$") + get_filename_component(CPP_TEST_CASE_PATH "${CPP_TEST_CASE_SOURCE}" ABSOLUTE BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") + set(CPP_TEST_WRAPPER "${CMAKE_CURRENT_BINARY_DIR}/cpp_test_script_generator_sources/test_case_${CPP_TEST_CASE_INDEX}.cpp") + file(GENERATE OUTPUT "${CPP_TEST_WRAPPER}" CONTENT "#include \"${CPP_TEST_CASE_PATH}\"\n") + list(APPEND CPP_TEST_GENERATOR_SOURCES "${CPP_TEST_WRAPPER}") + math(EXPR CPP_TEST_CASE_INDEX "${CPP_TEST_CASE_INDEX} + 1") + endif() + endforeach() + set_source_files_properties(${CPP_TEST_GENERATOR_SOURCES} PROPERTIES GENERATED TRUE) + + add_executable( + cpp_test_script_generator + cpp/testscriptgenerator.cpp + ${CPP_TEST_GENERATOR_SOURCES} + ) + target_compile_definitions(cpp_test_script_generator PRIVATE LIBSCRATCHCPP_CPP_TEST_GENERATOR) + if (UNIX) + target_compile_options(cpp_test_script_generator PRIVATE -g0) + endif() + target_link_libraries( + cpp_test_script_generator + GTest::gtest + GTest::gmock + scratchcpp + scratchcpp_mocks + codegen_test_functions + ) + + add_custom_command( + OUTPUT ${CPP_GENERATED_TEST_OUTPUTS} + COMMAND $ "${CPP_GENERATED_TEST_DIR}" + DEPENDS cpp_test_script_generator + VERBATIM + ) + + target_sources(codegen_test PRIVATE ${CPP_GENERATED_TEST_CHUNKS} "${CPP_GENERATED_TEST_SOURCE}" "${CPP_GENERATED_TEST_HEADER}") + target_include_directories(codegen_test PRIVATE + "${CPP_GENERATED_TEST_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}/.." + "${CMAKE_CURRENT_SOURCE_DIR}/../../src/engine/internal/codegen/cpp" + ) + target_compile_definitions(codegen_test PRIVATE LIBSCRATCHCPP_CPP_TEST_GENERATED_CODE) + if (UNIX) + target_compile_options(codegen_test PRIVATE -g0) + endif() + add_dependencies(codegen_test cpp_test_script_generator) + add_subdirectory(cpp) endif() diff --git a/test/codegen/codebuilder_test.cpp b/test/codegen/codebuilder_test.cpp index 7e16a9c4..0a2a1449 100644 --- a/test/codegen/codebuilder_test.cpp +++ b/test/codegen/codebuilder_test.cpp @@ -84,6 +84,9 @@ TEST_F(CodeBuilderTest, FunctionCalls) builder->addFunctionCall("test_print_unknown", Compiler::StaticType::Void, { Compiler::StaticType::Unknown }, { v }); auto code = builder->build(); +#ifdef LIBSCRATCHCPP_CPP_TEST_GENERATOR + continue; +#endif Script script(&m_utils.target(), nullptr, nullptr); script.setCode(code); Thread thread(&m_utils.target(), nullptr, &script); @@ -123,6 +126,9 @@ TEST_F(CodeBuilderTest, FunctionCalls) TEST_F(CodeBuilderTest, FunctionCallsWithPointers) { +#if defined(LIBSCRATCHCPP_CPP_TEST_GENERATOR) || defined(LIBSCRATCHCPP_CPP_TEST_GENERATED_CODE) + GTEST_SKIP() << "C++ backend does not support pointer constants"; +#else ICodeBuilder *builder = m_utils.createBuilder(true); int var = 12; @@ -148,6 +154,7 @@ TEST_F(CodeBuilderTest, FunctionCallsWithPointers) code->run(ctx.get()); ASSERT_EQ(testing::internal::GetCapturedStdout(), expected); ASSERT_TRUE(code->isFinished(ctx.get())); +#endif } TEST_F(CodeBuilderTest, ConstCasting) @@ -3860,6 +3867,7 @@ TEST_F(CodeBuilderTest, Reporters) auto code3 = builder->build(); +#if !defined(LIBSCRATCHCPP_CPP_TEST_GENERATOR) && !defined(LIBSCRATCHCPP_CPP_TEST_GENERATED_CODE) // Reporter 4 builder = m_utils.createReporterBuilder(&sprite); int pointee; @@ -3873,6 +3881,7 @@ TEST_F(CodeBuilderTest, Reporters) builder->addFunctionCall("test_const_pointer", Compiler::StaticType::Pointer, { Compiler::StaticType::Pointer }, { v }); auto code5 = builder->build(); +#endif auto runReporter = [&sprite](std::shared_ptr code) { Script script(&sprite, nullptr, nullptr); @@ -3899,6 +3908,7 @@ TEST_F(CodeBuilderTest, Reporters) ASSERT_EQ(Value(ret).toString(), "Hello world!"); value_free(&ret); +#if !defined(LIBSCRATCHCPP_CPP_TEST_GENERATOR) && !defined(LIBSCRATCHCPP_CPP_TEST_GENERATED_CODE) // 4 ret = runReporter(code4); ASSERT_TRUE(value_isPointer(&ret)); @@ -3910,6 +3920,7 @@ TEST_F(CodeBuilderTest, Reporters) ASSERT_TRUE(value_isPointer(&ret)); ASSERT_EQ(value_toPointer(&ret), &pointee); value_free(&ret); +#endif } TEST_F(CodeBuilderTest, UnknownTypeReporter) diff --git a/test/codegen/cpp/cppcodegenerator_test.cpp b/test/codegen/cpp/cppcodegenerator_test.cpp index 90740acb..2dac0203 100644 --- a/test/codegen/cpp/cppcodegenerator_test.cpp +++ b/test/codegen/cpp/cppcodegenerator_test.cpp @@ -9,12 +9,41 @@ #include #include #include +#include +#include +#include #include #include #include using namespace libscratchcpp; +TEST(CppCodeBuilderTest, UsesGeneratedCodeWithTheBuilderId) +{ + CppCompilerContext context(nullptr, nullptr); + context.setTestCodeId("builder#0"); + auto code = std::make_shared(&context); + context.setGeneratedCodeFactory([&](const std::string &id, CppCompilerContext *ctx) { + EXPECT_EQ(id, "builder#0"); + EXPECT_EQ(ctx, &context); + return code; + }); + + auto builder = CodeBuilderFactory::instance()->create(&context, nullptr, Compiler::CodeType::Script); + context.setTestCodeId("builder#1"); + EXPECT_EQ(builder->build(), code); +} + +TEST(CppCodeBuilderTest, MissingGeneratedCodeFailsExplicitly) +{ + CppCompilerContext context(nullptr, nullptr); + context.setTestCodeId("missing#0"); + context.setGeneratedCodeFactory([](const std::string &, CppCompilerContext *) -> std::shared_ptr { return nullptr; }); + + auto builder = CodeBuilderFactory::instance()->create(&context, nullptr, Compiler::CodeType::Script); + EXPECT_THROW(builder->build(), std::runtime_error); +} + TEST(CppCodeGeneratorTest, StringReturnValueCanBePassedToAnotherCall) { CppCodeGenerator codeGen; @@ -30,6 +59,23 @@ TEST(CppCodeGeneratorTest, StringReturnValueCanBePassedToAnotherCall) EXPECT_NE(source.find("test_print_string(string0)"), std::string::npos); } +TEST(CppCodeGeneratorTest, ReporterReturnsBoxedResult) +{ + CppCodeGenerator codeGen; + CppValue reporterResult(Compiler::StaticType::Number); + reporterResult.isRawValue = true; + + codeGen.createCall("test_get_number", CppIdentifier::Type::Double, &reporterResult, false, false, {}); + codeGen.setCodeType(Compiler::CodeType::Reporter, &reporterResult); + + const std::string source = codeGen.finalize(); + const std::string declaration = codeGen.generatedClassDeclaration(); + + EXPECT_NE(source.find("ValueData Script"), std::string::npos); + EXPECT_NE(source.find("value_assign_copy(&returnValue, &value0);"), std::string::npos) << source; + EXPECT_NE(declaration.find("ValueData runReporter("), std::string::npos); +} + TEST(CppCodeGeneratorTest, ReporterCanBeConvertedAndBoxedWithoutChangingItsOriginalValue) { CppCodeGenerator codeGen; @@ -52,7 +98,7 @@ TEST(CppCodeGeneratorTest, ReporterCanBeConvertedAndBoxedWithoutChangingItsOrigi EXPECT_NE(source.find("test_print_number(ret0)"), std::string::npos); EXPECT_NE(source.find("value0.numberValue = ret0;"), std::string::npos) << source; EXPECT_NE(source.find("value0.type = ValueType::Number;"), std::string::npos) << source; - EXPECT_NE(source.find("test_print_unknown(value0)"), std::string::npos) << source; + EXPECT_NE(source.find("test_print_unknown(&value0)"), std::string::npos) << source; } TEST(CppCodeSaverTest, WritesOnePairOfFilesPerScriptInTargetDirectories) diff --git a/test/codegen/cpp/testcodegenlistener.h b/test/codegen/cpp/testcodegenlistener.h new file mode 100644 index 00000000..ea6c8837 --- /dev/null +++ b/test/codegen/cpp/testcodegenlistener.h @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include + +#include + +#include "engine/internal/codegen/cpp/cppcompilercontext.h" + +namespace libscratchcpp::test +{ + +class CppTestCodegenListener : public testing::EmptyTestEventListener +{ + public: + void OnTestStart(const testing::TestInfo &testInfo) override + { + m_testName = std::string(testInfo.test_suite_name()) + "." + testInfo.name(); + m_builderCount = 0; + } + + void registerProvider() + { + CppCompilerContext::setTestCodeIdProvider([this] { + return m_testName + "#" + std::to_string(m_builderCount++); + }); + } + + private: + std::string m_testName; + unsigned int m_builderCount = 0; +}; + +} // namespace libscratchcpp::test diff --git a/test/codegen/cpp/testscriptgenerator.cpp b/test/codegen/cpp/testscriptgenerator.cpp new file mode 100644 index 00000000..f0b225fa --- /dev/null +++ b/test/codegen/cpp/testscriptgenerator.cpp @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include +#include +#include + +#include + +#include "testcodegenlistener.h" + +namespace +{ + +constexpr size_t SCRIPT_CHUNK_SIZE = 100; +constexpr size_t SCRIPT_CHUNK_COUNT = 64; + +bool writeGeneratedFactory(const std::filesystem::path &destination) +{ + std::map> scripts; + std::ifstream manifest(destination / "test_scripts.txt"); + if (!manifest) + return false; + std::string id; + std::string className; + std::string sourcePath; + + while (manifest >> id >> className >> sourcePath) { + if (!scripts.emplace(id, std::make_pair(className, sourcePath)).second) { + std::cerr << "error: duplicate C++ test script ID: " << id << std::endl; + return false; + } + } + + if (scripts.empty() || scripts.size() > SCRIPT_CHUNK_SIZE * SCRIPT_CHUNK_COUNT) { + std::cerr << "error: invalid generated C++ test script count: " << scripts.size() << std::endl; + return false; + } + + std::ofstream header(destination / "generated_cpp_test_code.h"); + header << "#pragma once\n\n" + "#include \n#include \n" + "#include \n\n" + "namespace libscratchcpp\n{\n" + "class CppCompilerContext;\n" + "std::shared_ptr createGeneratedCppTestCode(const std::string &id, CppCompilerContext *ctx);\n"; + + for (size_t chunk = 0; chunk < SCRIPT_CHUNK_COUNT; ++chunk) + header << "std::shared_ptr createGeneratedCppTestCodeChunk" << chunk << "(const std::string &id, CppCompilerContext *ctx);\n"; + + header << "}\n"; + + std::ofstream source(destination / "generated_cpp_test_code.cpp"); + source << "#include \"generated_cpp_test_code.h\"\n" + "\nnamespace libscratchcpp\n{\n\n" + "std::shared_ptr createGeneratedCppTestCode(const std::string &id, CppCompilerContext *ctx)\n{\n"; + + for (size_t chunk = 0; chunk < SCRIPT_CHUNK_COUNT; ++chunk) + source << " if (auto code = createGeneratedCppTestCodeChunk" << chunk << "(id, ctx))\n return code;\n"; + + source << " return nullptr;\n}\n\n} // namespace libscratchcpp\n"; + + auto script = scripts.begin(); + + for (size_t chunk = 0; chunk < SCRIPT_CHUNK_COUNT; ++chunk) { + std::ofstream chunkSource(destination / ("generated_cpp_test_code_" + std::to_string(chunk) + ".cpp")); + chunkSource << "#include \"testfunctions.h\"\n" + "#include \"generated_cpp_test_code.h\"\n"; + + std::vector> chunkScripts; + for (size_t i = 0; i < SCRIPT_CHUNK_SIZE && script != scripts.end(); ++i, ++script) { + chunkSource << "#include \"" << script->second.second << "\"\n"; + chunkScripts.emplace_back(script->first, script->second.first); + } + + chunkSource << "\nnamespace libscratchcpp\n{\n\n" + "std::shared_ptr createGeneratedCppTestCodeChunk" << chunk << "(const std::string &id, CppCompilerContext *ctx)\n{\n"; + + for (const auto &entry : chunkScripts) + chunkSource << " if (id == \"" << entry.first << "\")\n return std::make_shared<" << entry.second << ">(ctx);\n"; + + chunkSource << " return nullptr;\n}\n\n} // namespace libscratchcpp\n"; + chunkSource.close(); + if (!chunkSource) + return false; + } + + header.close(); + source.close(); + return header.good() && source.good(); +} + +} // namespace + +int main(int argc, char **argv) +{ + if (argc != 2) + return 1; + + const std::filesystem::path destination = std::filesystem::absolute(argv[1]); + std::error_code error; + std::filesystem::remove_all(destination, error); + + if (error) + return 1; + + std::filesystem::create_directories(destination, error); + + if (error) + return 1; + + libscratchcpp::CppCompilerContext::setTestGenerationDirectory(destination.string()); + std::filesystem::current_path(DATA_DIR); + + int gtestArgc = 1; + char *gtestArgv[] = { argv[0], nullptr }; + ::testing::InitGoogleTest(>estArgc, gtestArgv); + ::testing::GTEST_FLAG(brief) = true; + delete ::testing::UnitTest::GetInstance()->listeners().Release(::testing::UnitTest::GetInstance()->listeners().default_result_printer()); + auto *listener = new libscratchcpp::test::CppTestCodegenListener(); + listener->registerProvider(); + ::testing::UnitTest::GetInstance()->listeners().Append(listener); + + std::string testFilter = "CodeBuilderTest.*"; + + for (int i = 0; i < ::testing::UnitTest::GetInstance()->total_test_suite_count(); ++i) { + const std::string suiteName = ::testing::UnitTest::GetInstance()->GetTestSuite(i)->name(); + + if (suiteName.size() > 4 && suiteName.substr(suiteName.size() - 4) == "Test") + testFilter += ":" + suiteName + ".*"; + } + + ::testing::GTEST_FLAG(filter) = testFilter; + // This pass records builders using placeholder executable code. Execution + // assertions are checked by codegen_test after the generated C++ is compiled. + const int testResult = RUN_ALL_TESTS(); + (void)testResult; + + if (!std::filesystem::exists(destination / "test_scripts.txt")) { + std::cerr << "error: no C++ test scripts were generated" << std::endl; + return 1; + } + + return writeGeneratedFactory(destination) ? 0 : 1; +} diff --git a/test/codegen/main.cpp b/test/codegen/main.cpp index 1898d06d..dd6a4cba 100644 --- a/test/codegen/main.cpp +++ b/test/codegen/main.cpp @@ -1 +1,21 @@ #include "../common.h" + +#ifdef LIBSCRATCHCPP_CPP_TEST_GENERATED_CODE + +#include "generated_cpp_test_code.h" +#include "cpp/testcodegenlistener.h" + +int main(int argc, char **argv) +{ + std::filesystem::current_path(DATA_DIR); + ::testing::InitGoogleTest(&argc, argv); + + libscratchcpp::CppCompilerContext::setDefaultGeneratedCodeFactory(libscratchcpp::createGeneratedCppTestCode); + auto *listener = new libscratchcpp::test::CppTestCodegenListener(); + listener->registerProvider(); + ::testing::UnitTest::GetInstance()->listeners().Append(listener); + + return RUN_ALL_TESTS(); +} + +#endif diff --git a/test/codegen/testfunctions.h b/test/codegen/testfunctions.h index c56162f4..4f9809e6 100644 --- a/test/codegen/testfunctions.h +++ b/test/codegen/testfunctions.h @@ -21,6 +21,8 @@ extern "C" void test_empty_function(); void test_ctx_function(ExecutionContext *ctx, const StringPtr *arg); + void test_print(const StringPtr *str); + bool test_condition(); void test_function_no_args(Target *target); void test_function_no_args_ret(StringPtr *ret, Target *target); diff --git a/test/common.h b/test/common.h index 0024565f..d7ab50ec 100644 --- a/test/common.h +++ b/test/common.h @@ -24,7 +24,7 @@ ASSERT_TRUE(block->fieldAt(block->findField(fieldName))) #define GET_FIELD(block, fieldName) block->fieldAt(block->findField(fieldName)) -std::string readFileStr(const std::string &fileName) +inline std::string readFileStr(const std::string &fileName) { std::ifstream file(fileName); if (!file.is_open()) { @@ -37,9 +37,11 @@ std::string readFileStr(const std::string &fileName) return buffer.str(); } +#if !defined(LIBSCRATCHCPP_CPP_TEST_GENERATOR) && !defined(LIBSCRATCHCPP_CPP_TEST_GENERATED_CODE) int main(int argc, char **argv) { std::filesystem::current_path(DATA_DIR); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } +#endif