Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions include/scratchcpp/compiler.h
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ class LIBSCRATCHCPP_EXPORT Compiler
Block *block() const;

std::shared_ptr<ExecutableCode> 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 = {});
Expand Down
3 changes: 3 additions & 0 deletions include/scratchcpp/iengine.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions include/scratchcpp/project.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

#include <memory>
#include <functional>
#include <string>
#include "spimpl.h"

#include "global.h"
Expand All @@ -29,6 +30,7 @@ class LIBSCRATCHCPP_EXPORT Project
Project(const Project &) = delete;

bool load();
void save(const std::string &destination);
void stopLoading();

void start();
Expand Down
11 changes: 11 additions & 0 deletions src/engine/compiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,17 @@ std::shared_ptr<ExecutableCode> 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.
Expand Down
2 changes: 2 additions & 0 deletions src/engine/internal/codegen/cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ target_sources(scratchcpp
cppconstant.h
cppcodebuilder.cpp
cppcodebuilder.h
cppcodesaver.cpp
cppcodesaver.h
cppcodegenerator.cpp
cppcodegenerator.h
cppcodestream.h
Expand Down
81 changes: 78 additions & 3 deletions src/engine/internal/codegen/cpp/cppcodebuilder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,14 @@
#include <scratchcpp/compilerlocalvariable.h>
#include <scratchcpp/variable.h>
#include <scratchcpp/list.h>
#include <iostream>
#include <fstream>
#include <cctype>
#include <filesystem>
#include <functional>

#include "cppcodebuilder.h"
#include "cppcodesaver.h"
#include "cppcompilercontext.h"
#include "cppexecutablecode.h"
#include "cppinstruction.h"
Expand All @@ -15,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),
Expand All @@ -24,6 +31,13 @@ CppCodeBuilder::CppCodeBuilder(CppCompilerContext *ctx, BlockPrototype *procedur

std::shared_ptr<ExecutableCode> 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) {
Expand All @@ -48,14 +62,74 @@ std::shared_ptr<ExecutableCode> 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;
}

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<char>(character) : '_';

const std::string uniqueSuffix = suffix + "_" + std::to_string(std::hash<std::string>{}(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());

std::cout << m_codeGen.finalize();
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<CppExecutableCode>(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);
Comment on lines +129 to +130

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Exported scripts ignore their conditions

When a Scratch if contains a say block, CppCodeBuilder::save exports the say call without its condition. buildBeginIf emits no branch, so the exported script speaks even when the condition is false.

Learn more

compileIf sends its condition and body to Compiler::moveToIf, which places a branch instruction before the body. The C++ branch and loop handlers advance without emitting control flow. In contrast, compileSay emits a normal function call, which buildFunctionCall translates. The public save path therefore writes source that runs the body without its condition rather than rejecting an incomplete export.

Example: Export a green-flag script containing if <mouse down?> then say [Pressed]. The exported code calls looks_say even when the mouse button is up.

Recommended fix: Implement control-flow emission or reject export when a script contains an instruction the backend cannot emit. Propagate the error through project save and add a regression test that either rejects the example or confirms the exported script stays silent when the condition is false.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

}

CompilerValue *CppCodeBuilder::addFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args)
{
assert(argTypes.size() == args.size());
Expand Down Expand Up @@ -99,6 +173,7 @@ CompilerConstant *CppCodeBuilder::addConstValue(const Value &value)
{
auto constValue = std::make_shared<CppConstant>(TypeUtils::mapType(value.type()), value);
auto genericValue = std::static_pointer_cast<CppValue>(constValue);
m_lastConstValue = genericValue.get();
return static_cast<CompilerConstant *>(static_cast<CppConstant *>(addValue(genericValue, nullptr)));
}

Expand Down
3 changes: 3 additions & 0 deletions src/engine/internal/codegen/cpp/cppcodebuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class CppCodeBuilder : public ICodeBuilder
CppCodeBuilder(CppCompilerContext *ctx, BlockPrototype *procedurePrototype = nullptr, Compiler::CodeType codeType = Compiler::CodeType::Script);

std::shared_ptr<ExecutableCode> 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;
Expand Down Expand Up @@ -127,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<std::shared_ptr<CppValue>> m_values;
CppValue *m_lastConstValue = nullptr;
std::vector<std::shared_ptr<CompilerLocalVariable>> m_localVars;
CppInstructionList m_instructions;
CppCodeGenerator m_codeGen;
Expand Down
Loading
Loading