From ef8a40447dd14ff30e95c5589890ee461a797f97 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:23:11 +0100 Subject: [PATCH 01/18] Add C++ instruction builder --- .../internal/codegen/cpp/CMakeLists.txt | 2 + .../codegen/cpp/instructions/CMakeLists.txt | 30 +++ .../codegen/cpp/instructions/comparison.cpp | 65 ++++++ .../codegen/cpp/instructions/comparison.h | 25 ++ .../codegen/cpp/instructions/control.cpp | 155 +++++++++++++ .../codegen/cpp/instructions/control.h | 35 +++ .../codegen/cpp/instructions/functions.cpp | 29 +++ .../codegen/cpp/instructions/functions.h | 21 ++ .../cpp/instructions/instructionbuilder.cpp | 46 ++++ .../cpp/instructions/instructionbuilder.h | 24 ++ .../cpp/instructions/instructiongroup.cpp | 9 + .../cpp/instructions/instructiongroup.h | 18 ++ .../codegen/cpp/instructions/lists.cpp | 110 +++++++++ .../internal/codegen/cpp/instructions/lists.h | 37 +++ .../codegen/cpp/instructions/logic.cpp | 48 ++++ .../internal/codegen/cpp/instructions/logic.h | 23 ++ .../codegen/cpp/instructions/math.cpp | 217 ++++++++++++++++++ .../internal/codegen/cpp/instructions/math.h | 42 ++++ .../codegen/cpp/instructions/procedures.cpp | 40 ++++ .../codegen/cpp/instructions/procedures.h | 22 ++ .../codegen/cpp/instructions/processresult.h | 27 +++ .../codegen/cpp/instructions/string.cpp | 47 ++++ .../codegen/cpp/instructions/string.h | 23 ++ .../codegen/cpp/instructions/variables.cpp | 65 ++++++ .../codegen/cpp/instructions/variables.h | 25 ++ 25 files changed, 1185 insertions(+) create mode 100644 src/engine/internal/codegen/cpp/instructions/CMakeLists.txt create mode 100644 src/engine/internal/codegen/cpp/instructions/comparison.cpp create mode 100644 src/engine/internal/codegen/cpp/instructions/comparison.h create mode 100644 src/engine/internal/codegen/cpp/instructions/control.cpp create mode 100644 src/engine/internal/codegen/cpp/instructions/control.h create mode 100644 src/engine/internal/codegen/cpp/instructions/functions.cpp create mode 100644 src/engine/internal/codegen/cpp/instructions/functions.h create mode 100644 src/engine/internal/codegen/cpp/instructions/instructionbuilder.cpp create mode 100644 src/engine/internal/codegen/cpp/instructions/instructionbuilder.h create mode 100644 src/engine/internal/codegen/cpp/instructions/instructiongroup.cpp create mode 100644 src/engine/internal/codegen/cpp/instructions/instructiongroup.h create mode 100644 src/engine/internal/codegen/cpp/instructions/lists.cpp create mode 100644 src/engine/internal/codegen/cpp/instructions/lists.h create mode 100644 src/engine/internal/codegen/cpp/instructions/logic.cpp create mode 100644 src/engine/internal/codegen/cpp/instructions/logic.h create mode 100644 src/engine/internal/codegen/cpp/instructions/math.cpp create mode 100644 src/engine/internal/codegen/cpp/instructions/math.h create mode 100644 src/engine/internal/codegen/cpp/instructions/procedures.cpp create mode 100644 src/engine/internal/codegen/cpp/instructions/procedures.h create mode 100644 src/engine/internal/codegen/cpp/instructions/processresult.h create mode 100644 src/engine/internal/codegen/cpp/instructions/string.cpp create mode 100644 src/engine/internal/codegen/cpp/instructions/string.h create mode 100644 src/engine/internal/codegen/cpp/instructions/variables.cpp create mode 100644 src/engine/internal/codegen/cpp/instructions/variables.h diff --git a/src/engine/internal/codegen/cpp/CMakeLists.txt b/src/engine/internal/codegen/cpp/CMakeLists.txt index bf3e34349..03d4b1289 100644 --- a/src/engine/internal/codegen/cpp/CMakeLists.txt +++ b/src/engine/internal/codegen/cpp/CMakeLists.txt @@ -13,3 +13,5 @@ target_sources(scratchcpp cppcodebuilder.cpp cppcodebuilder.h ) + +add_subdirectory(instructions) diff --git a/src/engine/internal/codegen/cpp/instructions/CMakeLists.txt b/src/engine/internal/codegen/cpp/instructions/CMakeLists.txt new file mode 100644 index 000000000..bdf67e3ac --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/CMakeLists.txt @@ -0,0 +1,30 @@ +target_sources(scratchcpp + PRIVATE + instructionbuilder.cpp + instructionbuilder.h + instructiongroup.cpp + instructiongroup.h + processresult.h +) + +target_sources(scratchcpp + PRIVATE + functions.cpp + functions.h + math.cpp + math.h + comparison.cpp + comparison.h + string.cpp + string.h + logic.cpp + logic.h + control.cpp + control.h + variables.cpp + variables.h + lists.cpp + lists.h + procedures.cpp + procedures.h +) diff --git a/src/engine/internal/codegen/cpp/instructions/comparison.cpp b/src/engine/internal/codegen/cpp/instructions/comparison.cpp new file mode 100644 index 000000000..23b9130a4 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/comparison.cpp @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "comparison.h" +#include "../cppinstruction.h" + +using namespace libscratchcpp; +using namespace libscratchcpp::cppins; + +ProcessResult Comparison::process(CppInstruction *ins) +{ + ProcessResult ret(true, ins); + + switch (ins->type) { + case CppInstruction::Type::CmpEQ: + ret.next = buildCmpEQ(ins); + break; + + case CppInstruction::Type::CmpGT: + ret.next = buildCmpGT(ins); + break; + + case CppInstruction::Type::CmpLT: + ret.next = buildCmpLT(ins); + break; + + case CppInstruction::Type::StrCmpEQCS: + ret.next = buildStrCmpEQCS(ins); + break; + + case CppInstruction::Type::StrCmpEQCI: + ret.next = buildStrCmpEQCI(ins); + break; + + default: + ret.match = false; + break; + } + + return ret; +} + +CppInstruction *Comparison::buildCmpEQ(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Comparison::buildCmpGT(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Comparison::buildCmpLT(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Comparison::buildStrCmpEQCS(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Comparison::buildStrCmpEQCI(CppInstruction *ins) +{ + return ins->getNext(); +} diff --git a/src/engine/internal/codegen/cpp/instructions/comparison.h b/src/engine/internal/codegen/cpp/instructions/comparison.h new file mode 100644 index 000000000..1a7b496e4 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/comparison.h @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "instructiongroup.h" + +namespace libscratchcpp::cppins +{ + +class Comparison : public InstructionGroup +{ + public: + using InstructionGroup::InstructionGroup; + + ProcessResult process(CppInstruction *ins) override; + + private: + CppInstruction *buildCmpEQ(CppInstruction *ins); + CppInstruction *buildCmpGT(CppInstruction *ins); + CppInstruction *buildCmpLT(CppInstruction *ins); + CppInstruction *buildStrCmpEQCS(CppInstruction *ins); + CppInstruction *buildStrCmpEQCI(CppInstruction *ins); +}; + +} // namespace libscratchcpp::cppins diff --git a/src/engine/internal/codegen/cpp/instructions/control.cpp b/src/engine/internal/codegen/cpp/instructions/control.cpp new file mode 100644 index 000000000..78f56135d --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/control.cpp @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "control.h" +#include "../cppinstruction.h" + +using namespace libscratchcpp; +using namespace libscratchcpp::cppins; + +ProcessResult Control::process(CppInstruction *ins) +{ + ProcessResult ret(true, ins); + + switch (ins->type) { + case CppInstruction::Type::Select: + ret.next = buildSelect(ins); + break; + + case CppInstruction::Type::Yield: + ret.next = buildYield(ins); + break; + + case CppInstruction::Type::BeginIf: + ret.next = buildBeginIf(ins); + break; + + case CppInstruction::Type::BeginElse: + ret.next = buildBeginElse(ins); + break; + + case CppInstruction::Type::EndIf: + ret.next = buildEndIf(ins); + break; + + case CppInstruction::Type::BeginRepeatLoop: + ret.next = buildBeginRepeatLoop(ins); + break; + + case CppInstruction::Type::LoopIndex: + ret.next = buildLoopIndex(ins); + break; + + case CppInstruction::Type::BeginWhileLoop: + ret.next = buildBeginWhileLoop(ins); + break; + + case CppInstruction::Type::BeginRepeatUntilLoop: + ret.next = buildBeginRepeatUntilLoop(ins); + break; + + case CppInstruction::Type::BeginLoopCondition: + ret.next = buildBeginLoopCondition(ins); + break; + + case CppInstruction::Type::EndLoop: + ret.next = buildEndLoop(ins); + break; + + case CppInstruction::Type::Stop: + ret.next = buildStop(ins); + break; + + case CppInstruction::Type::ThreadStop: + ret.next = buildThreadStop(ins); + break; + + case CppInstruction::Type::InvalidateTarget: + ret.next = buildInvalidateTarget(ins); + break; + + case CppInstruction::Type::Print: + ret.next = buildPrint(ins); + break; + + default: + ret.match = false; + break; + } + + return ret; +} + +CppInstruction *Control::buildSelect(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildYield(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildBeginIf(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildBeginElse(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildEndIf(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildBeginRepeatLoop(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildLoopIndex(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildBeginWhileLoop(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildBeginRepeatUntilLoop(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildBeginLoopCondition(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildEndLoop(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildStop(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildThreadStop(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildInvalidateTarget(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Control::buildPrint(CppInstruction *ins) +{ + return ins->getNext(); +} diff --git a/src/engine/internal/codegen/cpp/instructions/control.h b/src/engine/internal/codegen/cpp/instructions/control.h new file mode 100644 index 000000000..8f92c8f8d --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/control.h @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "instructiongroup.h" + +namespace libscratchcpp::cppins +{ + +class Control : public InstructionGroup +{ + public: + using InstructionGroup::InstructionGroup; + + ProcessResult process(CppInstruction *ins) override; + + private: + CppInstruction *buildSelect(CppInstruction *ins); + CppInstruction *buildYield(CppInstruction *ins); + CppInstruction *buildBeginIf(CppInstruction *ins); + CppInstruction *buildBeginElse(CppInstruction *ins); + CppInstruction *buildEndIf(CppInstruction *ins); + CppInstruction *buildBeginRepeatLoop(CppInstruction *ins); + CppInstruction *buildLoopIndex(CppInstruction *ins); + CppInstruction *buildBeginWhileLoop(CppInstruction *ins); + CppInstruction *buildBeginRepeatUntilLoop(CppInstruction *ins); + CppInstruction *buildBeginLoopCondition(CppInstruction *ins); + CppInstruction *buildEndLoop(CppInstruction *ins); + CppInstruction *buildStop(CppInstruction *ins); + CppInstruction *buildThreadStop(CppInstruction *ins); + CppInstruction *buildInvalidateTarget(CppInstruction *ins); + CppInstruction *buildPrint(CppInstruction *ins); +}; + +} // namespace libscratchcpp::cppins diff --git a/src/engine/internal/codegen/cpp/instructions/functions.cpp b/src/engine/internal/codegen/cpp/instructions/functions.cpp new file mode 100644 index 000000000..fe0396f48 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/functions.cpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "functions.h" +#include "../cppinstruction.h" + +using namespace libscratchcpp; +using namespace libscratchcpp::cppins; + +ProcessResult Functions::process(CppInstruction *ins) +{ + ProcessResult ret(true, ins); + + switch (ins->type) { + case CppInstruction::Type::FunctionCall: + ret.next = buildFunctionCall(ins); + break; + + default: + ret.match = false; + break; + } + + return ret; +} + +CppInstruction *Functions::buildFunctionCall(CppInstruction *ins) +{ + return ins->getNext(); +} diff --git a/src/engine/internal/codegen/cpp/instructions/functions.h b/src/engine/internal/codegen/cpp/instructions/functions.h new file mode 100644 index 000000000..850ca00ab --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/functions.h @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "instructiongroup.h" + +namespace libscratchcpp::cppins +{ + +class Functions : public InstructionGroup +{ + public: + using InstructionGroup::InstructionGroup; + + ProcessResult process(CppInstruction *ins) override; + + private: + CppInstruction *buildFunctionCall(CppInstruction *ins); +}; + +} // namespace libscratchcpp::cppins diff --git a/src/engine/internal/codegen/cpp/instructions/instructionbuilder.cpp b/src/engine/internal/codegen/cpp/instructions/instructionbuilder.cpp new file mode 100644 index 000000000..0c4cebddb --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/instructionbuilder.cpp @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "instructionbuilder.h" +#include "functions.h" +#include "math.h" +#include "comparison.h" +#include "string.h" +#include "logic.h" +#include "control.h" +#include "variables.h" +#include "lists.h" +#include "procedures.h" +#include "../cppinstruction.h" + +using namespace libscratchcpp; +using namespace libscratchcpp::cppins; + +InstructionBuilder::InstructionBuilder() +{ + // Create groups + m_groups.push_back(std::make_shared()); + m_groups.push_back(std::make_shared()); + m_groups.push_back(std::make_shared()); + m_groups.push_back(std::make_shared()); + m_groups.push_back(std::make_shared()); + m_groups.push_back(std::make_shared()); + m_groups.push_back(std::make_shared()); + m_groups.push_back(std::make_shared()); + m_groups.push_back(std::make_shared()); +} + +CppInstruction *InstructionBuilder::process(CppInstruction *ins) +{ + // Process all groups + for (const auto &group : m_groups) { + ProcessResult result = group->process(ins); + + if (result.match) { + // TODO: Add integer support + return result.next; + } + } + + assert(false); // instruction not found + return ins; +} diff --git a/src/engine/internal/codegen/cpp/instructions/instructionbuilder.h b/src/engine/internal/codegen/cpp/instructions/instructionbuilder.h new file mode 100644 index 000000000..ea7c5d3d8 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/instructionbuilder.h @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include + +#include "instructiongroup.h" + +namespace libscratchcpp::cppins +{ + +class InstructionBuilder +{ + public: + InstructionBuilder(); + + CppInstruction *process(CppInstruction *ins); + + private: + std::vector> m_groups; +}; + +} // namespace libscratchcpp::cppins diff --git a/src/engine/internal/codegen/cpp/instructions/instructiongroup.cpp b/src/engine/internal/codegen/cpp/instructions/instructiongroup.cpp new file mode 100644 index 000000000..e41d26d85 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/instructiongroup.cpp @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "instructiongroup.h" + +using namespace libscratchcpp::cppins; + +InstructionGroup::InstructionGroup() +{ +} diff --git a/src/engine/internal/codegen/cpp/instructions/instructiongroup.h b/src/engine/internal/codegen/cpp/instructions/instructiongroup.h new file mode 100644 index 000000000..c36c10b27 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/instructiongroup.h @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "processresult.h" + +namespace libscratchcpp::cppins +{ + +class InstructionGroup +{ + public: + InstructionGroup(); + + virtual ProcessResult process(CppInstruction *ins) = 0; +}; + +} // namespace libscratchcpp::cppins diff --git a/src/engine/internal/codegen/cpp/instructions/lists.cpp b/src/engine/internal/codegen/cpp/instructions/lists.cpp new file mode 100644 index 000000000..739c38af8 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/lists.cpp @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "lists.h" +#include "../cppinstruction.h" + +using namespace libscratchcpp; +using namespace libscratchcpp::cppins; + +ProcessResult Lists::process(CppInstruction *ins) +{ + ProcessResult ret(true, ins); + + switch (ins->type) { + case CppInstruction::Type::ClearList: + ret.next = buildClearList(ins); + break; + + case CppInstruction::Type::RemoveListItem: + ret.next = buildRemoveListItem(ins); + break; + + case CppInstruction::Type::AppendToList: + ret.next = buildAppendToList(ins); + break; + + case CppInstruction::Type::InsertToList: + ret.next = buildInsertToList(ins); + break; + + case CppInstruction::Type::ListReplace: + ret.next = buildListReplace(ins); + break; + + case CppInstruction::Type::GetListContents: + ret.next = buildGetListContents(ins); + break; + + case CppInstruction::Type::GetListItem: + ret.next = buildGetListItem(ins); + break; + + case CppInstruction::Type::GetListSize: + ret.next = buildGetListSize(ins); + break; + + case CppInstruction::Type::GetListItemIndex: + ret.next = buildGetListItemIndex(ins); + break; + + case CppInstruction::Type::ListContainsItem: + ret.next = buildListContainsItem(ins); + break; + + default: + ret.match = false; + break; + } + + return ret; +} + +CppInstruction *Lists::buildClearList(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Lists::buildRemoveListItem(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Lists::buildAppendToList(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Lists::buildInsertToList(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Lists::buildListReplace(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Lists::buildGetListContents(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Lists::buildGetListItem(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Lists::buildGetListSize(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Lists::buildGetListItemIndex(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Lists::buildListContainsItem(CppInstruction *ins) +{ + return ins->getNext(); +} diff --git a/src/engine/internal/codegen/cpp/instructions/lists.h b/src/engine/internal/codegen/cpp/instructions/lists.h new file mode 100644 index 000000000..eec1c9c5f --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/lists.h @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include + +#include "instructiongroup.h" + +namespace libscratchcpp +{ + +namespace cppins +{ + +class Lists : public InstructionGroup +{ + public: + using InstructionGroup::InstructionGroup; + + ProcessResult process(CppInstruction *ins) override; + + private: + CppInstruction *buildClearList(CppInstruction *ins); + CppInstruction *buildRemoveListItem(CppInstruction *ins); + CppInstruction *buildAppendToList(CppInstruction *ins); + CppInstruction *buildInsertToList(CppInstruction *ins); + CppInstruction *buildListReplace(CppInstruction *ins); + CppInstruction *buildGetListContents(CppInstruction *ins); + CppInstruction *buildGetListItem(CppInstruction *ins); + CppInstruction *buildGetListSize(CppInstruction *ins); + CppInstruction *buildGetListItemIndex(CppInstruction *ins); + CppInstruction *buildListContainsItem(CppInstruction *ins); +}; + +} // namespace cppins + +} // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/instructions/logic.cpp b/src/engine/internal/codegen/cpp/instructions/logic.cpp new file mode 100644 index 000000000..bcd3c6004 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/logic.cpp @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "logic.h" +#include "../cppinstruction.h" + +using namespace libscratchcpp; +using namespace libscratchcpp::cppins; + +ProcessResult Logic::process(CppInstruction *ins) +{ + ProcessResult ret(true, ins); + + switch (ins->type) { + case CppInstruction::Type::And: + ret.next = buildAnd(ins); + break; + + case CppInstruction::Type::Or: + ret.next = buildOr(ins); + break; + + case CppInstruction::Type::Not: + ret.next = buildNot(ins); + break; + + default: + ret.match = false; + ret.next = (ins); + break; + } + + return ret; +} + +CppInstruction *Logic::buildAnd(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Logic::buildOr(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Logic::buildNot(CppInstruction *ins) +{ + return ins->getNext(); +} diff --git a/src/engine/internal/codegen/cpp/instructions/logic.h b/src/engine/internal/codegen/cpp/instructions/logic.h new file mode 100644 index 000000000..f51bccae6 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/logic.h @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "instructiongroup.h" + +namespace libscratchcpp::cppins +{ + +class Logic : public InstructionGroup +{ + public: + using InstructionGroup::InstructionGroup; + + ProcessResult process(CppInstruction *ins) override; + + private: + CppInstruction *buildAnd(CppInstruction *ins); + CppInstruction *buildOr(CppInstruction *ins); + CppInstruction *buildNot(CppInstruction *ins); +}; + +} // namespace libscratchcpp::cppins diff --git a/src/engine/internal/codegen/cpp/instructions/math.cpp b/src/engine/internal/codegen/cpp/instructions/math.cpp new file mode 100644 index 000000000..0b4ea7bb9 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/math.cpp @@ -0,0 +1,217 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "math.h" +#include "../cppinstruction.h" +using namespace libscratchcpp; +using namespace libscratchcpp::cppins; + +ProcessResult Math::process(CppInstruction *ins) +{ + ProcessResult ret(true, ins); + + switch (ins->type) { + case CppInstruction::Type::Add: + ret.next = buildAdd(ins); + break; + + case CppInstruction::Type::Sub: + ret.next = buildSub(ins); + break; + + case CppInstruction::Type::Mul: + ret.next = buildMul(ins); + break; + + case CppInstruction::Type::Div: + ret.next = buildDiv(ins); + break; + + case CppInstruction::Type::Random: + ret.next = buildRandom(ins); + break; + + case CppInstruction::Type::RandomInt: + ret.next = buildRandomInt(ins); + break; + + case CppInstruction::Type::Mod: + ret.next = buildMod(ins); + break; + + case CppInstruction::Type::Round: + ret.next = buildRound(ins); + break; + + case CppInstruction::Type::Abs: + ret.next = buildAbs(ins); + break; + + case CppInstruction::Type::Floor: + ret.next = buildFloor(ins); + break; + + case CppInstruction::Type::Ceil: + ret.next = buildCeil(ins); + break; + + case CppInstruction::Type::Sqrt: + ret.next = buildSqrt(ins); + break; + + case CppInstruction::Type::Sin: + ret.next = buildSin(ins); + break; + + case CppInstruction::Type::Cos: + ret.next = buildCos(ins); + break; + + case CppInstruction::Type::Tan: + ret.next = buildTan(ins); + break; + + case CppInstruction::Type::Asin: + ret.next = buildAsin(ins); + break; + + case CppInstruction::Type::Acos: + ret.next = buildAcos(ins); + break; + + case CppInstruction::Type::Atan: + ret.next = buildAtan(ins); + break; + + case CppInstruction::Type::Ln: + ret.next = buildLn(ins); + break; + + case CppInstruction::Type::Log10: + ret.next = buildLog10(ins); + break; + + case CppInstruction::Type::Exp: + ret.next = buildExp(ins); + break; + + case CppInstruction::Type::Exp10: + ret.next = buildExp10(ins); + break; + + default: + ret.match = false; + break; + } + + return ret; +} + +CppInstruction *Math::buildAdd(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildSub(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildMul(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildDiv(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildRandom(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildRandomInt(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildMod(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildRound(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildAbs(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildFloor(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildCeil(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildSqrt(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildSin(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildCos(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildTan(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildAsin(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildAcos(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildAtan(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildLn(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildLog10(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildExp(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Math::buildExp10(CppInstruction *ins) +{ + return ins->getNext(); +} diff --git a/src/engine/internal/codegen/cpp/instructions/math.h b/src/engine/internal/codegen/cpp/instructions/math.h new file mode 100644 index 000000000..d5685b545 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/math.h @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "instructiongroup.h" + +namespace libscratchcpp::cppins +{ + +class Math : public InstructionGroup +{ + public: + using InstructionGroup::InstructionGroup; + + ProcessResult process(CppInstruction *ins) override; + + private: + CppInstruction *buildAdd(CppInstruction *ins); + CppInstruction *buildSub(CppInstruction *ins); + CppInstruction *buildMul(CppInstruction *ins); + CppInstruction *buildDiv(CppInstruction *ins); + CppInstruction *buildRandom(CppInstruction *ins); + CppInstruction *buildRandomInt(CppInstruction *ins); + CppInstruction *buildMod(CppInstruction *ins); + CppInstruction *buildRound(CppInstruction *ins); + CppInstruction *buildAbs(CppInstruction *ins); + CppInstruction *buildFloor(CppInstruction *ins); + CppInstruction *buildCeil(CppInstruction *ins); + CppInstruction *buildSqrt(CppInstruction *ins); + CppInstruction *buildSin(CppInstruction *ins); + CppInstruction *buildCos(CppInstruction *ins); + CppInstruction *buildTan(CppInstruction *ins); + CppInstruction *buildAsin(CppInstruction *ins); + CppInstruction *buildAcos(CppInstruction *ins); + CppInstruction *buildAtan(CppInstruction *ins); + CppInstruction *buildLn(CppInstruction *ins); + CppInstruction *buildLog10(CppInstruction *ins); + CppInstruction *buildExp(CppInstruction *ins); + CppInstruction *buildExp10(CppInstruction *ins); +}; + +} // namespace libscratchcpp::cppins diff --git a/src/engine/internal/codegen/cpp/instructions/procedures.cpp b/src/engine/internal/codegen/cpp/instructions/procedures.cpp new file mode 100644 index 000000000..7c9e43e55 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/procedures.cpp @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include + +#include "procedures.h" +#include "../cppinstruction.h" + +using namespace libscratchcpp; +using namespace libscratchcpp::cppins; + +ProcessResult Procedures::process(CppInstruction *ins) +{ + ProcessResult ret(true, ins); + + switch (ins->type) { + case CppInstruction::Type::CallProcedure: + ret.next = buildCallProcedure(ins); + break; + + case CppInstruction::Type::ProcedureArg: + ret.next = buildProcedureArg(ins); + break; + + default: + ret.match = false; + break; + } + + return ret; +} + +CppInstruction *Procedures::buildCallProcedure(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Procedures::buildProcedureArg(CppInstruction *ins) +{ + return ins->getNext(); +} diff --git a/src/engine/internal/codegen/cpp/instructions/procedures.h b/src/engine/internal/codegen/cpp/instructions/procedures.h new file mode 100644 index 000000000..fa43dcbfd --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/procedures.h @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "instructiongroup.h" + +namespace libscratchcpp::cppins +{ + +class Procedures : public InstructionGroup +{ + public: + using InstructionGroup::InstructionGroup; + + ProcessResult process(CppInstruction *ins) override; + + private: + CppInstruction *buildCallProcedure(CppInstruction *ins); + CppInstruction *buildProcedureArg(CppInstruction *ins); +}; + +} // namespace libscratchcpp::cppins diff --git a/src/engine/internal/codegen/cpp/instructions/processresult.h b/src/engine/internal/codegen/cpp/instructions/processresult.h new file mode 100644 index 000000000..b058ad3da --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/processresult.h @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +namespace libscratchcpp +{ + +class CppInstruction; + +namespace cppins +{ + +// Result of group processing +struct ProcessResult +{ + ProcessResult(bool match, CppInstruction *next) : + match(match), + next(next) + { + } + + bool match = false; // whether the desired instruction was found + CppInstruction *next = nullptr; // next instruction (state) +}; + +} // namespace cppins +} // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/instructions/string.cpp b/src/engine/internal/codegen/cpp/instructions/string.cpp new file mode 100644 index 000000000..4d53a824f --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/string.cpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "string.h" +#include "../cppinstruction.h" + +using namespace libscratchcpp; +using namespace libscratchcpp::cppins; + +ProcessResult String::process(CppInstruction *ins) +{ + ProcessResult ret(true, ins); + + switch (ins->type) { + case CppInstruction::Type::StringConcat: + ret.next = buildStringConcat(ins); + break; + + case CppInstruction::Type::StringChar: + ret.next = buildStringChar(ins); + break; + + case CppInstruction::Type::StringLength: + ret.next = buildStringLength(ins); + break; + + default: + ret.match = false; + break; + } + + return ret; +} + +CppInstruction *String::buildStringConcat(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *String::buildStringChar(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *String::buildStringLength(CppInstruction *ins) +{ + return ins->getNext(); +} diff --git a/src/engine/internal/codegen/cpp/instructions/string.h b/src/engine/internal/codegen/cpp/instructions/string.h new file mode 100644 index 000000000..dd491be57 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/string.h @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "instructiongroup.h" + +namespace libscratchcpp::cppins +{ + +class String : public InstructionGroup +{ + public: + using InstructionGroup::InstructionGroup; + + ProcessResult process(CppInstruction *ins) override; + + private: + CppInstruction *buildStringConcat(CppInstruction *ins); + CppInstruction *buildStringChar(CppInstruction *ins); + CppInstruction *buildStringLength(CppInstruction *ins); +}; + +} // namespace libscratchcpp::cppins diff --git a/src/engine/internal/codegen/cpp/instructions/variables.cpp b/src/engine/internal/codegen/cpp/instructions/variables.cpp new file mode 100644 index 000000000..d9580476f --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/variables.cpp @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "variables.h" +#include "../cppinstruction.h" + +using namespace libscratchcpp; +using namespace libscratchcpp::cppins; + +ProcessResult Variables::process(CppInstruction *ins) +{ + ProcessResult ret(true, ins); + + switch (ins->type) { + case CppInstruction::Type::CreateLocalVariable: + ret.next = buildCreateLocalVariable(ins); + break; + + case CppInstruction::Type::WriteLocalVariable: + ret.next = buildWriteLocalVariable(ins); + break; + + case CppInstruction::Type::ReadLocalVariable: + ret.next = buildReadLocalVariable(ins); + break; + + case CppInstruction::Type::WriteVariable: + ret.next = buildWriteVariable(ins); + break; + + case CppInstruction::Type::ReadVariable: + ret.next = buildReadVariable(ins); + break; + + default: + ret.match = false; + break; + } + + return ret; +} + +CppInstruction *Variables::buildCreateLocalVariable(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Variables::buildWriteLocalVariable(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Variables::buildReadLocalVariable(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Variables::buildWriteVariable(CppInstruction *ins) +{ + return ins->getNext(); +} + +CppInstruction *Variables::buildReadVariable(CppInstruction *ins) +{ + return ins->getNext(); +} diff --git a/src/engine/internal/codegen/cpp/instructions/variables.h b/src/engine/internal/codegen/cpp/instructions/variables.h new file mode 100644 index 000000000..4572ffbe1 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/variables.h @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "instructiongroup.h" + +namespace libscratchcpp::cppins +{ + +class Variables : public InstructionGroup +{ + public: + using InstructionGroup::InstructionGroup; + + ProcessResult process(CppInstruction *ins) override; + + private: + CppInstruction *buildCreateLocalVariable(CppInstruction *ins); + CppInstruction *buildWriteLocalVariable(CppInstruction *ins); + CppInstruction *buildReadLocalVariable(CppInstruction *ins); + CppInstruction *buildWriteVariable(CppInstruction *ins); + CppInstruction *buildReadVariable(CppInstruction *ins); +}; + +} // namespace libscratchcpp::cppins From 09c012bcc3f16c6a3ff4372356ad7f85d5a7dbd3 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:25:15 +0100 Subject: [PATCH 02/18] CppCodeBuilder: Process instructions --- src/engine/internal/codegen/cpp/cppcodebuilder.cpp | 6 ++++++ src/engine/internal/codegen/cpp/cppcodebuilder.h | 5 ++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp index 482e0e2af..47549a959 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp @@ -18,6 +18,12 @@ CppCodeBuilder::CppCodeBuilder(CppCompilerContext *ctx, BlockPrototype *procedur std::shared_ptr CppCodeBuilder::build() { + // Build recorded instructions + CppInstruction *ins = m_instructions.first(); + + while (ins) + ins = m_instructionBuilder.process(ins); + return std::make_shared(m_ctx); } diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.h b/src/engine/internal/codegen/cpp/cppcodebuilder.h index ef08d8245..54a19ef5b 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.h +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.h @@ -3,13 +3,14 @@ #pragma once #include "../icodebuilder.h" +#include "cppinstructionlist.h" +#include "instructions/instructionbuilder.h" namespace libscratchcpp { class CppCompilerContext; class CppValue; -class CppInstruction; class CppCodeBuilder : public ICodeBuilder { @@ -114,6 +115,8 @@ class CppCodeBuilder : public ICodeBuilder std::vector> m_values; std::vector> m_localVars; + CppInstructionList m_instructions; + cppins::InstructionBuilder m_instructionBuilder; }; } // namespace libscratchcpp From fad80955eb33eaea8565c300287bf82b90e86eb1 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:29:26 +0100 Subject: [PATCH 03/18] CppCodeBuilder: Add code analyzer --- .../internal/codegen/cpp/cppcodebuilder.cpp | 27 ++++++++++++++++++- .../internal/codegen/cpp/cppcodebuilder.h | 3 +++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp index 47549a959..dd6cb9b70 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp @@ -1,9 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include #include "cppcodebuilder.h" +#include "cppcompilercontext.h" #include "cppexecutablecode.h" +#include "cppinstruction.h" #include "cppconstant.h" #include "../typeutils.h" @@ -12,12 +15,34 @@ using namespace libscratchcpp; CppCodeBuilder::CppCodeBuilder(CppCompilerContext *ctx, BlockPrototype *procedurePrototype, Compiler::CodeType codeType) : m_ctx(ctx), m_procedurePrototype(procedurePrototype), - m_codeType(codeType) + m_codeType(codeType), + m_codeAnalyzer(ctx) { } std::shared_ptr CppCodeBuilder::build() { + 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) { + return ins->type == CppInstruction::Type::Yield || (ins->type == CppInstruction::Type::CallProcedure && ins->procedurePrototype && !ins->procedurePrototype->warp()); + })) { + m_warp = true; + } + + // Only create coroutines in scripts + if (m_codeType != Compiler::CodeType::Script) + m_warp = true; + } + + if (m_warp) { +#ifdef ENABLE_CODE_ANALYZER + // Analyze the script (type analysis, optimizations, etc.) + // NOTE: Do this only for warp scripts + m_codeAnalyzer.analyzeScript(m_instructions); +#endif + } + // Build recorded instructions CppInstruction *ins = m_instructions.first(); diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.h b/src/engine/internal/codegen/cpp/cppcodebuilder.h index 54a19ef5b..af8e3e973 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.h +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.h @@ -5,6 +5,7 @@ #include "../icodebuilder.h" #include "cppinstructionlist.h" #include "instructions/instructionbuilder.h" +#include "../codeanalyzer.h" namespace libscratchcpp { @@ -117,6 +118,8 @@ class CppCodeBuilder : public ICodeBuilder std::vector> m_localVars; CppInstructionList m_instructions; cppins::InstructionBuilder m_instructionBuilder; + CodeAnalyzer m_codeAnalyzer; + bool m_warp = false; }; } // namespace libscratchcpp From be2acaca05539cffa448f4362a61b10fc62abce9 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:56:22 +0100 Subject: [PATCH 04/18] CppCodeBuilder: Populate instruction list --- .../internal/codegen/cpp/cppcodebuilder.cpp | 237 +++++++++++++++--- .../internal/codegen/cpp/cppcodebuilder.h | 11 + 2 files changed, 209 insertions(+), 39 deletions(-) diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp index dd6cb9b70..ec81f255b 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp @@ -1,7 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 #include -#include #include "cppcodebuilder.h" #include "cppcompilercontext.h" @@ -54,17 +53,41 @@ std::shared_ptr CppCodeBuilder::build() CompilerValue *CppCodeBuilder::addFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) { - return addConstValue(Value()); + assert(argTypes.size() == args.size()); + + auto ins = std::make_shared(CppInstruction::Type::FunctionCall, m_loopCondition); + ins->functionName = functionName; + + for (size_t i = 0; i < args.size(); i++) + ins->args.push_back({ argTypes[i], dynamic_cast(args[i]) }); + + m_instructions.addInstruction(ins); + + if (returnType != Compiler::StaticType::Void) { + auto reg = std::make_shared(returnType); + + if (TypeUtils::isSingleType(returnType)) + reg->isRawValue = true; + + ins->setFunctionReturnReg(reg.get()); + return addValue(reg, ins); + } + + return nullptr; } CompilerValue *CppCodeBuilder::addTargetFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) { - return addConstValue(Value()); + CompilerValue *ret = addFunctionCall(functionName, returnType, argTypes, args); + m_instructions.last()->functionTargetArg = true; + return ret; } CompilerValue *CppCodeBuilder::addFunctionCallWithCtx(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) { - return addConstValue(Value()); + CompilerValue *ret = addFunctionCall(functionName, returnType, argTypes, args); + m_instructions.last()->functionCtxArg = true; + return ret; } CompilerConstant *CppCodeBuilder::addConstValue(const Value &value) @@ -76,212 +99,241 @@ CompilerConstant *CppCodeBuilder::addConstValue(const Value &value) CompilerValue *CppCodeBuilder::addStringChar(CompilerValue *string, CompilerValue *index) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::StringChar, Compiler::StaticType::String, { Compiler::StaticType::String, Compiler::StaticType::Number }, { string, index }); } CompilerValue *CppCodeBuilder::addStringLength(CompilerValue *string) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::StringLength, Compiler::StaticType::Number, Compiler::StaticType::String, { string }); } CompilerValue *CppCodeBuilder::addLoopIndex() { - return addConstValue(Value()); + return createOp(CppInstruction::Type::LoopIndex, Compiler::StaticType::Number, {}, {}); } CompilerValue *CppCodeBuilder::addLocalVariableValue(CompilerLocalVariable *variable) { + // TODO: Add support for local variables return addConstValue(Value()); } CompilerValue *CppCodeBuilder::addVariableValue(Variable *variable) { + // TODO: Add support for variables return addConstValue(Value()); } CompilerValue *CppCodeBuilder::addListContents(List *list) { + // TODO: Add support for lists return addConstValue(Value()); } CompilerValue *CppCodeBuilder::addListItem(List *list, CompilerValue *index) { + // TODO: Add support for lists return addConstValue(Value()); } CompilerValue *CppCodeBuilder::addListItemIndex(List *list, CompilerValue *item) { + // TODO: Add support for lists return addConstValue(Value()); } CompilerValue *CppCodeBuilder::addListContains(List *list, CompilerValue *item) { + // TODO: Add support for lists return addConstValue(Value()); } CompilerValue *CppCodeBuilder::addListSize(List *list) { + // TODO: Add support for lists return addConstValue(Value()); } CompilerValue *CppCodeBuilder::addProcedureArgument(const std::string &name) { - return addConstValue(Value()); + if (!m_procedurePrototype) + return addConstValue(Value()); + + const auto &argNames = m_procedurePrototype->argumentNames(); + auto it = std::find(argNames.begin(), argNames.end(), name); + + if (it == argNames.end()) { + std::cout << "warning: could not find argument '" << name << "' in custom block '" << m_procedurePrototype->procCode() << "'" << std::endl; + return addConstValue(Value()); + } + + const auto index = it - argNames.begin(); + const Compiler::StaticType type = getProcedureArgType(m_procedurePrototype->argumentTypes()[index]); + auto ins = std::make_shared(CppInstruction::Type::ProcedureArg, m_loopCondition); + auto ret = std::make_shared(type); + ret->isRawValue = (type != Compiler::StaticType::Unknown); + ins->setFunctionReturnReg(ret.get()); + ins->procedureArgIndex = index; + + m_instructions.addInstruction(ins); + return addValue(ret, ins); } CompilerValue *CppCodeBuilder::createAdd(CompilerValue *operand1, CompilerValue *operand2) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Add, Compiler::StaticType::Number, Compiler::StaticType::Number, { operand1, operand2 }); } CompilerValue *CppCodeBuilder::createSub(CompilerValue *operand1, CompilerValue *operand2) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Sub, Compiler::StaticType::Number, Compiler::StaticType::Number, { operand1, operand2 }); } CompilerValue *CppCodeBuilder::createMul(CompilerValue *operand1, CompilerValue *operand2) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Mul, Compiler::StaticType::Number, Compiler::StaticType::Number, { operand1, operand2 }); } CompilerValue *CppCodeBuilder::createDiv(CompilerValue *operand1, CompilerValue *operand2) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Div, Compiler::StaticType::Number, Compiler::StaticType::Number, { operand1, operand2 }); } CompilerValue *CppCodeBuilder::createRandom(CompilerValue *from, CompilerValue *to) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Random, Compiler::StaticType::Number, Compiler::StaticType::Unknown, { from, to }); } CompilerValue *CppCodeBuilder::createRandomInt(CompilerValue *from, CompilerValue *to) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::RandomInt, Compiler::StaticType::Number, Compiler::StaticType::Number, { from, to }); } CompilerValue *CppCodeBuilder::createCmpEQ(CompilerValue *operand1, CompilerValue *operand2) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::CmpEQ, Compiler::StaticType::Bool, Compiler::StaticType::Number, { operand1, operand2 }); } CompilerValue *CppCodeBuilder::createCmpGT(CompilerValue *operand1, CompilerValue *operand2) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::CmpGT, Compiler::StaticType::Bool, Compiler::StaticType::Number, { operand1, operand2 }); } CompilerValue *CppCodeBuilder::createCmpLT(CompilerValue *operand1, CompilerValue *operand2) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::CmpLT, Compiler::StaticType::Bool, Compiler::StaticType::Number, { operand1, operand2 }); } CompilerValue *CppCodeBuilder::createStrCmpEQ(CompilerValue *string1, CompilerValue *string2, bool caseSensitive) { - return addConstValue(Value()); + return createOp(caseSensitive ? CppInstruction::Type::StrCmpEQCS : CppInstruction::Type::StrCmpEQCI, Compiler::StaticType::Bool, Compiler::StaticType::String, { string1, string2 }); } CompilerValue *CppCodeBuilder::createAnd(CompilerValue *operand1, CompilerValue *operand2) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::And, Compiler::StaticType::Bool, Compiler::StaticType::Bool, { operand1, operand2 }); } CompilerValue *CppCodeBuilder::createOr(CompilerValue *operand1, CompilerValue *operand2) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Or, Compiler::StaticType::Bool, Compiler::StaticType::Bool, { operand1, operand2 }); } CompilerValue *CppCodeBuilder::createNot(CompilerValue *operand) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Not, Compiler::StaticType::Bool, Compiler::StaticType::Bool, { operand }); } CompilerValue *CppCodeBuilder::createMod(CompilerValue *num1, CompilerValue *num2) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Mod, Compiler::StaticType::Number, Compiler::StaticType::Number, { num1, num2 }); } CompilerValue *CppCodeBuilder::createRound(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Round, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createAbs(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Abs, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createFloor(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Floor, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createCeil(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Ceil, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createSqrt(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Sqrt, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createSin(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Sin, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createCos(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Cos, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createTan(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Tan, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createAsin(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Asin, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createAcos(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Acos, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createAtan(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Atan, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createLn(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Ln, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createLog10(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Log10, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createExp(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Exp, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createExp10(CompilerValue *num) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::Exp10, Compiler::StaticType::Number, Compiler::StaticType::Number, { num }); } CompilerValue *CppCodeBuilder::createStringConcat(CompilerValue *string1, CompilerValue *string2) { - return addConstValue(Value()); + return createOp(CppInstruction::Type::StringConcat, Compiler::StaticType::String, Compiler::StaticType::String, { string1, string2 }); } CompilerValue *CppCodeBuilder::createSelect(CompilerValue *cond, CompilerValue *trueValue, CompilerValue *falseValue, Compiler::StaticType valueType) { - return addConstValue(Value()); + CppValue *ret = createOp(CppInstruction::Type::Select, valueType, { Compiler::StaticType::Bool, valueType, valueType }, { cond, trueValue, falseValue }); + ret->isRawValue = TypeUtils::isSingleType(valueType); + return ret; } CompilerLocalVariable *CppCodeBuilder::createLocalVariable(Compiler::StaticType type) @@ -295,86 +347,149 @@ CompilerLocalVariable *CppCodeBuilder::createLocalVariable(Compiler::StaticType void CppCodeBuilder::createLocalVariableWrite(CompilerLocalVariable *variable, CompilerValue *value) { + // TODO: Add support for local variables } void CppCodeBuilder::createVariableWrite(Variable *variable, CompilerValue *value) { + // TODO: Add support for variables } void CppCodeBuilder::createListClear(List *list) { + // TODO: Add support for lists } void CppCodeBuilder::createListRemove(List *list, CompilerValue *index) { + // TODO: Add support for lists } void CppCodeBuilder::createListAppend(List *list, CompilerValue *item) { + // TODO: Add support for lists } void CppCodeBuilder::createListInsert(List *list, CompilerValue *index, CompilerValue *item) { + // TODO: Add support for lists } void CppCodeBuilder::createListReplace(List *list, CompilerValue *index, CompilerValue *item) { + // TODO: Add support for lists } void CppCodeBuilder::beginIfStatement(CompilerValue *cond) { + auto ins = std::make_shared(CppInstruction::Type::BeginIf, m_loopCondition); + ins->args.push_back({ Compiler::StaticType::Bool, dynamic_cast(cond) }); + m_instructions.addInstruction(ins); } void CppCodeBuilder::beginElseBranch() { + auto ins = std::make_shared(CppInstruction::Type::BeginElse, m_loopCondition); + m_instructions.addInstruction(ins); } void CppCodeBuilder::endIf() { + auto ins = std::make_shared(CppInstruction::Type::EndIf, m_loopCondition); + m_instructions.addInstruction(ins); } void CppCodeBuilder::beginRepeatLoop(CompilerValue *count) { + assert(!m_loopCondition); + + auto ins = std::make_shared(CppInstruction::Type::BeginRepeatLoop, m_loopCondition); + ins->args.push_back({ Compiler::StaticType::Number, dynamic_cast(count) }); + m_instructions.addInstruction(ins); } void CppCodeBuilder::beginWhileLoop(CompilerValue *cond) { + assert(m_loopCondition); + m_loopCondition = false; + + auto ins = std::make_shared(CppInstruction::Type::BeginWhileLoop, m_loopCondition); + ins->args.push_back({ Compiler::StaticType::Bool, dynamic_cast(cond) }); + m_instructions.addInstruction(ins); } void CppCodeBuilder::beginRepeatUntilLoop(CompilerValue *cond) { + assert(m_loopCondition); + m_loopCondition = false; + + auto ins = std::make_shared(CppInstruction::Type::BeginRepeatUntilLoop, m_loopCondition); + ins->args.push_back({ Compiler::StaticType::Bool, dynamic_cast(cond) }); + m_instructions.addInstruction(ins); } void CppCodeBuilder::beginLoopCondition() { + assert(!m_loopCondition); + + auto ins = std::make_shared(CppInstruction::Type::BeginLoopCondition, m_loopCondition); + m_instructions.addInstruction(ins); + m_loopCondition = true; } void CppCodeBuilder::endLoop() { + if (!m_warp) { + auto ins = std::make_shared(CppInstruction::Type::Yield, m_loopCondition); + m_instructions.addInstruction(ins); + } + + auto ins = std::make_shared(CppInstruction::Type::EndLoop, m_loopCondition); + m_instructions.addInstruction(ins); } void CppCodeBuilder::yield() { + auto ins = std::make_shared(CppInstruction::Type::Yield, m_loopCondition); + m_instructions.addInstruction(ins); } void CppCodeBuilder::createStop() { + auto ins = std::make_shared(CppInstruction::Type::Stop, m_loopCondition); + m_instructions.addInstruction(ins); } void CppCodeBuilder::createThreadStop() { + auto ins = std::make_shared(CppInstruction::Type::ThreadStop, m_loopCondition); + m_instructions.addInstruction(ins); } void CppCodeBuilder::invalidateTarget() { + auto ins = std::make_shared(CppInstruction::Type::InvalidateTarget, m_loopCondition); + m_instructions.addInstruction(ins); } void CppCodeBuilder::createProcedureCall(BlockPrototype *prototype, const Compiler::Args &args) { + assert(prototype); + assert(prototype->argumentTypes().size() == args.size()); + const auto &procedureArgs = prototype->argumentTypes(); + Compiler::ArgTypes types; + + for (BlockPrototype::ArgType type : procedureArgs) + types.push_back(getProcedureArgType(type)); + + CppInstruction ins(CppInstruction::Type::CallProcedure, m_loopCondition); + ins.procedurePrototype = prototype; + createOp(ins, Compiler::StaticType::Void, types, args); } void CppCodeBuilder::createPrint(CompilerValue *string) { + createOp(CppInstruction::Type::Print, Compiler::StaticType::Void, Compiler::StaticType::String, { string }); } CppValue *CppCodeBuilder::addValue(std::shared_ptr value, std::shared_ptr ins) @@ -383,3 +498,47 @@ CppValue *CppCodeBuilder::addValue(std::shared_ptr value, std::shared_ m_values.push_back(value); return value.get(); } + +Compiler::StaticType CppCodeBuilder::getProcedureArgType(BlockPrototype::ArgType type) +{ + return type == BlockPrototype::ArgType::Bool ? Compiler::StaticType::Bool : Compiler::StaticType::Unknown; +} + +CppValue *CppCodeBuilder::createOp(CppInstruction::Type type, Compiler::StaticType retType, Compiler::StaticType argType, const Compiler::Args &args) +{ + return createOp({ type, m_loopCondition }, retType, argType, args); +} + +CppValue *CppCodeBuilder::createOp(CppInstruction::Type type, Compiler::StaticType retType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) +{ + return createOp({ type, m_loopCondition }, retType, argTypes, args); +} + +CppValue *CppCodeBuilder::createOp(const CppInstruction &ins, Compiler::StaticType retType, Compiler::StaticType argType, const Compiler::Args &args) +{ + std::vector types; + types.reserve(args.size()); + + for (size_t i = 0; i < args.size(); i++) + types.push_back(argType); + + return createOp(ins, retType, types, args); +} + +CppValue *CppCodeBuilder::createOp(const CppInstruction &ins, Compiler::StaticType retType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) +{ + auto createdIns = std::make_shared(ins); + m_instructions.addInstruction(createdIns); + + for (size_t i = 0; i < args.size(); i++) + createdIns->args.push_back({ argTypes[i], dynamic_cast(args[i]) }); + + if (retType != Compiler::StaticType::Void) { + auto ret = std::make_shared(retType); + ret->isRawValue = true; + createdIns->functionReturnReg = ret.get(); + return addValue(ret, createdIns); + } + + return nullptr; +} diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.h b/src/engine/internal/codegen/cpp/cppcodebuilder.h index af8e3e973..6808fea5c 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.h +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.h @@ -2,7 +2,10 @@ #pragma once +#include + #include "../icodebuilder.h" +#include "cppinstruction.h" #include "cppinstructionlist.h" #include "instructions/instructionbuilder.h" #include "../codeanalyzer.h" @@ -110,6 +113,13 @@ class CppCodeBuilder : public ICodeBuilder private: CppValue *addValue(std::shared_ptr value, std::shared_ptr ins); + Compiler::StaticType getProcedureArgType(BlockPrototype::ArgType type); + + CppValue *createOp(CppInstruction::Type type, Compiler::StaticType retType, Compiler::StaticType argType, const Compiler::Args &args); + CppValue *createOp(CppInstruction::Type type, Compiler::StaticType retType, const Compiler::ArgTypes &argTypes = {}, const Compiler::Args &args = {}); + CppValue *createOp(const CppInstruction &ins, Compiler::StaticType retType, Compiler::StaticType argType, const Compiler::Args &args); + CppValue *createOp(const CppInstruction &ins, Compiler::StaticType retType, const Compiler::ArgTypes &argTypes = {}, const Compiler::Args &args = {}); + CppCompilerContext *m_ctx = nullptr; BlockPrototype *m_procedurePrototype = nullptr; Compiler::CodeType m_codeType = Compiler::CodeType::Script; @@ -120,6 +130,7 @@ class CppCodeBuilder : public ICodeBuilder cppins::InstructionBuilder m_instructionBuilder; CodeAnalyzer m_codeAnalyzer; bool m_warp = false; + bool m_loopCondition = false; // whether we're currently compiling a loop condition }; } // namespace libscratchcpp From 15e4aca5ccb1a188de2e3ddb09485d47a6633e44 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:48:15 +0100 Subject: [PATCH 05/18] Add initial CppCodeBuilder implementation --- .../internal/codegen/cpp/CMakeLists.txt | 9 + .../internal/codegen/cpp/cppcodegenerator.cpp | 396 ++++++++++++++++++ .../internal/codegen/cpp/cppcodegenerator.h | 86 ++++ .../internal/codegen/cpp/cppcodestream.h | 31 ++ .../internal/codegen/cpp/cppconstidentifier.h | 27 ++ .../internal/codegen/cpp/cppfunctioncall.h | 77 ++++ .../internal/codegen/cpp/cppidentifier.h | 65 +++ .../internal/codegen/cpp/cppnamedidentifier.h | 29 ++ src/engine/internal/codegen/cpp/cppswitch.h | 80 ++++ src/engine/internal/codegen/cpp/cpptypeinfo.h | 18 + 10 files changed, 818 insertions(+) create mode 100644 src/engine/internal/codegen/cpp/cppcodegenerator.cpp create mode 100644 src/engine/internal/codegen/cpp/cppcodegenerator.h create mode 100644 src/engine/internal/codegen/cpp/cppcodestream.h create mode 100644 src/engine/internal/codegen/cpp/cppconstidentifier.h create mode 100644 src/engine/internal/codegen/cpp/cppfunctioncall.h create mode 100644 src/engine/internal/codegen/cpp/cppidentifier.h create mode 100644 src/engine/internal/codegen/cpp/cppnamedidentifier.h create mode 100644 src/engine/internal/codegen/cpp/cppswitch.h create mode 100644 src/engine/internal/codegen/cpp/cpptypeinfo.h diff --git a/src/engine/internal/codegen/cpp/CMakeLists.txt b/src/engine/internal/codegen/cpp/CMakeLists.txt index 03d4b1289..b3f56a22a 100644 --- a/src/engine/internal/codegen/cpp/CMakeLists.txt +++ b/src/engine/internal/codegen/cpp/CMakeLists.txt @@ -12,6 +12,15 @@ target_sources(scratchcpp cppconstant.h cppcodebuilder.cpp cppcodebuilder.h + cppcodegenerator.cpp + cppcodegenerator.h + cppcodestream.h + cpptypeinfo.h + cppidentifier.h + cppconstidentifier.h + cppnamedidentifier.h + cppfunctioncall.h + cppswitch.h ) add_subdirectory(instructions) diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp new file mode 100644 index 000000000..803375037 --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -0,0 +1,396 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include + +#include "cppcodegenerator.h" +#include "cppfunctioncall.h" +#include "cppvalue.h" +#include "cppconstidentifier.h" +#include "../typeutils.h" + +using namespace libscratchcpp; + +const std::unordered_map CppCodeGenerator::m_valueTypeMap = { + { Compiler::StaticType::Number, CppIdentifier::Type::Double }, + { Compiler::StaticType::Bool, CppIdentifier::Type::Bool }, + { Compiler::StaticType::String, CppIdentifier::Type::StringPtr }, + { Compiler::StaticType::Pointer, CppIdentifier::Type::Pointer } +}; + +const std::unordered_map CppCodeGenerator::m_headers = { + { Header::Limits, "" }, + { Header::Value, "" }, + { Header::ValueData, "" }, + { Header::ValueFunctions, "" }, + { Header::ExecutionContext, "" } +}; + +const std::unordered_map CppCodeGenerator::m_funcParams = { + { FuncParam::Context, CppNamedIdentifier(CppIdentifier::Type::ContextPointer, "ctx", false) }, + { FuncParam::Target, CppNamedIdentifier(CppIdentifier::Type::TargetPointer, "target", false) }, + { FuncParam::TargetVariables, CppNamedIdentifier(CppIdentifier::Type::VariablePointerArray, "targetVariables", false) }, + { FuncParam::TargetLists, CppNamedIdentifier(CppIdentifier::Type::ListPointerArray, "targetLists", false) } +}; + +CppCodeGenerator::CppCodeGenerator() : + m_stringArray(CppIdentifier::Type::StringPtrArray, "stringArray", true) +{ +} + +CppCodeGenerator::~CppCodeGenerator() +{ + std::cout << m_codeStream.code() << std::endl; +} + +const CppIdentifier *CppCodeGenerator::castValue(CppValue *value, Compiler::StaticType targetType) +{ + // TODO: Implement this + if (value->isConst()) { + if (!TypeUtils::isSingleType(targetType)) + return createValue(value); + else + return castConstValue(value->constValue(), targetType); + } + + if (value->isRawValue) + return castRawValue(value, targetType); + + return getNamedIdentifier(value, m_valueTypeMap.at(targetType), "castValue", false); +} + +void CppCodeGenerator::createCall(const std::string &name, bool ctxArg, bool targetArg, const std::vector &args) +{ + m_codeStream.beginLine(); + createCall(name, nullptr, ctxArg, targetArg, args); + m_codeStream.endLine(); +} + +void CppCodeGenerator::createCall(const std::string &name, CppIdentifier::Type retType, CppValue *retValue, bool ctxArg, bool targetArg, const std::vector &args) +{ + if (identifierExists(retValue)) { + throw std::runtime_error("assigning to existing return value identifier when calling function: " + name); + } + + const CppNamedIdentifier *strRet = nullptr; + + if (retType == CppIdentifier::Type::StringPtr) { + // Strings are returned through an output parameter + includeHeader(Header::ExecutionContext); + strRet = addStringAlloca(); + } + + m_codeStream.beginLine(); + + if (retType != CppIdentifier::Type::StringPtr) { + m_codeStream.addToLine(CppIdentifier::typeString(retType)); + m_codeStream.addToLine(" "); + m_codeStream.addToLine(getNamedIdentifier(retValue, retType, "ret", false)->name); + m_codeStream.addToLine(" = "); + } + + createCall(name, strRet, ctxArg, targetArg, args); + m_codeStream.endLine(); +} + +void CppCodeGenerator::createCall(const std::string &name, const CppNamedIdentifier *strRet, bool ctxArg, bool targetArg, const std::vector &args) +{ + CppFunctionCall call(m_codeStream, name); + + if (strRet) + call.param(strRet); + + if (ctxArg) + call.param(getParam(FuncParam::Context)); + + if (targetArg) + call.param(getParam(FuncParam::Target)); + + for (const CppIdentifier *arg : args) { + try { + 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); + } + } catch (std::exception &e) { + throw std::runtime_error("error when creating call of function '" + name + "': " + e.what()); + } + } + + call.close(); +} + +const CppNamedIdentifier *CppCodeGenerator::getParam(FuncParam param) +{ + return &m_funcParams.at(param); +} + +const CppIdentifier *CppCodeGenerator::getIdentifier(CppValue *value) +{ + auto it = m_identifiers.find(value); + + if (it == m_identifiers.cend()) { + throw std::runtime_error("undefined identifier"); + } + + return it->second.get(); +} + +const CppNamedIdentifier *CppCodeGenerator::getNamedIdentifier(CppValue *value, CppIdentifier::Type type, const std::string &name, bool isMutable) +{ + auto it = m_identifiers.find(value); + + if (it == m_identifiers.cend()) { + auto identifier = std::make_shared(type, getNewIdentifierName(name), isMutable); + m_identifiers[value] = identifier; + return identifier.get(); + } else { + auto identifier = std::dynamic_pointer_cast(it->second); + + if (!identifier) { + throw std::runtime_error("specified value does not have a named identifier"); + } + + return identifier.get(); + } +} + +const CppNamedIdentifier *CppCodeGenerator::createNamedIdentifier(CppIdentifier::Type type, const std::string &name, bool isMutable) +{ + auto identifier = std::make_shared(type, getNewIdentifierName(name), isMutable); + m_internalIdentifiers.push_back(identifier); + return identifier.get(); +} + +std::string CppCodeGenerator::getNewIdentifierName(const std::string &name) +{ + auto it = m_identifierNameCounts.find(name); + + if (it == m_identifierNameCounts.cend()) { + m_identifierNameCounts[name] = 0; + return name + "0"; + } else { + return name + std::to_string(++it->second); + } +} + +void CppCodeGenerator::includeHeader(Header header) +{ + m_includedHeaders.insert(header); +} + +const CppNamedIdentifier *CppCodeGenerator::addStringAlloca() +{ + auto identifier = std::make_shared(CppIdentifier::Type::StringPtr, getNewIdentifierName("string"), true); + m_strings.push_back(identifier); + + m_codeStream.beginLine(); + m_codeStream.addToLine(CppIdentifier::typeString(CppIdentifier::Type::StringPtr)); + m_codeStream.addToLine(" "); + m_codeStream.addToLine(identifier->name); + m_codeStream.addToLine(" = "); + addArrayElement(&m_stringArray, m_strings.size() - 1); + m_codeStream.endLine(); + + return identifier.get(); +} + +void CppCodeGenerator::addArrayElement(const CppNamedIdentifier *array, size_t index) +{ + if (!array->isArray()) { + throw std::runtime_error("'" + array->name + "' is not an array"); + } + + m_codeStream.addToLine(array->name); + m_codeStream.addToLine("["); + m_codeStream.addToLine(std::to_string(index)); + m_codeStream.addToLine("]"); +} + +const CppConstIdentifier *CppCodeGenerator::castConstValue(const Value &value, Compiler::StaticType targetType) +{ + // TODO: Implement this + auto identifierType = m_valueTypeMap.at(TypeUtils::mapType(value.type())); + auto ret = std::make_shared(identifierType, value); + m_constants.push_back(ret); + return ret.get(); +} + +const CppNamedIdentifier *CppCodeGenerator::castRawValue(CppValue *value, Compiler::StaticType targetType) +{ + // TODO: Implement this + assert(value->isRawValue); + return getNamedIdentifier(value, m_valueTypeMap.at(targetType), "castRawValue", false); +} + +const CppNamedIdentifier *CppCodeGenerator::createValue(CppValue *value) +{ + const CppNamedIdentifier *identifier = getNamedIdentifier(value, CppIdentifier::Type::ValueData, "value", false); + + if (value->isConst()) { + includeHeader(Header::Value); + + // const Value constant(...); + const CppNamedIdentifier *valueObj = createNamedIdentifier(CppIdentifier::Type::Value, "constant", false); + m_codeStream.beginLine(); + m_codeStream.addToLine("const "); + m_codeStream.addToLine(valueObj->typeString()); + m_codeStream.addToLine(" "); + m_codeStream.addToLine(valueObj->name); + m_codeStream.addToLine("("); + m_codeStream.addToLine(toCppConstant(value->constValue())); + m_codeStream.addToLine(")"); + m_codeStream.addToLine(";"); + m_codeStream.endLine(); + + // const ValueData &value = constant.data(); + m_codeStream.beginLine(); + m_codeStream.addToLine("const "); + m_codeStream.addToLine(identifier->typeString()); + m_codeStream.addToLine(" &"); + m_codeStream.addToLine(identifier->name); + m_codeStream.addToLine(" = "); + + CppFunctionCall dataCall(m_codeStream, valueObj, "data"); + dataCall.close(); + + m_codeStream.addToLine(";"); + m_codeStream.endLine(); + } else if (value->isRawValue) { + includeHeader(Header::ValueData); + + // const ValueData value; + m_codeStream.beginLine(); + m_codeStream.addToLine("const "); + m_codeStream.addToLine(identifier->typeString()); + m_codeStream.addToLine(" "); + m_codeStream.addToLine(identifier->name); + m_codeStream.addToLine(";"); + m_codeStream.endLine(); + + // Store value + const CppIdentifier *valueIdentifier = getIdentifier(value); + + if (!valueIdentifier || !valueIdentifier->isNamed()) { + throw std::runtime_error("raw values must have a named identifier when creating a ValueData instance"); + } + + auto valueNamedIdentifier = static_cast(valueIdentifier); + m_codeStream.addToLine(identifier->name); + + switch (value->type()) { + case Compiler::StaticType::Number: + // value.numberValue = rawValue; + m_codeStream.addToLine(".numberValue = "); + break; + + case Compiler::StaticType::Bool: + // value.boolValue = rawValue; + m_codeStream.addToLine(".boolValue = "); + break; + + case Compiler::StaticType::String: + // value.stringValue = rawValue; + m_codeStream.addToLine(".stringValue = "); + break; + + case Compiler::StaticType::Pointer: + // value.pointerValue = rawValue; + m_codeStream.addToLine(".pointerValue = "); + break; + + default: + assert(false); + break; + } + + m_codeStream.addToLine(valueNamedIdentifier->name); + m_codeStream.addToLine(";"); + m_codeStream.endLine(); + } + + return identifier; +} + +std::string CppCodeGenerator::toCppConstant(const Value &value) +{ + switch (value.type()) { + case ValueType::Number: + return toCppDouble(value.toDouble()); + + case ValueType::Bool: + return value.toString(); + break; + + case ValueType::String: + return "\"" + escapeCppString(value.toString()) + "\""; + + default: + throw std::runtime_error("unsupported constant type"); + } +} + +std::string CppCodeGenerator::toCppDouble(double value) +{ + includeHeader(Header::Limits); + + if (std::isnan(value)) + return "std::numeric_limits::quiet_NaN()"; + + if (std::isinf(value)) + return value > 0 ? "std::numeric_limits::infinity()" : "-std::numeric_limits::infinity()"; + + // Shortest round-trip representation + std::ostringstream ss; + ss << std::setprecision(std::numeric_limits::max_digits10) << value; + std::string s = ss.str(); + + // Ensure it parses as double, not int (e.g. "1" -> "1.0") + if (s.find_first_of(".eEnN") == std::string::npos) + s += ".0"; + + return s; +} + +std::string CppCodeGenerator::escapeCppString(const std::string &str) +{ + std::string out; + out.reserve(str.size() + 8); + + for (unsigned char c : str) { + switch (c) { + case '\\': + out += "\\\\"; + break; + case '"': + out += "\\\""; + break; + case '\n': + out += "\\n"; + break; + case '\r': + out += "\\r"; + break; + case '\t': + out += "\\t"; + break; + case '\0': + out += "\\0"; + break; + default: + if (c < 0x20 || c == 0x7f) { + // Control characters: octal escape (fixed 3 digits so a + // following digit can't extend the escape sequence) + char buf[5]; + std::snprintf(buf, sizeof(buf), "\\%03o", c); + out += buf; + } else { + out += static_cast(c); + } + } + } + + return out; +} diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.h b/src/engine/internal/codegen/cpp/cppcodegenerator.h new file mode 100644 index 000000000..00b66e04d --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.h @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include +#include + +#include "cppnamedidentifier.h" +#include "cppconstidentifier.h" +#include "cppcodestream.h" + +namespace libscratchcpp +{ + +class CppValue; + +class CppCodeGenerator +{ + public: + CppCodeGenerator(); + ~CppCodeGenerator(); + + inline CppIdentifier::Type getType(Compiler::StaticType type) const { return m_valueTypeMap.at(type); } + + const CppIdentifier *castValue(CppValue *value, Compiler::StaticType targetType); + + 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); + + private: + enum class Header + { + Limits, + Value, + ValueData, + ValueFunctions, + ExecutionContext + }; + + enum class FuncParam + { + Context, + Target, + TargetVariables, + TargetLists + }; + + void createCall(const std::string &name, const CppNamedIdentifier *strRet, bool ctxArg, bool targetArg, const std::vector &args); + + const CppNamedIdentifier *getParam(FuncParam param); + const CppIdentifier *getIdentifier(CppValue *value); + const CppNamedIdentifier *getNamedIdentifier(CppValue *value, CppIdentifier::Type type, const std::string &name, bool isMutable); + const CppNamedIdentifier *createNamedIdentifier(CppIdentifier::Type type, const std::string &name, bool isMutable); + std::string getNewIdentifierName(const std::string &name); + void includeHeader(Header header); + + inline bool identifierExists(CppValue *value) const { return m_identifiers.find(value) != m_identifiers.cend(); } + + const CppNamedIdentifier *addStringAlloca(); + void addArrayElement(const CppNamedIdentifier *array, size_t index); + const CppConstIdentifier *castConstValue(const Value &value, Compiler::StaticType targetType); + const CppNamedIdentifier *castRawValue(CppValue *value, Compiler::StaticType targetType); + const CppNamedIdentifier *createValue(CppValue *value); + + std::string toCppConstant(const Value &value); + std::string toCppDouble(double value); + static std::string escapeCppString(const std::string &str); + + static const std::unordered_map m_valueTypeMap; + static const std::unordered_map m_headers; + static const std::unordered_map m_funcParams; + + CppCodeStream m_codeStream; + + std::unordered_map> m_identifiers; + std::unordered_map m_identifierNameCounts; + std::unordered_set
m_includedHeaders; + std::vector> m_internalIdentifiers; + std::vector> m_constants; + + CppNamedIdentifier m_stringArray; + std::vector> m_strings; +}; + +} // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/cppcodestream.h b/src/engine/internal/codegen/cpp/cppcodestream.h new file mode 100644 index 000000000..e8139537a --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppcodestream.h @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include + +namespace libscratchcpp +{ + +class CppCodeStream +{ + public: + inline void beginLine() { m_code << std::string(m_indentLevel * 4, ' '); } + inline void addToLine(const std::string &code) { m_code << code; } + inline void endLine() { m_code << "\n"; } + + inline void indent() { m_indentLevel++; }; + inline void dedent() { m_indentLevel--; }; + + inline std::string code() const + { + // TODO: Avoid copying the code + return m_code.str(); + }; + + private: + std::ostringstream m_code; + int m_indentLevel = 0; +}; + +} // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/cppconstidentifier.h b/src/engine/internal/codegen/cpp/cppconstidentifier.h new file mode 100644 index 000000000..44957514e --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppconstidentifier.h @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include + +#include "cppidentifier.h" + +namespace libscratchcpp +{ + +struct CppConstIdentifier : public CppIdentifier +{ + CppConstIdentifier() { } + + CppConstIdentifier(Type type, const Value &value) : + CppIdentifier(type), + value(value) + { + } + + virtual bool isConst() const override final { return true; } + + Value value; +}; + +} // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/cppfunctioncall.h b/src/engine/internal/codegen/cpp/cppfunctioncall.h new file mode 100644 index 000000000..6d4bf93f4 --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppfunctioncall.h @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "cppnamedidentifier.h" +#include "cppcodestream.h" + +namespace libscratchcpp +{ + +class CppFunctionCall +{ + public: + CppFunctionCall(CppCodeStream &out, const std::string &name) : + m_out(out) + { + m_out.addToLine(name); + m_out.addToLine("("); + } + + CppFunctionCall(CppCodeStream &out, const CppNamedIdentifier *identifier, const std::string &name) : + m_out(out) + { + if (!identifier->isMemberAccessible()) { + throw std::runtime_error("cannot call method '" + name + "' on '" + name + "'"); + } + + m_out.addToLine(identifier->name); + m_out.addToLine(identifier->isPointer() ? "->" : "."); + m_out.addToLine(name); + m_out.addToLine("("); + } + + ~CppFunctionCall() + { + if (!m_closed) + m_out.addToLine(")"); + } + + CppFunctionCall(const CppFunctionCall &) = delete; + CppFunctionCall &operator=(const CppFunctionCall &) = delete; + + CppFunctionCall ¶m(const CppNamedIdentifier *p) + { + sep(); + m_out.addToLine(p->name); + return *this; + } + + CppFunctionCall ¶m(const std::string &expr) + { + sep(); + m_out.addToLine(expr); + return *this; + } + + void close() + { + m_closed = true; + m_out.addToLine(")"); + } + + private: + void sep() + { + if (!m_first) + m_out.addToLine(", "); + + m_first = false; + } + + CppCodeStream &m_out; + bool m_first = true; + bool m_closed = false; +}; + +} // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/cppidentifier.h b/src/engine/internal/codegen/cpp/cppidentifier.h new file mode 100644 index 000000000..1a9cb8774 --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppidentifier.h @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include + +#include "cpptypeinfo.h" + +namespace libscratchcpp +{ + +class CppIdentifier +{ + public: + enum class Type + { + Double, + Bool, + StringPtr, + Pointer, + Value, + ValueData, + ContextPointer, + TargetPointer, + VariablePointerArray, + ListPointerArray, + StringPtrArray + }; + + CppIdentifier() { } + + CppIdentifier(Type type) : + type(type) + { + } + + inline bool isPointer() const { return m_typeInfo.at(type).isPointer; } + inline bool isMemberAccessible() const { return m_typeInfo.at(type).isMemberAccessible; } + inline bool isArray() const { return m_typeInfo.at(type).isArray; } + + inline const std::string &typeString() const { return m_typeInfo.at(type).name; } + static inline const std::string &typeString(CppIdentifier::Type type) { return m_typeInfo.at(type).name; } + + virtual bool isConst() const { return false; } + virtual bool isNamed() const { return false; } + + const Type type = Type::Pointer; + + private: + static inline const std::unordered_map m_typeInfo = { + { Type::Double, { "double", false, false, false } }, + { Type::Bool, { "bool", false, false, false } }, + { Type::StringPtr, { "StringPtr *", true, true, false } }, + { Type::Pointer, { "void *", false, true, false } }, + { Type::Value, { "Value", true, false, false } }, + { Type::ValueData, { "ValueData", true, false, false } }, + { Type::ContextPointer, { "ExecutionContext *", true, true, false } }, + { Type::TargetPointer, { "Target *", true, true, false } }, + { Type::VariablePointerArray, { "Variable **", false, true, true } }, + { Type::ListPointerArray, { "List **", false, true, true } }, + { Type::StringPtrArray, { "StringPtr **", false, true, true } } + }; +}; + +} // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/cppnamedidentifier.h b/src/engine/internal/codegen/cpp/cppnamedidentifier.h new file mode 100644 index 000000000..fedb8ee06 --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppnamedidentifier.h @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include + +#include "cppidentifier.h" + +namespace libscratchcpp +{ + +struct CppNamedIdentifier : public CppIdentifier +{ + CppNamedIdentifier() { } + + CppNamedIdentifier(Type type, const std::string &name, bool isMutable = true) : + CppIdentifier(type), + name(name), + isMutable(isMutable) + { + } + + virtual bool isNamed() const override final { return true; } + + std::string name; + bool isMutable = true; +}; + +} // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/cppswitch.h b/src/engine/internal/codegen/cpp/cppswitch.h new file mode 100644 index 000000000..d0411e0a2 --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppswitch.h @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "cppnamedidentifier.h" +#include "cppcodestream.h" + +namespace libscratchcpp +{ + +class CppSwitch +{ + public: + CppSwitch(CppCodeStream &out, const CppNamedIdentifier *identifier) : + m_out(out) + { + m_out.beginLine(); + m_out.addToLine("switch ("); + m_out.addToLine(identifier->name); + m_out.addToLine(") {"); + m_out.indent(); + } + + ~CppSwitch() + { + if (!m_closed) { + close(); + } + } + + CppSwitch(const CppSwitch &) = delete; + CppSwitch &operator=(const CppSwitch &) = delete; + + CppSwitch &addCase(const std::string &value) + { + if (m_inCase) + m_out.dedent(); + + m_inCase = true; + + m_out.beginLine(); + m_out.addToLine("case "); + m_out.addToLine(value); + m_out.addToLine(":"); + + m_out.indent(); + + return *this; + } + + CppSwitch &addDefaultCase(const std::string &value) + { + if (m_inCase) + m_out.dedent(); + + m_inCase = true; + + m_out.beginLine(); + m_out.addToLine("default:"); + m_out.indent(); + + return *this; + } + + void close() + { + if (m_inCase) + m_out.dedent(); + + m_closed = true; + m_out.dedent(); + } + + private: + CppCodeStream &m_out; + bool m_inCase = false; + bool m_closed = false; +}; + +} // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/cpptypeinfo.h b/src/engine/internal/codegen/cpp/cpptypeinfo.h new file mode 100644 index 000000000..fc720a917 --- /dev/null +++ b/src/engine/internal/codegen/cpp/cpptypeinfo.h @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include + +namespace libscratchcpp +{ + +struct CppTypeInfo +{ + const std::string name; + const bool isMemberAccessible = false; + const bool isPointer = false; + const bool isArray = false; +}; + +} // namespace libscratchcpp From 68bc1aa0ddd76cd2132c2ce72b5d2b9150c63b6f Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:48:52 +0100 Subject: [PATCH 06/18] Pass CppCodeGenerator to InstructionBuilder --- .../internal/codegen/cpp/cppcodebuilder.cpp | 1 + .../internal/codegen/cpp/cppcodebuilder.h | 2 ++ .../cpp/instructions/instructionbuilder.cpp | 20 +++++++++---------- .../cpp/instructions/instructionbuilder.h | 2 +- .../cpp/instructions/instructiongroup.cpp | 3 ++- .../cpp/instructions/instructiongroup.h | 16 ++++++++++++--- 6 files changed, 29 insertions(+), 15 deletions(-) diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp index ec81f255b..9b06d8677 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp @@ -15,6 +15,7 @@ CppCodeBuilder::CppCodeBuilder(CppCompilerContext *ctx, BlockPrototype *procedur m_ctx(ctx), m_procedurePrototype(procedurePrototype), m_codeType(codeType), + m_instructionBuilder(m_codeGen), m_codeAnalyzer(ctx) { } diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.h b/src/engine/internal/codegen/cpp/cppcodebuilder.h index 6808fea5c..3f2bdb5ed 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.h +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.h @@ -7,6 +7,7 @@ #include "../icodebuilder.h" #include "cppinstruction.h" #include "cppinstructionlist.h" +#include "cppcodegenerator.h" #include "instructions/instructionbuilder.h" #include "../codeanalyzer.h" @@ -127,6 +128,7 @@ class CppCodeBuilder : public ICodeBuilder std::vector> m_values; std::vector> m_localVars; CppInstructionList m_instructions; + CppCodeGenerator m_codeGen; cppins::InstructionBuilder m_instructionBuilder; CodeAnalyzer m_codeAnalyzer; bool m_warp = false; diff --git a/src/engine/internal/codegen/cpp/instructions/instructionbuilder.cpp b/src/engine/internal/codegen/cpp/instructions/instructionbuilder.cpp index 0c4cebddb..65c6df836 100644 --- a/src/engine/internal/codegen/cpp/instructions/instructionbuilder.cpp +++ b/src/engine/internal/codegen/cpp/instructions/instructionbuilder.cpp @@ -15,18 +15,18 @@ using namespace libscratchcpp; using namespace libscratchcpp::cppins; -InstructionBuilder::InstructionBuilder() +InstructionBuilder::InstructionBuilder(CppCodeGenerator &codeGen) { // Create groups - m_groups.push_back(std::make_shared()); - m_groups.push_back(std::make_shared()); - m_groups.push_back(std::make_shared()); - m_groups.push_back(std::make_shared()); - m_groups.push_back(std::make_shared()); - m_groups.push_back(std::make_shared()); - m_groups.push_back(std::make_shared()); - m_groups.push_back(std::make_shared()); - m_groups.push_back(std::make_shared()); + m_groups.push_back(std::make_shared(codeGen)); + m_groups.push_back(std::make_shared(codeGen)); + m_groups.push_back(std::make_shared(codeGen)); + m_groups.push_back(std::make_shared(codeGen)); + m_groups.push_back(std::make_shared(codeGen)); + m_groups.push_back(std::make_shared(codeGen)); + m_groups.push_back(std::make_shared(codeGen)); + m_groups.push_back(std::make_shared(codeGen)); + m_groups.push_back(std::make_shared(codeGen)); } CppInstruction *InstructionBuilder::process(CppInstruction *ins) diff --git a/src/engine/internal/codegen/cpp/instructions/instructionbuilder.h b/src/engine/internal/codegen/cpp/instructions/instructionbuilder.h index ea7c5d3d8..bf817b8f2 100644 --- a/src/engine/internal/codegen/cpp/instructions/instructionbuilder.h +++ b/src/engine/internal/codegen/cpp/instructions/instructionbuilder.h @@ -13,7 +13,7 @@ namespace libscratchcpp::cppins class InstructionBuilder { public: - InstructionBuilder(); + InstructionBuilder(CppCodeGenerator &codeGen); CppInstruction *process(CppInstruction *ins); diff --git a/src/engine/internal/codegen/cpp/instructions/instructiongroup.cpp b/src/engine/internal/codegen/cpp/instructions/instructiongroup.cpp index e41d26d85..7b0e58e4b 100644 --- a/src/engine/internal/codegen/cpp/instructions/instructiongroup.cpp +++ b/src/engine/internal/codegen/cpp/instructions/instructiongroup.cpp @@ -4,6 +4,7 @@ using namespace libscratchcpp::cppins; -InstructionGroup::InstructionGroup() +InstructionGroup::InstructionGroup(CppCodeGenerator &codeGen) : + m_codeGen(codeGen) { } diff --git a/src/engine/internal/codegen/cpp/instructions/instructiongroup.h b/src/engine/internal/codegen/cpp/instructions/instructiongroup.h index c36c10b27..57df59573 100644 --- a/src/engine/internal/codegen/cpp/instructions/instructiongroup.h +++ b/src/engine/internal/codegen/cpp/instructions/instructiongroup.h @@ -4,15 +4,25 @@ #include "processresult.h" -namespace libscratchcpp::cppins +namespace libscratchcpp +{ + +class CppCodeGenerator; + +namespace cppins { class InstructionGroup { public: - InstructionGroup(); + InstructionGroup(CppCodeGenerator &codeGen); virtual ProcessResult process(CppInstruction *ins) = 0; + + protected: + CppCodeGenerator &m_codeGen; }; -} // namespace libscratchcpp::cppins +} // namespace cppins + +} // namespace libscratchcpp From 6954532dfb1107b89edb83f07d8f2c566f81f50a Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:49:04 +0100 Subject: [PATCH 07/18] Add initial C++ function call implementation --- .../codegen/cpp/instructions/functions.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/engine/internal/codegen/cpp/instructions/functions.cpp b/src/engine/internal/codegen/cpp/instructions/functions.cpp index fe0396f48..aebb9814e 100644 --- a/src/engine/internal/codegen/cpp/instructions/functions.cpp +++ b/src/engine/internal/codegen/cpp/instructions/functions.cpp @@ -2,6 +2,7 @@ #include "functions.h" #include "../cppinstruction.h" +#include "../cppcodegenerator.h" using namespace libscratchcpp; using namespace libscratchcpp::cppins; @@ -25,5 +26,21 @@ ProcessResult Functions::process(CppInstruction *ins) CppInstruction *Functions::buildFunctionCall(CppInstruction *ins) { + // TODO: Synchronize variables + std::vector args; + + const auto &insArgs = ins->getArgs(); + + for (auto &arg : insArgs) { + args.push_back(m_codeGen.castValue(arg.second, arg.first)); + } + + if (ins->getFunctionReturnReg()) { + CppIdentifier::Type retType = m_codeGen.getType(ins->getFunctionReturnReg()->type()); + m_codeGen.createCall(ins->functionName, retType, ins->getFunctionReturnReg(), ins->functionCtxArg, ins->functionTargetArg, args); + } else { + m_codeGen.createCall(ins->functionName, ins->functionCtxArg, ins->functionTargetArg, args); + } + return ins->getNext(); } From d66f05bed421284852b6d5a3e2acad125aa1bb22 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:27:24 +0100 Subject: [PATCH 08/18] Add unknown type to C++ type map --- src/engine/internal/codegen/cpp/cppcodegenerator.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp index 803375037..bd4181d5c 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -14,7 +14,8 @@ const std::unordered_map CppCodeGener { Compiler::StaticType::Number, CppIdentifier::Type::Double }, { Compiler::StaticType::Bool, CppIdentifier::Type::Bool }, { Compiler::StaticType::String, CppIdentifier::Type::StringPtr }, - { Compiler::StaticType::Pointer, CppIdentifier::Type::Pointer } + { Compiler::StaticType::Pointer, CppIdentifier::Type::Pointer }, + { Compiler::StaticType::Unknown, CppIdentifier::Type::ValueData } }; const std::unordered_map CppCodeGenerator::m_headers = { From 3073ed3ca79c6ba89bd8dbf0548cc26809af5403 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:20:31 +0100 Subject: [PATCH 09/18] Add isReference property to CppNamedIdentifier --- src/engine/internal/codegen/cpp/cppnamedidentifier.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/engine/internal/codegen/cpp/cppnamedidentifier.h b/src/engine/internal/codegen/cpp/cppnamedidentifier.h index fedb8ee06..a0ac1b4e7 100644 --- a/src/engine/internal/codegen/cpp/cppnamedidentifier.h +++ b/src/engine/internal/codegen/cpp/cppnamedidentifier.h @@ -13,10 +13,11 @@ struct CppNamedIdentifier : public CppIdentifier { CppNamedIdentifier() { } - CppNamedIdentifier(Type type, const std::string &name, bool isMutable = true) : + CppNamedIdentifier(Type type, const std::string &name, bool isMutable = true, bool isReference = false) : CppIdentifier(type), name(name), - isMutable(isMutable) + isMutable(isMutable), + isReference(isReference) { } @@ -24,6 +25,7 @@ struct CppNamedIdentifier : public CppIdentifier std::string name; bool isMutable = true; + bool isReference = false; }; } // namespace libscratchcpp From 0ea12c2af41f95d2c9ced41aa48b5d783e6a58d2 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:21:10 +0100 Subject: [PATCH 10/18] CppCodeGenerator: Do not declare identifiers manually --- .../internal/codegen/cpp/cppcodegenerator.cpp | 41 +++++++------------ .../internal/codegen/cpp/cppcodegenerator.h | 2 +- 2 files changed, 15 insertions(+), 28 deletions(-) diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp index bd4181d5c..ddca3116a 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -83,8 +83,6 @@ void CppCodeGenerator::createCall(const std::string &name, CppIdentifier::Type r m_codeStream.beginLine(); if (retType != CppIdentifier::Type::StringPtr) { - m_codeStream.addToLine(CppIdentifier::typeString(retType)); - m_codeStream.addToLine(" "); m_codeStream.addToLine(getNamedIdentifier(retValue, retType, "ret", false)->name); m_codeStream.addToLine(" = "); } @@ -139,12 +137,12 @@ const CppIdentifier *CppCodeGenerator::getIdentifier(CppValue *value) return it->second.get(); } -const CppNamedIdentifier *CppCodeGenerator::getNamedIdentifier(CppValue *value, CppIdentifier::Type type, const std::string &name, bool isMutable) +const CppNamedIdentifier *CppCodeGenerator::getNamedIdentifier(CppValue *value, CppIdentifier::Type type, const std::string &name, bool isMutable, bool isReference) { auto it = m_identifiers.find(value); if (it == m_identifiers.cend()) { - auto identifier = std::make_shared(type, getNewIdentifierName(name), isMutable); + auto identifier = std::make_shared(type, getNewIdentifierName(name), isMutable, isReference); m_identifiers[value] = identifier; return identifier.get(); } else { @@ -188,8 +186,6 @@ const CppNamedIdentifier *CppCodeGenerator::addStringAlloca() m_strings.push_back(identifier); m_codeStream.beginLine(); - m_codeStream.addToLine(CppIdentifier::typeString(CppIdentifier::Type::StringPtr)); - m_codeStream.addToLine(" "); m_codeStream.addToLine(identifier->name); m_codeStream.addToLine(" = "); addArrayElement(&m_stringArray, m_strings.size() - 1); @@ -228,29 +224,25 @@ const CppNamedIdentifier *CppCodeGenerator::castRawValue(CppValue *value, Compil const CppNamedIdentifier *CppCodeGenerator::createValue(CppValue *value) { - const CppNamedIdentifier *identifier = getNamedIdentifier(value, CppIdentifier::Type::ValueData, "value", false); - if (value->isConst()) { + const CppNamedIdentifier *identifier = getNamedIdentifier(value, CppIdentifier::Type::ValueData, "value", true, true); + includeHeader(Header::Value); - // const Value constant(...); + // const Value constant = Value(...); const CppNamedIdentifier *valueObj = createNamedIdentifier(CppIdentifier::Type::Value, "constant", false); m_codeStream.beginLine(); - m_codeStream.addToLine("const "); - m_codeStream.addToLine(valueObj->typeString()); - m_codeStream.addToLine(" "); m_codeStream.addToLine(valueObj->name); + m_codeStream.addToLine(" = "); + m_codeStream.addToLine(valueObj->typeString()); m_codeStream.addToLine("("); m_codeStream.addToLine(toCppConstant(value->constValue())); m_codeStream.addToLine(")"); m_codeStream.addToLine(";"); m_codeStream.endLine(); - // const ValueData &value = constant.data(); + // ValueData &value = constant.data(); m_codeStream.beginLine(); - m_codeStream.addToLine("const "); - m_codeStream.addToLine(identifier->typeString()); - m_codeStream.addToLine(" &"); m_codeStream.addToLine(identifier->name); m_codeStream.addToLine(" = "); @@ -259,17 +251,11 @@ const CppNamedIdentifier *CppCodeGenerator::createValue(CppValue *value) m_codeStream.addToLine(";"); m_codeStream.endLine(); + return identifier; } else if (value->isRawValue) { - includeHeader(Header::ValueData); + const CppNamedIdentifier *identifier = getNamedIdentifier(value, CppIdentifier::Type::ValueData, "value", false); - // const ValueData value; - m_codeStream.beginLine(); - m_codeStream.addToLine("const "); - m_codeStream.addToLine(identifier->typeString()); - m_codeStream.addToLine(" "); - m_codeStream.addToLine(identifier->name); - m_codeStream.addToLine(";"); - m_codeStream.endLine(); + includeHeader(Header::ValueData); // Store value const CppIdentifier *valueIdentifier = getIdentifier(value); @@ -310,9 +296,10 @@ const CppNamedIdentifier *CppCodeGenerator::createValue(CppValue *value) m_codeStream.addToLine(valueNamedIdentifier->name); m_codeStream.addToLine(";"); m_codeStream.endLine(); + return identifier; + } else { + return getNamedIdentifier(value, CppIdentifier::Type::ValueData, "value", false); } - - return identifier; } std::string CppCodeGenerator::toCppConstant(const Value &value) diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.h b/src/engine/internal/codegen/cpp/cppcodegenerator.h index 00b66e04d..9edfe6730 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.h +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.h @@ -50,7 +50,7 @@ class CppCodeGenerator const CppNamedIdentifier *getParam(FuncParam param); const CppIdentifier *getIdentifier(CppValue *value); - const CppNamedIdentifier *getNamedIdentifier(CppValue *value, CppIdentifier::Type type, const std::string &name, bool isMutable); + const CppNamedIdentifier *getNamedIdentifier(CppValue *value, CppIdentifier::Type type, const std::string &name, bool isMutable, bool isReference = false); const CppNamedIdentifier *createNamedIdentifier(CppIdentifier::Type type, const std::string &name, bool isMutable); std::string getNewIdentifierName(const std::string &name); void includeHeader(Header header); From f3b4eb131437b50489738486a31259579496cb5a Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:53:01 +0100 Subject: [PATCH 11/18] Use CppAssignment for assignments --- .../internal/codegen/cpp/CMakeLists.txt | 1 + .../internal/codegen/cpp/cppassignment.h | 58 +++++++++++++++++++ .../internal/codegen/cpp/cppcodegenerator.cpp | 55 +++++++++++------- 3 files changed, 92 insertions(+), 22 deletions(-) create mode 100644 src/engine/internal/codegen/cpp/cppassignment.h diff --git a/src/engine/internal/codegen/cpp/CMakeLists.txt b/src/engine/internal/codegen/cpp/CMakeLists.txt index b3f56a22a..28f7593cc 100644 --- a/src/engine/internal/codegen/cpp/CMakeLists.txt +++ b/src/engine/internal/codegen/cpp/CMakeLists.txt @@ -19,6 +19,7 @@ target_sources(scratchcpp cppidentifier.h cppconstidentifier.h cppnamedidentifier.h + cppassignment.h cppfunctioncall.h cppswitch.h ) diff --git a/src/engine/internal/codegen/cpp/cppassignment.h b/src/engine/internal/codegen/cpp/cppassignment.h new file mode 100644 index 000000000..636bb2f6a --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppassignment.h @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "cppnamedidentifier.h" +#include "cppcodestream.h" + +namespace libscratchcpp +{ + +class CppAssignment +{ + public: + CppAssignment(CppCodeStream &out, const CppNamedIdentifier *dst) : + m_out(out) + { + if (!dst->isMutable) { + throw std::runtime_error("cannot assign to '" + dst->name + "'"); + } + + m_out.addToLine(dst->name); + m_out.addToLine(" = "); + } + + CppAssignment(CppCodeStream &out, const CppNamedIdentifier *dstObj, const std::string &dstMember) : + m_out(out) + { + if (!dstObj->isMutable) { + throw std::runtime_error("cannot assign to member of '" + dstObj->name + "'"); + } + + m_out.addToLine(dstObj->name); + m_out.addToLine("."); + m_out.addToLine(dstMember); + m_out.addToLine(" = "); + } + + ~CppAssignment() + { + if (!m_closed) + close(); + } + + CppAssignment(const CppAssignment &) = delete; + CppAssignment &operator=(const CppAssignment &) = delete; + + void close() + { + m_closed = true; + m_out.addToLine(";"); + } + + private: + CppCodeStream &m_out; + bool m_closed = false; +}; + +} // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp index ddca3116a..fc7b77a7e 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -1,8 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include #include "cppcodegenerator.h" +#include "cppassignment.h" #include "cppfunctioncall.h" #include "cppvalue.h" #include "cppconstidentifier.h" @@ -82,12 +84,17 @@ void CppCodeGenerator::createCall(const std::string &name, CppIdentifier::Type r m_codeStream.beginLine(); + std::unique_ptr strAssignment; + if (retType != CppIdentifier::Type::StringPtr) { - m_codeStream.addToLine(getNamedIdentifier(retValue, retType, "ret", false)->name); - m_codeStream.addToLine(" = "); + strAssignment = std::make_unique(m_codeStream, getNamedIdentifier(retValue, retType, "ret", false)); } createCall(name, strRet, ctxArg, targetArg, args); + + if (strAssignment) + strAssignment->close(); + m_codeStream.endLine(); } @@ -186,9 +193,10 @@ const CppNamedIdentifier *CppCodeGenerator::addStringAlloca() m_strings.push_back(identifier); m_codeStream.beginLine(); - m_codeStream.addToLine(identifier->name); - m_codeStream.addToLine(" = "); + + CppAssignment assignment(m_codeStream, identifier.get()); addArrayElement(&m_stringArray, m_strings.size() - 1); + assignment.close(); m_codeStream.endLine(); return identifier.get(); @@ -229,27 +237,28 @@ const CppNamedIdentifier *CppCodeGenerator::createValue(CppValue *value) includeHeader(Header::Value); - // const Value constant = Value(...); - const CppNamedIdentifier *valueObj = createNamedIdentifier(CppIdentifier::Type::Value, "constant", false); + // Value constant = Value(...); + const CppNamedIdentifier *valueObj = createNamedIdentifier(CppIdentifier::Type::Value, "constant", true); m_codeStream.beginLine(); - m_codeStream.addToLine(valueObj->name); - m_codeStream.addToLine(" = "); + + CppAssignment constAssignment(m_codeStream, valueObj); m_codeStream.addToLine(valueObj->typeString()); m_codeStream.addToLine("("); m_codeStream.addToLine(toCppConstant(value->constValue())); m_codeStream.addToLine(")"); m_codeStream.addToLine(";"); + + constAssignment.close(); m_codeStream.endLine(); // ValueData &value = constant.data(); m_codeStream.beginLine(); - m_codeStream.addToLine(identifier->name); - m_codeStream.addToLine(" = "); + CppAssignment valueAssignment(m_codeStream, identifier); CppFunctionCall dataCall(m_codeStream, valueObj, "data"); dataCall.close(); - m_codeStream.addToLine(";"); + valueAssignment.close(); m_codeStream.endLine(); return identifier; } else if (value->isRawValue) { @@ -264,35 +273,37 @@ const CppNamedIdentifier *CppCodeGenerator::createValue(CppValue *value) throw std::runtime_error("raw values must have a named identifier when creating a ValueData instance"); } - auto valueNamedIdentifier = static_cast(valueIdentifier); - m_codeStream.addToLine(identifier->name); - switch (value->type()) { - case Compiler::StaticType::Number: + case Compiler::StaticType::Number: { // value.numberValue = rawValue; - m_codeStream.addToLine(".numberValue = "); + CppAssignment valueAssignment(m_codeStream, identifier, "numberValue"); break; + } - case Compiler::StaticType::Bool: + case Compiler::StaticType::Bool: { // value.boolValue = rawValue; - m_codeStream.addToLine(".boolValue = "); + CppAssignment valueAssignment(m_codeStream, identifier, "boolValue"); break; + } - case Compiler::StaticType::String: + case Compiler::StaticType::String: { // value.stringValue = rawValue; - m_codeStream.addToLine(".stringValue = "); + CppAssignment valueAssignment(m_codeStream, identifier, "stringValue"); break; + } - case Compiler::StaticType::Pointer: + case Compiler::StaticType::Pointer: { // value.pointerValue = rawValue; - m_codeStream.addToLine(".pointerValue = "); + CppAssignment valueAssignment(m_codeStream, identifier, "pointerValue"); break; + } default: assert(false); break; } + auto valueNamedIdentifier = static_cast(valueIdentifier); m_codeStream.addToLine(valueNamedIdentifier->name); m_codeStream.addToLine(";"); m_codeStream.endLine(); From d9c16a3e3a9b7b1645f0bad18d46ee3a55505651 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:39:37 +0100 Subject: [PATCH 12/18] Implement C++ value casting --- .../internal/codegen/cpp/cppcodegenerator.cpp | 162 +++++++++++++++++- .../internal/codegen/cpp/cppidentifier.h | 2 + 2 files changed, 157 insertions(+), 7 deletions(-) diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp index fc7b77a7e..535726cef 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -6,6 +6,7 @@ #include "cppcodegenerator.h" #include "cppassignment.h" #include "cppfunctioncall.h" +#include "cppswitch.h" #include "cppvalue.h" #include "cppconstidentifier.h" #include "../typeutils.h" @@ -47,7 +48,6 @@ CppCodeGenerator::~CppCodeGenerator() const CppIdentifier *CppCodeGenerator::castValue(CppValue *value, Compiler::StaticType targetType) { - // TODO: Implement this if (value->isConst()) { if (!TypeUtils::isSingleType(targetType)) return createValue(value); @@ -58,7 +58,97 @@ const CppIdentifier *CppCodeGenerator::castValue(CppValue *value, Compiler::Stat if (value->isRawValue) return castRawValue(value, targetType); - return getNamedIdentifier(value, m_valueTypeMap.at(targetType), "castValue", false); + if (!TypeUtils::isSingleType(targetType)) + return createValue(value); + + assert(value->type() != Compiler::StaticType::Void && targetType != Compiler::StaticType::Void); + const CppNamedIdentifier *source = static_cast(createValue(value)); + const CppNamedIdentifier *result = getNamedIdentifier(value, m_valueTypeMap.at(targetType), "castValue", false); + const CppNamedIdentifier *valueType = createNamedIdentifier(CppIdentifier::Type::ValueType, "valueType", true); + + m_codeStream.beginLine(); + + CppAssignment typeAssignment(m_codeStream, valueType); + m_codeStream.addToLine(source->name + ".type"); + typeAssignment.close(); + m_codeStream.endLine(); + + const CppNamedIdentifier *stringResult = targetType == Compiler::StaticType::String ? addStringAlloca() : nullptr; + CppSwitch sw(m_codeStream, valueType); + const auto emitCase = [&](ValueType fromType, const std::string &, const std::string &expression) { + sw.addCase("ValueType::" + (fromType == ValueType::Number ? std::string("Number") : fromType == ValueType::Bool ? "Bool" : "String")); + m_codeStream.beginLine(); + CppAssignment assignment(m_codeStream, result); + m_codeStream.addToLine(expression); + assignment.close(); + m_codeStream.endLine(); + m_codeStream.beginLine(); + m_codeStream.addToLine("break;"); + m_codeStream.endLine(); + }; + + includeHeader(Header::ValueData); + + if (targetType == Compiler::StaticType::Number) { + emitCase(ValueType::Number, "numberValue", source->name + ".numberValue"); + emitCase(ValueType::Bool, "boolValue", "static_cast(" + source->name + ".boolValue)"); + includeHeader(Header::ValueFunctions); + emitCase(ValueType::String, "stringValue", "value_stringToDouble(" + source->name + ".stringValue)"); + } else if (targetType == Compiler::StaticType::Bool) { + emitCase(ValueType::Number, "numberValue", "(" + source->name + ".numberValue != 0.0)"); + emitCase(ValueType::Bool, "boolValue", source->name + ".boolValue"); + includeHeader(Header::ValueFunctions); + emitCase(ValueType::String, "stringValue", "value_stringToBool(" + source->name + ".stringValue)"); + } else if (targetType == Compiler::StaticType::String) { + includeHeader(Header::ValueFunctions); + + // The string destination is passed to the number conversion routine; bool conversion returns a stable pointer. + sw.addCase("ValueType::Number"); + m_codeStream.beginLine(); + + CppFunctionCall numberCall(m_codeStream, "value_doubleToStringPtr"); + numberCall.param(source->name + ".numberValue").param(stringResult->name); + numberCall.close(); + m_codeStream.addToLine(";"); + m_codeStream.endLine(); + m_codeStream.beginLine(); + + CppAssignment stringAssignment(m_codeStream, result); + m_codeStream.addToLine(stringResult->name); + stringAssignment.close(); + m_codeStream.endLine(); + m_codeStream.beginLine(); + m_codeStream.addToLine("break;"); + m_codeStream.endLine(); + sw.addCase("ValueType::Bool"); + m_codeStream.beginLine(); + + CppAssignment boolAssignment(m_codeStream, result); + m_codeStream.addToLine("value_boolToStringPtr(" + source->name + ".boolValue)"); + boolAssignment.close(); + m_codeStream.endLine(); + m_codeStream.beginLine(); + m_codeStream.addToLine("break;"); + m_codeStream.endLine(); + sw.addCase("ValueType::String"); + m_codeStream.beginLine(); + + CppAssignment identityAssignment(m_codeStream, result); + m_codeStream.addToLine(source->name + ".stringValue"); + identityAssignment.close(); + m_codeStream.endLine(); + m_codeStream.beginLine(); + m_codeStream.addToLine("break;"); + m_codeStream.endLine(); + } + + sw.addDefaultCase(""); + m_codeStream.beginLine(); + m_codeStream.addToLine("__builtin_unreachable();"); + m_codeStream.endLine(); + sw.close(); + + return result; } void CppCodeGenerator::createCall(const std::string &name, bool ctxArg, bool targetArg, const std::vector &args) @@ -216,18 +306,76 @@ void CppCodeGenerator::addArrayElement(const CppNamedIdentifier *array, size_t i const CppConstIdentifier *CppCodeGenerator::castConstValue(const Value &value, Compiler::StaticType targetType) { - // TODO: Implement this - auto identifierType = m_valueTypeMap.at(TypeUtils::mapType(value.type())); - auto ret = std::make_shared(identifierType, value); + Value casted = value; + + switch (targetType) { + case Compiler::StaticType::Number: + casted = Value(value.toDouble()); + break; + + case Compiler::StaticType::Bool: + casted = Value(value.toBool()); + break; + + case Compiler::StaticType::String: + casted = Value(value.toString()); + break; + + case Compiler::StaticType::Pointer: + casted = Value(value.toPointer()); + break; + + default: + assert(false); + break; + } + + auto ret = std::make_shared(m_valueTypeMap.at(targetType), casted); m_constants.push_back(ret); return ret.get(); } const CppNamedIdentifier *CppCodeGenerator::castRawValue(CppValue *value, Compiler::StaticType targetType) { - // TODO: Implement this assert(value->isRawValue); - return getNamedIdentifier(value, m_valueTypeMap.at(targetType), "castRawValue", false); + + const CppNamedIdentifier *source = static_cast(getIdentifier(value)); + + if (value->type() == targetType) + return source; + + const CppNamedIdentifier *result = getNamedIdentifier(value, m_valueTypeMap.at(targetType), "castRawValue", false); + std::string expression; + + includeHeader(Header::ValueFunctions); + + if (targetType == Compiler::StaticType::Number) { + expression = value->type() == Compiler::StaticType::Bool ? "static_cast(" + source->name + ")" : "value_stringToDouble(" + source->name + ")"; + } else if (targetType == Compiler::StaticType::Bool) { + expression = value->type() == Compiler::StaticType::Number ? "(" + source->name + " != 0.0)" : "value_stringToBool(" + source->name + ")"; + } else if (targetType == Compiler::StaticType::String) { + if (value->type() == Compiler::StaticType::Number) { + const CppNamedIdentifier *string = addStringAlloca(); + + m_codeStream.beginLine(); + CppFunctionCall call(m_codeStream, "value_doubleToStringPtr"); + call.param(source->name).param(string->name); + call.close(); + m_codeStream.addToLine(";"); + m_codeStream.endLine(); + + expression = string->name; + } else if (value->type() == Compiler::StaticType::Bool) { + expression = "value_boolToStringPtr(" + source->name + ")"; + } + } + + m_codeStream.beginLine(); + CppAssignment assignment(m_codeStream, result); + m_codeStream.addToLine(expression); + assignment.close(); + m_codeStream.endLine(); + return result; } const CppNamedIdentifier *CppCodeGenerator::createValue(CppValue *value) diff --git a/src/engine/internal/codegen/cpp/cppidentifier.h b/src/engine/internal/codegen/cpp/cppidentifier.h index 1a9cb8774..b373ca9a8 100644 --- a/src/engine/internal/codegen/cpp/cppidentifier.h +++ b/src/engine/internal/codegen/cpp/cppidentifier.h @@ -20,6 +20,7 @@ class CppIdentifier Pointer, Value, ValueData, + ValueType, ContextPointer, TargetPointer, VariablePointerArray, @@ -54,6 +55,7 @@ class CppIdentifier { Type::Pointer, { "void *", false, true, false } }, { Type::Value, { "Value", true, false, false } }, { Type::ValueData, { "ValueData", true, false, false } }, + { Type::ValueType, { "ValueType", false, false, false } }, { Type::ContextPointer, { "ExecutionContext *", true, true, false } }, { Type::TargetPointer, { "Target *", true, true, false } }, { Type::VariablePointerArray, { "Variable **", false, true, true } }, From 267d030af6f37d824d0b98b0b2fc3c39fe818cdb Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:03:45 +0100 Subject: [PATCH 13/18] CppCodeGenerator: Add finalize() method --- .../internal/codegen/cpp/cppcodegenerator.cpp | 58 ++++++++++++++++++- .../internal/codegen/cpp/cppcodegenerator.h | 4 +- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp index 535726cef..1e7c803c6 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 -#include #include +#include #include "cppcodegenerator.h" #include "cppassignment.h" @@ -43,7 +43,61 @@ CppCodeGenerator::CppCodeGenerator() : CppCodeGenerator::~CppCodeGenerator() { - std::cout << m_codeStream.code() << std::endl; +} + +std::string CppCodeGenerator::finalize() +{ + static unsigned int scriptCount = 0; + + const std::string scriptName = "Script" + std::to_string(scriptCount++); + + std::ostringstream source; + source << "#include \"script" + std::to_string(scriptCount++) + ".h\"\n"; + + for (Header header : m_includedHeaders) { + source << "#include " << m_headers.at(header) << "\n"; + } + + source << "\nnamespace libscratchcpp\n{\n\n"; + source << "void " << scriptName << "::runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists)\n{\n"; + + std::unordered_set declared; + const auto declare = [&](const CppIdentifier *identifier) { + if (!identifier || !identifier->isNamed() || !declared.insert(identifier).second) + return; + + const auto *named = static_cast(identifier); + + source << " " << identifier->typeString(); + source << " " << named->name << ";\n"; + }; + + for (const auto &entry : m_identifiers) + declare(entry.second.get()); + + for (const auto &identifier : m_internalIdentifiers) + declare(identifier.get()); + + for (const auto &identifier : m_strings) + declare(identifier.get()); + + if (!m_strings.empty()) { + for (size_t i = 0; i < m_strings.size(); ++i) + source << " StringPtr " << m_strings[i]->name << "Storage;\n"; + + source << " StringPtr *" << m_stringArray.name << "[" << m_strings.size() << "] = { "; + + for (size_t i = 0; i < m_strings.size(); ++i) { + if (i) + source << ", "; + source << "&" << m_strings[i]->name << "Storage"; + } + source << " };\n"; + } + + source << m_codeStream.code(); + source << "}\n\n} // namespace libscratchcpp\n"; + return source.str(); } const CppIdentifier *CppCodeGenerator::castValue(CppValue *value, Compiler::StaticType targetType) diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.h b/src/engine/internal/codegen/cpp/cppcodegenerator.h index 9edfe6730..8aea6fdee 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.h +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.h @@ -25,6 +25,8 @@ class CppCodeGenerator const CppIdentifier *castValue(CppValue *value, Compiler::StaticType targetType); + std::string finalize(); + 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); @@ -80,7 +82,7 @@ class CppCodeGenerator std::vector> m_constants; CppNamedIdentifier m_stringArray; - std::vector> m_strings; + std::vector> m_strings; }; } // namespace libscratchcpp From d13335e485cb8d7d377bdbd394c3a64f563d34df Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:04:09 +0100 Subject: [PATCH 14/18] CppCodeBuilder: Finalize generated code --- src/engine/internal/codegen/cpp/cppcodebuilder.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp index 9b06d8677..00008ba08 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp @@ -49,6 +49,8 @@ std::shared_ptr CppCodeBuilder::build() while (ins) ins = m_instructionBuilder.process(ins); + std::cout << m_codeGen.finalize(); + return std::make_shared(m_ctx); } From 2eade6e96f6baf3609f0db438ecb13ca0f440152 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:16:11 +0100 Subject: [PATCH 15/18] CppCodeGenerator: Make return string pointer mutable --- src/engine/internal/codegen/cpp/cppcodegenerator.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp index 1e7c803c6..7e9884539 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -231,7 +231,7 @@ void CppCodeGenerator::createCall(const std::string &name, CppIdentifier::Type r std::unique_ptr strAssignment; if (retType != CppIdentifier::Type::StringPtr) { - strAssignment = std::make_unique(m_codeStream, getNamedIdentifier(retValue, retType, "ret", false)); + strAssignment = std::make_unique(m_codeStream, getNamedIdentifier(retValue, retType, "ret", true)); } createCall(name, strRet, ctxArg, targetArg, args); From 0d92146d007798c284580e7a2df5041210a224f3 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:30:52 +0100 Subject: [PATCH 16/18] CppCodeGenerator: Fix undefined return string identifier --- .../internal/codegen/cpp/cppcodegenerator.cpp | 3 +++ .../internal/codegen/cpp/cppcodegenerator.h | 3 ++- test/codegen/cpp/CMakeLists.txt | 1 + test/codegen/cpp/cppcodegenerator_test.cpp | 23 +++++++++++++++++++ 4 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 test/codegen/cpp/cppcodegenerator_test.cpp diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp index 7e9884539..e442a9670 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -224,6 +224,9 @@ void CppCodeGenerator::createCall(const std::string &name, CppIdentifier::Type r // Strings are returned through an output parameter includeHeader(Header::ExecutionContext); strRet = addStringAlloca(); + + if (retValue) + m_identifiers[retValue] = m_strings.back(); } m_codeStream.beginLine(); diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.h b/src/engine/internal/codegen/cpp/cppcodegenerator.h index 8aea6fdee..4fc016b70 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.h +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.h @@ -3,6 +3,7 @@ #pragma once #include +#include #include #include @@ -15,7 +16,7 @@ namespace libscratchcpp class CppValue; -class CppCodeGenerator +class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator { public: CppCodeGenerator(); diff --git a/test/codegen/cpp/CMakeLists.txt b/test/codegen/cpp/CMakeLists.txt index 04f3e1897..7efc9ffd0 100644 --- a/test/codegen/cpp/CMakeLists.txt +++ b/test/codegen/cpp/CMakeLists.txt @@ -1,6 +1,7 @@ add_executable( cpp_test main.cpp + cppcodegenerator_test.cpp cppexecutioncontext_test.cpp cppexecutablecode_test.cpp cppexecutablecodemock.h diff --git a/test/codegen/cpp/cppcodegenerator_test.cpp b/test/codegen/cpp/cppcodegenerator_test.cpp new file mode 100644 index 000000000..2606b4dc3 --- /dev/null +++ b/test/codegen/cpp/cppcodegenerator_test.cpp @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include + +#include +#include + +using namespace libscratchcpp; + +TEST(CppCodeGeneratorTest, StringReturnValueCanBePassedToAnotherCall) +{ + CppCodeGenerator codeGen; + CppValue stringResult(Compiler::StaticType::String); + stringResult.isRawValue = true; + + codeGen.createCall("test_function_no_args_ret", CppIdentifier::Type::StringPtr, &stringResult, false, false, {}); + + const CppIdentifier *stringArg = codeGen.castValue(&stringResult, Compiler::StaticType::String); + codeGen.createCall("test_print_string", false, false, { stringArg }); + + const std::string source = codeGen.finalize(); + EXPECT_NE(source.find("test_print_string(string0)"), std::string::npos); +} From 9f777af9ea64479c1cde0440720176033b2d7521 Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:19:43 +0100 Subject: [PATCH 17/18] CppCodeGenerator: Store distinct identifiers for different types --- .../internal/codegen/cpp/cppcodegenerator.cpp | 69 ++++++++++++++----- .../internal/codegen/cpp/cppcodegenerator.h | 2 + test/codegen/cpp/cppcodegenerator_test.cpp | 25 +++++++ 3 files changed, 77 insertions(+), 19 deletions(-) diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp index e442a9670..5530e4943 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -109,15 +109,15 @@ const CppIdentifier *CppCodeGenerator::castValue(CppValue *value, Compiler::Stat return castConstValue(value->constValue(), targetType); } - if (value->isRawValue) - return castRawValue(value, targetType); - if (!TypeUtils::isSingleType(targetType)) return createValue(value); + if (value->isRawValue) + return castRawValue(value, targetType); + assert(value->type() != Compiler::StaticType::Void && targetType != Compiler::StaticType::Void); const CppNamedIdentifier *source = static_cast(createValue(value)); - const CppNamedIdentifier *result = getNamedIdentifier(value, m_valueTypeMap.at(targetType), "castValue", false); + const CppNamedIdentifier *result = createNamedIdentifier(m_valueTypeMap.at(targetType), "castValue", true); const CppNamedIdentifier *valueType = createNamedIdentifier(CppIdentifier::Type::ValueType, "valueType", true); m_codeStream.beginLine(); @@ -361,6 +361,18 @@ void CppCodeGenerator::addArrayElement(const CppNamedIdentifier *array, size_t i m_codeStream.addToLine("]"); } +const CppNamedIdentifier *CppCodeGenerator::getValueDataIdentifier(CppValue *value) +{ + auto it = m_valueDataIdentifiers.find(value); + + if (it != m_valueDataIdentifiers.cend()) + return it->second; + + const CppNamedIdentifier *identifier = createNamedIdentifier(CppIdentifier::Type::ValueData, "value", true); + m_valueDataIdentifiers[value] = identifier; + return identifier; +} + const CppConstIdentifier *CppCodeGenerator::castConstValue(const Value &value, Compiler::StaticType targetType) { Value casted = value; @@ -401,7 +413,7 @@ const CppNamedIdentifier *CppCodeGenerator::castRawValue(CppValue *value, Compil if (value->type() == targetType) return source; - const CppNamedIdentifier *result = getNamedIdentifier(value, m_valueTypeMap.at(targetType), "castRawValue", false); + const CppNamedIdentifier *result = createNamedIdentifier(m_valueTypeMap.at(targetType), "castRawValue", true); std::string expression; includeHeader(Header::ValueFunctions); @@ -438,7 +450,7 @@ const CppNamedIdentifier *CppCodeGenerator::castRawValue(CppValue *value, Compil const CppNamedIdentifier *CppCodeGenerator::createValue(CppValue *value) { if (value->isConst()) { - const CppNamedIdentifier *identifier = getNamedIdentifier(value, CppIdentifier::Type::ValueData, "value", true, true); + const CppNamedIdentifier *identifier = getValueDataIdentifier(value); includeHeader(Header::Value); @@ -466,8 +478,12 @@ const CppNamedIdentifier *CppCodeGenerator::createValue(CppValue *value) valueAssignment.close(); m_codeStream.endLine(); return identifier; - } else if (value->isRawValue) { - const CppNamedIdentifier *identifier = getNamedIdentifier(value, CppIdentifier::Type::ValueData, "value", false); + } + + const auto it = m_identifiers.find(value); + + if (value->isRawValue || (it != m_identifiers.cend() && it->second->type != CppIdentifier::Type::ValueData)) { + const CppNamedIdentifier *identifier = getValueDataIdentifier(value); includeHeader(Header::ValueData); @@ -478,28 +494,31 @@ const CppNamedIdentifier *CppCodeGenerator::createValue(CppValue *value) throw std::runtime_error("raw values must have a named identifier when creating a ValueData instance"); } + std::string member; + ValueType type = ValueType::Number; + switch (value->type()) { case Compiler::StaticType::Number: { - // value.numberValue = rawValue; - CppAssignment valueAssignment(m_codeStream, identifier, "numberValue"); + member = "numberValue"; + type = ValueType::Number; break; } case Compiler::StaticType::Bool: { - // value.boolValue = rawValue; - CppAssignment valueAssignment(m_codeStream, identifier, "boolValue"); + member = "boolValue"; + type = ValueType::Bool; break; } case Compiler::StaticType::String: { - // value.stringValue = rawValue; - CppAssignment valueAssignment(m_codeStream, identifier, "stringValue"); + member = "stringValue"; + type = ValueType::String; break; } case Compiler::StaticType::Pointer: { - // value.pointerValue = rawValue; - CppAssignment valueAssignment(m_codeStream, identifier, "pointerValue"); + member = "pointerValue"; + type = ValueType::Pointer; break; } @@ -509,13 +528,25 @@ const CppNamedIdentifier *CppCodeGenerator::createValue(CppValue *value) } auto valueNamedIdentifier = static_cast(valueIdentifier); + + m_codeStream.beginLine(); + CppAssignment valueAssignment(m_codeStream, identifier, member); m_codeStream.addToLine(valueNamedIdentifier->name); - m_codeStream.addToLine(";"); + valueAssignment.close(); + m_codeStream.endLine(); + + m_codeStream.beginLine(); + CppAssignment typeAssignment(m_codeStream, identifier, "type"); + m_codeStream.addToLine("ValueType::" + (type == ValueType::Number ? std::string("Number") : type == ValueType::Bool ? "Bool" : type == ValueType::String ? "String" : "Pointer")); + typeAssignment.close(); m_codeStream.endLine(); return identifier; - } else { - return getNamedIdentifier(value, CppIdentifier::Type::ValueData, "value", false); } + + if (it != m_identifiers.cend()) + return static_cast(it->second.get()); + + return getNamedIdentifier(value, CppIdentifier::Type::ValueData, "value", false); } std::string CppCodeGenerator::toCppConstant(const Value &value) diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.h b/src/engine/internal/codegen/cpp/cppcodegenerator.h index 4fc016b70..ca271d8fd 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.h +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.h @@ -62,6 +62,7 @@ class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator const CppNamedIdentifier *addStringAlloca(); void addArrayElement(const CppNamedIdentifier *array, size_t index); + const CppNamedIdentifier *getValueDataIdentifier(CppValue *value); const CppConstIdentifier *castConstValue(const Value &value, Compiler::StaticType targetType); const CppNamedIdentifier *castRawValue(CppValue *value, Compiler::StaticType targetType); const CppNamedIdentifier *createValue(CppValue *value); @@ -77,6 +78,7 @@ class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator CppCodeStream m_codeStream; std::unordered_map> m_identifiers; + std::unordered_map m_valueDataIdentifiers; std::unordered_map m_identifierNameCounts; std::unordered_set
m_includedHeaders; std::vector> m_internalIdentifiers; diff --git a/test/codegen/cpp/cppcodegenerator_test.cpp b/test/codegen/cpp/cppcodegenerator_test.cpp index 2606b4dc3..a6805ac51 100644 --- a/test/codegen/cpp/cppcodegenerator_test.cpp +++ b/test/codegen/cpp/cppcodegenerator_test.cpp @@ -21,3 +21,28 @@ TEST(CppCodeGeneratorTest, StringReturnValueCanBePassedToAnotherCall) const std::string source = codeGen.finalize(); EXPECT_NE(source.find("test_print_string(string0)"), std::string::npos); } + +TEST(CppCodeGeneratorTest, ReporterCanBeConvertedAndBoxedWithoutChangingItsOriginalValue) +{ + CppCodeGenerator codeGen; + CppValue numberResult(Compiler::StaticType::Number); + numberResult.isRawValue = true; + + codeGen.createCall("test_get_number", CppIdentifier::Type::Double, &numberResult, false, false, {}); + + const CppIdentifier *boolArg = codeGen.castValue(&numberResult, Compiler::StaticType::Bool); + codeGen.createCall("test_print_bool", false, false, { boolArg }); + + const CppIdentifier *numberArg = codeGen.castValue(&numberResult, Compiler::StaticType::Number); + codeGen.createCall("test_print_number", false, false, { numberArg }); + + const CppIdentifier *valueArg = codeGen.castValue(&numberResult, Compiler::StaticType::Unknown); + codeGen.createCall("test_print_unknown", false, false, { valueArg }); + + const std::string source = codeGen.finalize(); + EXPECT_NE(source.find("test_print_bool(castRawValue0)"), std::string::npos); + 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; +} From 79f56731fe64d60236ee0084248760c507f9634c Mon Sep 17 00:00:00 2001 From: adazem009 <68537469+adazem009@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:02:50 +0100 Subject: [PATCH 18/18] Avoid constant pointers in generated code --- include/scratchcpp/compiler.h | 10 ++ src/blocks/listblocks.cpp | 6 +- src/blocks/looksblocks.cpp | 2 +- src/blocks/motionblocks.cpp | 10 +- src/blocks/sensingblocks.cpp | 14 +-- src/blocks/variableblocks.cpp | 4 +- src/engine/compiler.cpp | 36 ++++++ .../internal/codegen/cpp/cppcodebuilder.cpp | 29 +++++ .../internal/codegen/cpp/cppcodebuilder.h | 5 + .../internal/codegen/cpp/cppcodegenerator.cpp | 64 +++++++++- .../internal/codegen/cpp/cppcodegenerator.h | 3 + .../codegen/cpp/cppexecutablecode.cpp | 90 +++++++++++++-- .../internal/codegen/cpp/cppexecutablecode.h | 18 ++- .../internal/codegen/cpp/cppobjectpointer.h | 31 +++++ src/engine/internal/codegen/cpp/cppvalue.h | 17 +++ src/engine/internal/codegen/icodebuilder.h | 5 + .../internal/codegen/llvm/llvmcodebuilder.cpp | 32 +++++ .../internal/codegen/llvm/llvmcodebuilder.h | 5 + test/blocks/motion_blocks_test.cpp | 80 ++++++------- test/blocks/sensing_blocks_test.cpp | 109 +++++++++++------- test/codegen/cpp/cppexecutablecode_test.cpp | 14 +-- test/codegen/cpp/cppexecutablecodemock.h | 6 +- test/mocks/codebuildermock.h | 5 + 23 files changed, 468 insertions(+), 127 deletions(-) create mode 100644 src/engine/internal/codegen/cpp/cppobjectpointer.h diff --git a/include/scratchcpp/compiler.h b/include/scratchcpp/compiler.h index 626635528..a0bbe68fd 100644 --- a/include/scratchcpp/compiler.h +++ b/include/scratchcpp/compiler.h @@ -67,6 +67,16 @@ class LIBSCRATCHCPP_EXPORT Compiler CompilerValue *addTargetFunctionCall(const std::string &functionName, StaticType returnType = StaticType::Void, const ArgTypes &argTypes = {}, const Args &args = {}); CompilerValue *addFunctionCallWithCtx(const std::string &functionName, StaticType returnType = StaticType::Void, const ArgTypes &argTypes = {}, const Args &args = {}); CompilerConstant *addConstValue(const Value &value); + + CompilerValue *addTargetPointer(const std::string &name); + + CompilerValue *addVariablePointer(Variable *variable); + + CompilerValue *addListPointer(List *list); + + CompilerValue *addTimerPointer(); + + CompilerValue *addEffectPointer(const std::string &name); CompilerValue *addStringChar(CompilerValue *string, CompilerValue *index); CompilerValue *addStringLength(CompilerValue *string); CompilerValue *addLoopIndex(); diff --git a/src/blocks/listblocks.cpp b/src/blocks/listblocks.cpp index 146aabc33..bfc7495b4 100644 --- a/src/blocks/listblocks.cpp +++ b/src/blocks/listblocks.cpp @@ -55,7 +55,7 @@ CompilerValue *ListBlocks::compileListContents(Compiler *compiler) // If this block is used in a list monitor, return the list pointer if (compiler->block()->isMonitorBlock()) - return compiler->addConstValue(list.get()); + return compiler->addListPointer(static_cast(list.get())); else return compiler->addListContents(static_cast(list.get())); } @@ -224,7 +224,7 @@ CompilerValue *ListBlocks::compileShowList(Compiler *compiler) List *list = static_cast(field->valuePtr().get()); assert(list); - CompilerConstant *listPtr = compiler->addConstValue(list); + CompilerValue *listPtr = compiler->addListPointer(list); compiler->addTargetFunctionCall("data_showlist", Compiler::StaticType::Void, { Compiler::StaticType::Pointer }, { listPtr }); return nullptr; @@ -237,7 +237,7 @@ CompilerValue *ListBlocks::compileHideList(Compiler *compiler) List *list = static_cast(field->valuePtr().get()); assert(list); - CompilerConstant *listPtr = compiler->addConstValue(list); + CompilerValue *listPtr = compiler->addListPointer(list); compiler->addTargetFunctionCall("data_hidelist", Compiler::StaticType::Void, { Compiler::StaticType::Pointer }, { listPtr }); return nullptr; diff --git a/src/blocks/looksblocks.cpp b/src/blocks/looksblocks.cpp index 7d3cb3b0b..23a7df8ed 100644 --- a/src/blocks/looksblocks.cpp +++ b/src/blocks/looksblocks.cpp @@ -109,7 +109,7 @@ void LooksBlocks::compileSetOrChangeEffect(Compiler *compiler, const std::string IGraphicsEffect *effect = ScratchConfiguration::getGraphicsEffect(effectName); if (effect) { - CompilerValue *effectPtr = compiler->addConstValue(effect); + CompilerValue *effectPtr = compiler->addEffectPointer(effectName); compiler->addTargetFunctionCall(function, Compiler::StaticType::Void, { Compiler::StaticType::Pointer, Compiler::StaticType::Number }, { effectPtr, arg }); } else std::cout << "warning: graphic effect '" << effectName << "' is not registered" << std::endl; diff --git a/src/blocks/motionblocks.cpp b/src/blocks/motionblocks.cpp index 9d23cc42b..c6e464dc7 100644 --- a/src/blocks/motionblocks.cpp +++ b/src/blocks/motionblocks.cpp @@ -116,7 +116,7 @@ CompilerValue *MotionBlocks::compilePointTowards(Compiler *compiler) Target *anotherTarget = compiler->engine()->targetAt(index); if (anotherTarget && !anotherTarget->isStage()) - compiler->addTargetFunctionCall("motion_point_towards_sprite", Compiler::StaticType::Void, { Compiler::StaticType::Pointer }, { compiler->addConstValue(anotherTarget) }); + compiler->addTargetFunctionCall("motion_point_towards_sprite", Compiler::StaticType::Void, { Compiler::StaticType::Pointer }, { compiler->addTargetPointer(anotherTarget->name()) }); } } else { CompilerValue *towards = compiler->addInput(input); @@ -156,7 +156,7 @@ CompilerValue *MotionBlocks::compileGoTo(Compiler *compiler) Target *anotherTarget = compiler->engine()->targetAt(index); if (anotherTarget && !anotherTarget->isStage()) - compiler->addTargetFunctionCall("motion_go_to_sprite", Compiler::StaticType::Void, { Compiler::StaticType::Pointer }, { compiler->addConstValue(anotherTarget) }); + compiler->addTargetFunctionCall("motion_go_to_sprite", Compiler::StaticType::Void, { Compiler::StaticType::Pointer }, { compiler->addTargetPointer(anotherTarget->name()) }); } } else { CompilerValue *to = compiler->addInput(input); @@ -218,8 +218,10 @@ CompilerValue *MotionBlocks::compileGlideTo(Compiler *compiler) if (anotherTarget && !anotherTarget->isStage()) { if (!target->isStage()) { - endX = compiler->addFunctionCallWithCtx("motion_get_sprite_x", Compiler::StaticType::Number, { Compiler::StaticType::Pointer }, { compiler->addConstValue(anotherTarget) }); - endY = compiler->addFunctionCallWithCtx("motion_get_sprite_y", Compiler::StaticType::Number, { Compiler::StaticType::Pointer }, { compiler->addConstValue(anotherTarget) }); + endX = + compiler->addFunctionCallWithCtx("motion_get_sprite_x", Compiler::StaticType::Number, { Compiler::StaticType::Pointer }, { compiler->addTargetPointer(anotherTarget->name()) }); + endY = + compiler->addFunctionCallWithCtx("motion_get_sprite_y", Compiler::StaticType::Number, { Compiler::StaticType::Pointer }, { compiler->addTargetPointer(anotherTarget->name()) }); } } else return nullptr; diff --git a/src/blocks/sensingblocks.cpp b/src/blocks/sensingblocks.cpp index 47f8c4562..a33017a8c 100644 --- a/src/blocks/sensingblocks.cpp +++ b/src/blocks/sensingblocks.cpp @@ -113,7 +113,7 @@ CompilerValue *SensingBlocks::compileTouchingObject(Compiler *compiler) Target *target = engine->targetAt(engine->findTarget(value)); if (target) { - CompilerValue *targetPtr = compiler->addConstValue(target); + CompilerValue *targetPtr = compiler->addTargetPointer(value); return compiler->addTargetFunctionCall("sensing_touching_sprite", Compiler::StaticType::Bool, { Compiler::StaticType::Pointer }, { targetPtr }); } } @@ -155,7 +155,7 @@ CompilerValue *SensingBlocks::compileDistanceTo(Compiler *compiler) Target *target = engine->targetAt(engine->findTarget(value)); if (target) { - CompilerValue *targetPtr = compiler->addConstValue(target); + CompilerValue *targetPtr = compiler->addTargetPointer(value); return compiler->addTargetFunctionCall("sensing_distance_to_sprite", Compiler::StaticType::Number, { Compiler::StaticType::Pointer }, { targetPtr }); } } @@ -237,15 +237,13 @@ CompilerValue *SensingBlocks::compileLoud(Compiler *compiler) CompilerValue *SensingBlocks::compileTimer(Compiler *compiler) { - ITimer *timer = compiler->engine()->timer(); - CompilerValue *timerPtr = compiler->addConstValue(timer); + CompilerValue *timerPtr = compiler->addTimerPointer(); return compiler->addFunctionCall("sensing_timer", Compiler::StaticType::Number, { Compiler::StaticType::Pointer }, { timerPtr }); } CompilerValue *SensingBlocks::compileResetTimer(Compiler *compiler) { - ITimer *timer = compiler->engine()->timer(); - CompilerValue *timerPtr = compiler->addConstValue(timer); + CompilerValue *timerPtr = compiler->addTimerPointer(); compiler->addFunctionCall("sensing_resettimer", Compiler::StaticType::Void, { Compiler::StaticType::Pointer }, { timerPtr }); return nullptr; } @@ -269,7 +267,7 @@ CompilerValue *SensingBlocks::compileOf(Compiler *compiler) if (value == "_stage_") { // Stage properties target = engine->stage(); - targetPtr = compiler->addConstValue(target); + targetPtr = compiler->addTargetPointer("_stage_"); if (property == "backdrop #") return compiler->addFunctionCall("sensing_costume_number_of_target", Compiler::StaticType::Number, { Compiler::StaticType::Pointer }, { targetPtr }); @@ -280,7 +278,7 @@ CompilerValue *SensingBlocks::compileOf(Compiler *compiler) target = engine->targetAt(engine->findTarget(value)); if (target) { - targetPtr = compiler->addConstValue(target); + targetPtr = compiler->addTargetPointer(value); if (property == "x position") return compiler->addFunctionCall("sensing_x_position_of_sprite", Compiler::StaticType::Number, { Compiler::StaticType::Pointer }, { targetPtr }); diff --git a/src/blocks/variableblocks.cpp b/src/blocks/variableblocks.cpp index 55db51e35..b53c33b73 100644 --- a/src/blocks/variableblocks.cpp +++ b/src/blocks/variableblocks.cpp @@ -90,7 +90,7 @@ CompilerValue *VariableBlocks::compileShowVariable(Compiler *compiler) Variable *var = static_cast(field->valuePtr().get()); assert(var); - CompilerConstant *varPtr = compiler->addConstValue(var); + CompilerValue *varPtr = compiler->addVariablePointer(var); compiler->addTargetFunctionCall("data_showvariable", Compiler::StaticType::Void, { Compiler::StaticType::Pointer }, { varPtr }); return nullptr; @@ -103,7 +103,7 @@ CompilerValue *VariableBlocks::compileHideVariable(Compiler *compiler) Variable *var = static_cast(field->valuePtr().get()); assert(var); - CompilerConstant *varPtr = compiler->addConstValue(var); + CompilerValue *varPtr = compiler->addVariablePointer(var); compiler->addTargetFunctionCall("data_hidevariable", Compiler::StaticType::Void, { Compiler::StaticType::Pointer }, { varPtr }); return nullptr; diff --git a/src/engine/compiler.cpp b/src/engine/compiler.cpp index 799c0ae14..a1f9ac3b7 100644 --- a/src/engine/compiler.cpp +++ b/src/engine/compiler.cpp @@ -167,9 +167,45 @@ CompilerValue *Compiler::addFunctionCallWithCtx(const std::string &functionName, /*! Adds the given constant to the compiled code. */ CompilerConstant *Compiler::addConstValue(const Value &value) { + if (value.isPointer()) { + std::cerr << "error: constant pointers are not supported" << std::endl; + assert(false); + return nullptr; + } + return static_cast(impl->builder->addConstValue(value)); } +/*! Adds a pointer to a target that is identified by its name. */ +CompilerValue *Compiler::addTargetPointer(const std::string &name) +{ + return impl->builder->addTargetPointer(name); +} + +/*! Adds a pointer to a variable that is identified by its ID. */ +CompilerValue *Compiler::addVariablePointer(Variable *variable) +{ + return impl->builder->addVariablePointer(variable); +} + +/*! Adds a pointer to a list that is identified by its ID. */ +CompilerValue *Compiler::addListPointer(List *list) +{ + return impl->builder->addListPointer(list); +} + +/*! Adds a pointer to the engine's timer. */ +CompilerValue *Compiler::addTimerPointer() +{ + return impl->builder->addTimerPointer(); +} + +/*! Adds a pointer to the graphics effect that is identified by its name. */ +CompilerValue *Compiler::addEffectPointer(const std::string &name) +{ + return impl->builder->addEffectPointer(name); +} + /*! Adds the string character with the given index to the compiled code. */ CompilerValue *Compiler::addStringChar(CompilerValue *string, CompilerValue *index) { diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp index 00008ba08..f973fb164 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include +#include #include "cppcodebuilder.h" #include "cppcompilercontext.h" @@ -100,6 +102,33 @@ CompilerConstant *CppCodeBuilder::addConstValue(const Value &value) return static_cast(static_cast(addValue(genericValue, nullptr))); } +CompilerValue *CppCodeBuilder::addTargetPointer(const std::string &name) +{ + return addValue(std::make_shared(CppObjectPointerDescriptor(CppObjectPointerDescriptor::Kind::Target, name)), nullptr); +} + +CompilerValue *CppCodeBuilder::addVariablePointer(Variable *variable) +{ + assert(variable); + return addValue(std::make_shared(CppObjectPointerDescriptor(CppObjectPointerDescriptor::Kind::Variable, variable->id())), nullptr); +} + +CompilerValue *CppCodeBuilder::addListPointer(List *list) +{ + assert(list); + return addValue(std::make_shared(CppObjectPointerDescriptor(CppObjectPointerDescriptor::Kind::List, list->id())), nullptr); +} + +CompilerValue *CppCodeBuilder::addTimerPointer() +{ + return addValue(std::make_shared(CppObjectPointerDescriptor(CppObjectPointerDescriptor::Kind::Timer)), nullptr); +} + +CompilerValue *CppCodeBuilder::addEffectPointer(const std::string &name) +{ + return addValue(std::make_shared(CppObjectPointerDescriptor(CppObjectPointerDescriptor::Kind::Effect, name)), nullptr); +} + CompilerValue *CppCodeBuilder::addStringChar(CompilerValue *string, CompilerValue *index) { return createOp(CppInstruction::Type::StringChar, Compiler::StaticType::String, { Compiler::StaticType::String, Compiler::StaticType::Number }, { string, index }); diff --git a/src/engine/internal/codegen/cpp/cppcodebuilder.h b/src/engine/internal/codegen/cpp/cppcodebuilder.h index 3f2bdb5ed..4bd476ea0 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.h +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.h @@ -28,6 +28,11 @@ class CppCodeBuilder : public ICodeBuilder CompilerValue *addTargetFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) override; CompilerValue *addFunctionCallWithCtx(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) override; CompilerConstant *addConstValue(const Value &value) override; + CompilerValue *addTargetPointer(const std::string &name) override; + CompilerValue *addVariablePointer(Variable *variable) override; + CompilerValue *addListPointer(List *list) override; + CompilerValue *addTimerPointer() override; + CompilerValue *addEffectPointer(const std::string &name) override; CompilerValue *addStringChar(CompilerValue *string, CompilerValue *index) override; CompilerValue *addStringLength(CompilerValue *string) override; CompilerValue *addLoopIndex() override; diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp index 5530e4943..8871ee2d3 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -49,17 +49,50 @@ std::string CppCodeGenerator::finalize() { static unsigned int scriptCount = 0; - const std::string scriptName = "Script" + std::to_string(scriptCount++); + const std::string scriptNumber = std::to_string(scriptCount++); + const std::string scriptName = "Script" + scriptNumber; std::ostringstream source; - source << "#include \"script" + std::to_string(scriptCount++) + ".h\"\n"; + source << "#include \"script" << scriptNumber << ".h\"\n"; for (Header header : m_includedHeaders) { source << "#include " << m_headers.at(header) << "\n"; } source << "\nnamespace libscratchcpp\n{\n\n"; - source << "void " << scriptName << "::runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists)\n{\n"; + source << scriptName << "::" << scriptName << "(CppCompilerContext *ctx) :\n"; + source << " CppExecutableCode(ctx, {"; + + for (size_t i = 0; i < m_objectPointers.size(); ++i) { + if (i) + source << ","; + + const CppObjectPointerDescriptor &descriptor = m_objectPointers[i]; + const char *kind = ""; + + switch (descriptor.kind) { + case CppObjectPointerDescriptor::Kind::Target: + kind = "Target"; + break; + case CppObjectPointerDescriptor::Kind::Variable: + kind = "Variable"; + break; + case CppObjectPointerDescriptor::Kind::List: + kind = "List"; + break; + case CppObjectPointerDescriptor::Kind::Timer: + kind = "Timer"; + break; + case CppObjectPointerDescriptor::Kind::Effect: + kind = "Effect"; + break; + } + + source << " { CppObjectPointerDescriptor::Kind::" << kind << ", \"" << escapeCppString(descriptor.key) << "\" }"; + } + + source << "})\n{\n}\n\n"; + source << "void " << scriptName << "::runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects)\n{\n"; std::unordered_set declared; const auto declare = [&](const CppIdentifier *identifier) { @@ -68,6 +101,9 @@ std::string CppCodeGenerator::finalize() const auto *named = static_cast(identifier); + if (named->name.rfind("objects[", 0) == 0) + return; + source << " " << identifier->typeString(); source << " " << named->name << ";\n"; }; @@ -102,6 +138,9 @@ std::string CppCodeGenerator::finalize() const CppIdentifier *CppCodeGenerator::castValue(CppValue *value, Compiler::StaticType targetType) { + if (auto *pointerValue = dynamic_cast(value)) + return addPointerValue(value, pointerValue->descriptor); + if (value->isConst()) { if (!TypeUtils::isSingleType(targetType)) return createValue(value); @@ -205,6 +244,22 @@ const CppIdentifier *CppCodeGenerator::castValue(CppValue *value, Compiler::Stat return result; } +const CppIdentifier *CppCodeGenerator::addPointerValue(CppValue *value, const CppObjectPointerDescriptor &descriptor) +{ + auto it = m_identifiers.find(value); + + if (it != m_identifiers.cend()) + return it->second.get(); + + const size_t index = m_objectPointers.size(); + m_objectPointers.push_back(descriptor); + + const std::string expression = "objects[" + std::to_string(index) + "]"; + auto identifier = std::make_shared(CppIdentifier::Type::Pointer, expression, false); + m_identifiers[value] = identifier; + return identifier.get(); +} + void CppCodeGenerator::createCall(const std::string &name, bool ctxArg, bool targetArg, const std::vector &args) { m_codeStream.beginLine(); @@ -562,6 +617,9 @@ std::string CppCodeGenerator::toCppConstant(const Value &value) case ValueType::String: return "\"" + escapeCppString(value.toString()) + "\""; + case ValueType::Pointer: + throw std::runtime_error("pointer constants not supported in C++ backend"); + default: throw std::runtime_error("unsupported constant type"); } diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.h b/src/engine/internal/codegen/cpp/cppcodegenerator.h index ca271d8fd..b68f0931c 100644 --- a/src/engine/internal/codegen/cpp/cppcodegenerator.h +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.h @@ -10,6 +10,7 @@ #include "cppnamedidentifier.h" #include "cppconstidentifier.h" #include "cppcodestream.h" +#include "cppobjectpointer.h" namespace libscratchcpp { @@ -55,6 +56,7 @@ class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator const CppIdentifier *getIdentifier(CppValue *value); const CppNamedIdentifier *getNamedIdentifier(CppValue *value, CppIdentifier::Type type, const std::string &name, bool isMutable, bool isReference = false); const CppNamedIdentifier *createNamedIdentifier(CppIdentifier::Type type, const std::string &name, bool isMutable); + const CppIdentifier *addPointerValue(CppValue *value, const CppObjectPointerDescriptor &descriptor); std::string getNewIdentifierName(const std::string &name); void includeHeader(Header header); @@ -83,6 +85,7 @@ class LIBSCRATCHCPP_TEST_EXPORT CppCodeGenerator std::unordered_set
m_includedHeaders; std::vector> m_internalIdentifiers; std::vector> m_constants; + std::vector m_objectPointers; CppNamedIdentifier m_stringArray; std::vector> m_strings; diff --git a/src/engine/internal/codegen/cpp/cppexecutablecode.cpp b/src/engine/internal/codegen/cpp/cppexecutablecode.cpp index 2fc611f19..04ea5a884 100644 --- a/src/engine/internal/codegen/cpp/cppexecutablecode.cpp +++ b/src/engine/internal/codegen/cpp/cppexecutablecode.cpp @@ -4,7 +4,14 @@ #include #include #include +#include +#include +#include +#include +#include +#include #include +#include #include "cppexecutablecode.h" #include "cppcompilercontext.h" @@ -12,10 +19,14 @@ using namespace libscratchcpp; -CppExecutableCode::CppExecutableCode(CppCompilerContext *ctx) : - m_ctx(ctx) +CppExecutableCode::CppExecutableCode(CppCompilerContext *ctx, std::vector objectPointers) : + m_ctx(ctx), + m_objectPointerDescriptors(std::move(objectPointers)) { assert(m_ctx); + + if (m_ctx && !m_objectPointerDescriptors.empty()) + getObjectPointers(m_ctx->engine()); } void CppExecutableCode::run(ExecutionContext *context) @@ -37,20 +48,20 @@ void CppExecutableCode::run(ExecutionContext *context) // TODO: Add support for coroutines // TODO: Add support for end thread sentinel value Target *target = ctx->thread()->target(); - runScript(context, target, target->variableData(), target->listData()); + runScript(context, target, target->variableData(), target->listData(), getObjectPointers(context->engine())); ctx->setFinished(true); } ValueData CppExecutableCode::runReporter(ExecutionContext *context) { Target *target = context->thread()->target(); - return runReporter(context, target, target->variableData(), target->listData()); + return runReporter(context, target, target->variableData(), target->listData(), getObjectPointers(context->engine())); } bool CppExecutableCode::runPredicate(ExecutionContext *context) { Target *target = context->thread()->target(); - return runPredicate(context, target, target->variableData(), target->listData()); + return runPredicate(context, target, target->variableData(), target->listData(), getObjectPointers(context->engine())); } void CppExecutableCode::kill(ExecutionContext *context) @@ -83,23 +94,86 @@ std::shared_ptr CppExecutableCode::createExecutionContext(Thre return std::make_shared(m_ctx, thread); } -void CppExecutableCode::runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists) +void CppExecutableCode::runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects) { // Generated code overrides this } -ValueData CppExecutableCode::runReporter(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists) +ValueData CppExecutableCode::runReporter(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects) { // Generated code overrides this return ValueData(); } -bool CppExecutableCode::runPredicate(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists) +bool CppExecutableCode::runPredicate(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects) { // Generated code overrides this return false; } +void **CppExecutableCode::getObjectPointers(IEngine *engine) const +{ + if (m_objectPointerDescriptors.empty()) + return nullptr; + + std::lock_guard lock(m_objectPointerMutex); + auto it = m_objectPointersByEngine.find(engine); + + if (it == m_objectPointersByEngine.cend()) { + std::vector pointers(m_objectPointerDescriptors.size(), nullptr); + + for (size_t i = 0; i < m_objectPointerDescriptors.size(); ++i) { + const CppObjectPointerDescriptor &descriptor = m_objectPointerDescriptors[i]; + + switch (descriptor.kind) { + case CppObjectPointerDescriptor::Kind::Target: { + const int targetIndex = engine->findTarget(descriptor.key); + + if (targetIndex >= 0) + pointers[i] = engine->targetAt(targetIndex); + + break; + } + + case CppObjectPointerDescriptor::Kind::Variable: + case CppObjectPointerDescriptor::Kind::List: { + for (const auto &target : engine->targets()) { + if (descriptor.kind == CppObjectPointerDescriptor::Kind::Variable) { + const int index = target->findVariableById(descriptor.key); + + if (index >= 0) { + pointers[i] = target->variableAt(index).get(); + break; + } + } else { + const int index = target->findListById(descriptor.key); + + if (index >= 0) { + pointers[i] = target->listAt(index).get(); + break; + } + } + } + + break; + } + + case CppObjectPointerDescriptor::Kind::Timer: + pointers[i] = engine->timer(); + break; + + case CppObjectPointerDescriptor::Kind::Effect: + pointers[i] = ScratchConfiguration::getGraphicsEffect(descriptor.key); + break; + } + } + + it = m_objectPointersByEngine.emplace(engine, std::move(pointers)).first; + } + + return it->second.data(); +} + CppExecutionContext *CppExecutableCode::getContext(ExecutionContext *context) { assert(dynamic_cast(context)); diff --git a/src/engine/internal/codegen/cpp/cppexecutablecode.h b/src/engine/internal/codegen/cpp/cppexecutablecode.h index 97ce1f0a0..8ce9ba2af 100644 --- a/src/engine/internal/codegen/cpp/cppexecutablecode.h +++ b/src/engine/internal/codegen/cpp/cppexecutablecode.h @@ -4,6 +4,11 @@ #include +#include +#include +#include + +#include "cppobjectpointer.h" #include "test_export.h" namespace libscratchcpp @@ -11,13 +16,14 @@ namespace libscratchcpp class Target; class List; +class IEngine; class CppCompilerContext; class CppExecutionContext; class LIBSCRATCHCPP_TEST_EXPORT CppExecutableCode : public ExecutableCode { public: - CppExecutableCode(CppCompilerContext *ctx); + CppExecutableCode(CppCompilerContext *ctx, std::vector objectPointers = {}); virtual void run(ExecutionContext *context) override final; virtual ValueData runReporter(ExecutionContext *context) override final; @@ -30,14 +36,18 @@ class LIBSCRATCHCPP_TEST_EXPORT CppExecutableCode : public ExecutableCode virtual std::shared_ptr createExecutionContext(Thread *thread) const override final; protected: - virtual void runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists); - virtual ValueData runReporter(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists); - virtual bool runPredicate(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists); + virtual void runScript(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects); + virtual ValueData runReporter(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects); + virtual bool runPredicate(ExecutionContext *ctx, Target *target, ValueData **targetVariables, List **targetLists, void **objects); private: static CppExecutionContext *getContext(ExecutionContext *context); + void **getObjectPointers(IEngine *engine) const; CppCompilerContext *m_ctx = nullptr; + std::vector m_objectPointerDescriptors; + mutable std::mutex m_objectPointerMutex; + mutable std::unordered_map> m_objectPointersByEngine; }; } // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/cppobjectpointer.h b/src/engine/internal/codegen/cpp/cppobjectpointer.h new file mode 100644 index 000000000..d5e209ed0 --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppobjectpointer.h @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include + +namespace libscratchcpp +{ + +struct CppObjectPointerDescriptor +{ + enum class Kind + { + Target, + Variable, + List, + Timer, + Effect + }; + + CppObjectPointerDescriptor(Kind kind, const std::string &key = "") : + kind(kind), + key(key) + { + } + + Kind kind; + std::string key; +}; + +} // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/cppvalue.h b/src/engine/internal/codegen/cpp/cppvalue.h index 77f6d7824..679fb689a 100644 --- a/src/engine/internal/codegen/cpp/cppvalue.h +++ b/src/engine/internal/codegen/cpp/cppvalue.h @@ -5,6 +5,10 @@ #include #include +#include + +#include "cppobjectpointer.h" + namespace libscratchcpp { @@ -28,4 +32,17 @@ struct CppValue : public virtual CompilerValue std::shared_ptr instruction; }; +struct CppPointerValue : public CppValue +{ + CppPointerValue(CppObjectPointerDescriptor descriptor) : + CompilerValue(Compiler::StaticType::Pointer), + CppValue(Compiler::StaticType::Pointer), + descriptor(std::move(descriptor)) + { + isRawValue = true; + } + + CppObjectPointerDescriptor descriptor; +}; + } // namespace libscratchcpp diff --git a/src/engine/internal/codegen/icodebuilder.h b/src/engine/internal/codegen/icodebuilder.h index cb8d2f95a..72b859da0 100644 --- a/src/engine/internal/codegen/icodebuilder.h +++ b/src/engine/internal/codegen/icodebuilder.h @@ -24,6 +24,11 @@ class ICodeBuilder virtual CompilerValue *addTargetFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) = 0; virtual CompilerValue *addFunctionCallWithCtx(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) = 0; virtual CompilerConstant *addConstValue(const Value &value) = 0; + virtual CompilerValue *addTargetPointer(const std::string &name) = 0; + virtual CompilerValue *addVariablePointer(Variable *variable) = 0; + virtual CompilerValue *addListPointer(List *list) = 0; + virtual CompilerValue *addTimerPointer() = 0; + virtual CompilerValue *addEffectPointer(const std::string &name) = 0; virtual CompilerValue *addStringChar(CompilerValue *string, CompilerValue *index) = 0; virtual CompilerValue *addStringLength(CompilerValue *string) = 0; virtual CompilerValue *addLoopIndex() = 0; diff --git a/src/engine/internal/codegen/llvm/llvmcodebuilder.cpp b/src/engine/internal/codegen/llvm/llvmcodebuilder.cpp index 32d445ada..ce7c4a84e 100644 --- a/src/engine/internal/codegen/llvm/llvmcodebuilder.cpp +++ b/src/engine/internal/codegen/llvm/llvmcodebuilder.cpp @@ -6,6 +6,9 @@ #include #include #include +#include +#include +#include #include #include @@ -144,6 +147,35 @@ CompilerConstant *LLVMCodeBuilder::addConstValue(const Value &value) return static_cast(static_cast(addReg(reg, nullptr))); } +CompilerValue *LLVMCodeBuilder::addTargetPointer(const std::string &name) +{ + IEngine *engine = m_ctx->engine(); + const int targetIndex = engine->findTarget(name); + Target *target = targetIndex >= 0 ? engine->targetAt(targetIndex) : nullptr; + + return addConstValue(Value(static_cast(target))); +} + +CompilerValue *LLVMCodeBuilder::addVariablePointer(Variable *variable) +{ + return addConstValue(Value(static_cast(variable))); +} + +CompilerValue *LLVMCodeBuilder::addListPointer(List *list) +{ + return addConstValue(Value(static_cast(list))); +} + +CompilerValue *LLVMCodeBuilder::addTimerPointer() +{ + return addConstValue(Value(static_cast(m_ctx->engine()->timer()))); +} + +CompilerValue *LLVMCodeBuilder::addEffectPointer(const std::string &name) +{ + return addConstValue(Value(static_cast(ScratchConfiguration::getGraphicsEffect(name)))); +} + CompilerValue *LLVMCodeBuilder::addStringChar(CompilerValue *string, CompilerValue *index) { return createOp(LLVMInstruction::Type::StringChar, Compiler::StaticType::String, { Compiler::StaticType::String, Compiler::StaticType::Number }, { string, index }); diff --git a/src/engine/internal/codegen/llvm/llvmcodebuilder.h b/src/engine/internal/codegen/llvm/llvmcodebuilder.h index 123eefd6f..0f85ae1a6 100644 --- a/src/engine/internal/codegen/llvm/llvmcodebuilder.h +++ b/src/engine/internal/codegen/llvm/llvmcodebuilder.h @@ -38,6 +38,11 @@ class LIBSCRATCHCPP_TEST_EXPORT LLVMCodeBuilder : public ICodeBuilder CompilerValue *addTargetFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) override; CompilerValue *addFunctionCallWithCtx(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args) override; CompilerConstant *addConstValue(const Value &value) override; + CompilerValue *addTargetPointer(const std::string &name) override; + CompilerValue *addVariablePointer(Variable *variable) override; + CompilerValue *addListPointer(List *list) override; + CompilerValue *addTimerPointer() override; + CompilerValue *addEffectPointer(const std::string &name) override; CompilerValue *addStringChar(CompilerValue *string, CompilerValue *index) override; CompilerValue *addStringLength(CompilerValue *string) override; CompilerValue *addLoopIndex() override; diff --git a/test/blocks/motion_blocks_test.cpp b/test/blocks/motion_blocks_test.cpp index b5758bae7..dc8f3fd91 100644 --- a/test/blocks/motion_blocks_test.cpp +++ b/test/blocks/motion_blocks_test.cpp @@ -312,13 +312,13 @@ TEST_F(MotionBlocksTest, PointTowardsSprite) anotherSprite->setY(-123.48); anotherSprite->setDirection(-2.5); + EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(2)); + EXPECT_CALL(m_engineMock, targetAt(2)).WillRepeatedly(Return(anotherSprite.get())); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_pointtowards"); builder.addDropdownInput("TOWARDS", "def"); auto block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("def")).WillOnce(Return(2)); - EXPECT_CALL(m_engineMock, targetAt(2)).WillRepeatedly(Return(anotherSprite.get())); Compiler compiler(&m_engineMock, sprite.get()); auto code = compiler.compile(block); Script script(sprite.get(), block, &m_engineMock); @@ -337,13 +337,13 @@ TEST_F(MotionBlocksTest, PointTowardsSprite) sprite->setY(-100.025); sprite->setDirection(21.58); + EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(2)); + EXPECT_CALL(m_engineMock, targetAt(2)).WillRepeatedly(Return(nullptr)); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_pointtowards"); builder.addDropdownInput("TOWARDS", "def"); auto block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("def")).WillOnce(Return(2)); - EXPECT_CALL(m_engineMock, targetAt(2)).WillRepeatedly(Return(nullptr)); Compiler compiler(&m_engineMock, sprite.get()); auto code = compiler.compile(block); Script script(sprite.get(), block, &m_engineMock); @@ -364,13 +364,13 @@ TEST_F(MotionBlocksTest, PointTowardsSprite) auto stage = std::make_shared(); + EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(0)); + EXPECT_CALL(m_engineMock, targetAt(0)).WillRepeatedly(Return(stage.get())); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_pointtowards"); builder.addDropdownInput("TOWARDS", "_stage_"); auto block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillOnce(Return(0)); - EXPECT_CALL(m_engineMock, targetAt(0)).WillOnce(Return(stage.get())); Compiler compiler(&m_engineMock, sprite.get()); auto code = compiler.compile(block); Script script(sprite.get(), block, &m_engineMock); @@ -396,6 +396,8 @@ TEST_F(MotionBlocksTest, PointTowardsSprite) anotherSprite->setY(-3.21); anotherSprite->setDirection(82.54); + EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(5)); + EXPECT_CALL(m_engineMock, targetAt(5)).WillRepeatedly(Return(anotherSprite.get())); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_pointtowards"); builder.addValueInput("TOWARDS", "def"); @@ -407,8 +409,6 @@ TEST_F(MotionBlocksTest, PointTowardsSprite) script.setCode(code); Thread thread(sprite.get(), &m_engineMock, &script); - EXPECT_CALL(m_engineMock, findTarget("def")).WillOnce(Return(5)); - EXPECT_CALL(m_engineMock, targetAt(5)).WillOnce(Return(anotherSprite.get())); thread.run(); ASSERT_EQ(std::round(sprite->direction() * 100) / 100, 29.66); } @@ -421,6 +421,8 @@ TEST_F(MotionBlocksTest, PointTowardsSprite) sprite->setY(-100.025); sprite->setDirection(21.58); + EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(5)); + EXPECT_CALL(m_engineMock, targetAt(5)).WillRepeatedly(Return(nullptr)); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_pointtowards"); builder.addValueInput("TOWARDS", "def"); @@ -432,8 +434,6 @@ TEST_F(MotionBlocksTest, PointTowardsSprite) script.setCode(code); Thread thread(sprite.get(), &m_engineMock, &script); - EXPECT_CALL(m_engineMock, findTarget("def")).WillOnce(Return(5)); - EXPECT_CALL(m_engineMock, targetAt(5)).WillOnce(Return(nullptr)); thread.run(); ASSERT_EQ(sprite->direction(), 21.58); } @@ -448,6 +448,8 @@ TEST_F(MotionBlocksTest, PointTowardsSprite) auto stage = std::make_shared(); + EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(0)); + EXPECT_CALL(m_engineMock, targetAt(0)).WillRepeatedly(Return(stage.get())); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_pointtowards"); builder.addValueInput("TOWARDS", "_stage_"); @@ -459,8 +461,6 @@ TEST_F(MotionBlocksTest, PointTowardsSprite) script.setCode(code); Thread thread(sprite.get(), &m_engineMock, &script); - EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillOnce(Return(0)); - EXPECT_CALL(m_engineMock, targetAt(0)).WillOnce(Return(stage.get())); thread.run(); ASSERT_EQ(std::round(sprite->direction() * 100) / 100, 21.58); } @@ -674,13 +674,13 @@ TEST_F(MotionBlocksTest, GoToSprite) anotherSprite->setX(-45.12); anotherSprite->setY(-123.48); + EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(2)); + EXPECT_CALL(m_engineMock, targetAt(2)).WillRepeatedly(Return(anotherSprite.get())); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_goto"); builder.addDropdownInput("TO", "def"); auto block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("def")).WillOnce(Return(2)); - EXPECT_CALL(m_engineMock, targetAt(2)).WillRepeatedly(Return(anotherSprite.get())); Compiler compiler(&m_engineMock, sprite.get()); auto code = compiler.compile(block); Script script(sprite.get(), block, &m_engineMock); @@ -699,13 +699,13 @@ TEST_F(MotionBlocksTest, GoToSprite) sprite->setX(70.1); sprite->setY(-100.025); + EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(2)); + EXPECT_CALL(m_engineMock, targetAt(2)).WillRepeatedly(Return(nullptr)); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_goto"); builder.addDropdownInput("TO", "def"); auto block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("def")).WillOnce(Return(2)); - EXPECT_CALL(m_engineMock, targetAt(2)).WillRepeatedly(Return(nullptr)); Compiler compiler(&m_engineMock, sprite.get()); auto code = compiler.compile(block); Script script(sprite.get(), block, &m_engineMock); @@ -726,13 +726,13 @@ TEST_F(MotionBlocksTest, GoToSprite) auto stage = std::make_shared(); + EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(0)); + EXPECT_CALL(m_engineMock, targetAt(0)).WillRepeatedly(Return(stage.get())); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_goto"); builder.addDropdownInput("TO", "_stage_"); auto block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillOnce(Return(0)); - EXPECT_CALL(m_engineMock, targetAt(0)).WillOnce(Return(stage.get())); Compiler compiler(&m_engineMock, sprite.get()); auto code = compiler.compile(block); Script script(sprite.get(), block, &m_engineMock); @@ -757,6 +757,8 @@ TEST_F(MotionBlocksTest, GoToSprite) anotherSprite->setX(125.23); anotherSprite->setY(-3.21); + EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(5)); + EXPECT_CALL(m_engineMock, targetAt(5)).WillRepeatedly(Return(anotherSprite.get())); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_goto"); builder.addValueInput("TO", "def"); @@ -768,8 +770,6 @@ TEST_F(MotionBlocksTest, GoToSprite) script.setCode(code); Thread thread(sprite.get(), &m_engineMock, &script); - EXPECT_CALL(m_engineMock, findTarget("def")).WillOnce(Return(5)); - EXPECT_CALL(m_engineMock, targetAt(5)).WillOnce(Return(anotherSprite.get())); thread.run(); ASSERT_EQ(sprite->x(), 125.23); ASSERT_EQ(sprite->y(), -3.21); @@ -782,6 +782,8 @@ TEST_F(MotionBlocksTest, GoToSprite) sprite->setX(70.1); sprite->setY(-100.025); + EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(5)); + EXPECT_CALL(m_engineMock, targetAt(5)).WillRepeatedly(Return(nullptr)); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_goto"); builder.addValueInput("TO", "def"); @@ -793,8 +795,6 @@ TEST_F(MotionBlocksTest, GoToSprite) script.setCode(code); Thread thread(sprite.get(), &m_engineMock, &script); - EXPECT_CALL(m_engineMock, findTarget("def")).WillOnce(Return(5)); - EXPECT_CALL(m_engineMock, targetAt(5)).WillOnce(Return(nullptr)); thread.run(); ASSERT_EQ(sprite->x(), 70.1); ASSERT_EQ(sprite->y(), -100.025); @@ -809,6 +809,8 @@ TEST_F(MotionBlocksTest, GoToSprite) auto stage = std::make_shared(); + EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(0)); + EXPECT_CALL(m_engineMock, targetAt(0)).WillRepeatedly(Return(stage.get())); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_goto"); builder.addValueInput("TO", "_stage_"); @@ -820,8 +822,6 @@ TEST_F(MotionBlocksTest, GoToSprite) script.setCode(code); Thread thread(sprite.get(), &m_engineMock, &script); - EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillOnce(Return(0)); - EXPECT_CALL(m_engineMock, targetAt(0)).WillOnce(Return(stage.get())); thread.run(); ASSERT_EQ(sprite->x(), 70.1); ASSERT_EQ(sprite->y(), -100.025); @@ -1283,14 +1283,14 @@ TEST_F(MotionBlocksTest, GlideToSprite) anotherSprite->setX(-45.12); anotherSprite->setY(-123.48); + EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(2)); + EXPECT_CALL(m_engineMock, targetAt(2)).WillRepeatedly(Return(anotherSprite.get())); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_glideto"); builder.addValueInput("SECS", 2.5); builder.addDropdownInput("TO", "def"); auto block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("def")).WillOnce(Return(2)); - EXPECT_CALL(m_engineMock, targetAt(2)).WillRepeatedly(Return(anotherSprite.get())); Compiler compiler(&m_engineMock, sprite.get()); auto code = compiler.compile(block); Script script(sprite.get(), block, &m_engineMock); @@ -1327,14 +1327,14 @@ TEST_F(MotionBlocksTest, GlideToSprite) sprite->setX(70.1); sprite->setY(-100.025); + EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(2)); + EXPECT_CALL(m_engineMock, targetAt(2)).WillRepeatedly(Return(nullptr)); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_glideto"); builder.addValueInput("SECS", 2.5); builder.addDropdownInput("TO", "def"); auto block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("def")).WillOnce(Return(2)); - EXPECT_CALL(m_engineMock, targetAt(2)).WillRepeatedly(Return(nullptr)); Compiler compiler(&m_engineMock, sprite.get()); auto code = compiler.compile(block); Script script(sprite.get(), block, &m_engineMock); @@ -1363,14 +1363,14 @@ TEST_F(MotionBlocksTest, GlideToSprite) auto stage = std::make_shared(); + EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(0)); + EXPECT_CALL(m_engineMock, targetAt(0)).WillRepeatedly(Return(stage.get())); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_glideto"); builder.addValueInput("SECS", 2.5); builder.addDropdownInput("TO", "_stage_"); auto block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillOnce(Return(0)); - EXPECT_CALL(m_engineMock, targetAt(0)).WillOnce(Return(stage.get())); Compiler compiler(&m_engineMock, sprite.get()); auto code = compiler.compile(block); Script script(sprite.get(), block, &m_engineMock); @@ -1403,6 +1403,8 @@ TEST_F(MotionBlocksTest, GlideToSprite) anotherSprite->setX(-45.12); anotherSprite->setY(-123.48); + EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(5)); + EXPECT_CALL(m_engineMock, targetAt(5)).WillRepeatedly(Return(anotherSprite.get())); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_glideto"); builder.addValueInput("SECS", 2.5); @@ -1418,8 +1420,6 @@ TEST_F(MotionBlocksTest, GlideToSprite) StackTimerMock timer; ctx->setStackTimer(&timer); - EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(5)); - EXPECT_CALL(m_engineMock, targetAt(5)).WillRepeatedly(Return(anotherSprite.get())); EXPECT_CALL(timer, start(2.5)); EXPECT_CALL(m_engineMock, requestRedraw()).WillRepeatedly(Return()); @@ -1448,6 +1448,8 @@ TEST_F(MotionBlocksTest, GlideToSprite) sprite->setX(70.1); sprite->setY(-100.025); + EXPECT_CALL(m_engineMock, findTarget("def")).WillRepeatedly(Return(5)); + EXPECT_CALL(m_engineMock, targetAt(5)).WillRepeatedly(Return(nullptr)); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_glideto"); builder.addValueInput("SECS", 2.5); @@ -1466,8 +1468,6 @@ TEST_F(MotionBlocksTest, GlideToSprite) EXPECT_CALL(m_engineMock, requestRedraw).Times(0); EXPECT_CALL(timer, start).Times(0); - EXPECT_CALL(m_engineMock, findTarget("def")).WillOnce(Return(5)); - EXPECT_CALL(m_engineMock, targetAt(5)).WillOnce(Return(nullptr)); code->run(ctx.get()); ASSERT_EQ(sprite->x(), 70.1); ASSERT_EQ(sprite->y(), -100.025); @@ -1484,6 +1484,8 @@ TEST_F(MotionBlocksTest, GlideToSprite) auto stage = std::make_shared(); + EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(0)); + EXPECT_CALL(m_engineMock, targetAt(0)).WillRepeatedly(Return(stage.get())); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("motion_glideto"); builder.addValueInput("SECS", 2.5); @@ -1502,8 +1504,6 @@ TEST_F(MotionBlocksTest, GlideToSprite) EXPECT_CALL(m_engineMock, requestRedraw).Times(0); EXPECT_CALL(timer, start).Times(0); - EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillOnce(Return(0)); - EXPECT_CALL(m_engineMock, targetAt(0)).WillOnce(Return(stage.get())); code->run(ctx.get()); ASSERT_EQ(sprite->x(), 70.1); ASSERT_EQ(sprite->y(), -100.025); @@ -1520,6 +1520,8 @@ TEST_F(MotionBlocksTest, GlideToSprite) sprite->setX(153.2); sprite->setY(59.27); + EXPECT_CALL(m_engineMock, findTarget("Test")).WillRepeatedly(Return(9)); + EXPECT_CALL(m_engineMock, targetAt(9)).WillRepeatedly(Return(sprite.get())); ScriptBuilder builder(m_extension.get(), m_engine, stage); builder.addBlock("motion_glideto"); @@ -1527,8 +1529,6 @@ TEST_F(MotionBlocksTest, GlideToSprite) builder.addDropdownInput("TO", "Test"); auto block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("Test")).WillOnce(Return(9)); - EXPECT_CALL(m_engineMock, targetAt(9)).WillOnce(Return(sprite.get())); Compiler compiler(&m_engineMock, stage.get()); auto code = compiler.compile(block); Script script(stage.get(), block, &m_engineMock); @@ -1563,6 +1563,8 @@ TEST_F(MotionBlocksTest, GlideToSprite) sprite->setX(153.2); sprite->setY(59.27); + EXPECT_CALL(m_engineMock, findTarget("Test")).WillRepeatedly(Return(9)); + EXPECT_CALL(m_engineMock, targetAt(9)).WillRepeatedly(Return(sprite.get())); ScriptBuilder builder(m_extension.get(), m_engine, stage); builder.addBlock("motion_glideto"); @@ -1581,8 +1583,6 @@ TEST_F(MotionBlocksTest, GlideToSprite) EXPECT_CALL(m_engineMock, requestRedraw).Times(0); - EXPECT_CALL(m_engineMock, findTarget("Test")).WillOnce(Return(9)); - EXPECT_CALL(m_engineMock, targetAt(9)).WillOnce(Return(sprite.get())); EXPECT_CALL(timer, start(2.5)); code->run(ctx.get()); ASSERT_FALSE(code->isFinished(ctx.get())); diff --git a/test/blocks/sensing_blocks_test.cpp b/test/blocks/sensing_blocks_test.cpp index 939cc8bb6..238485a77 100644 --- a/test/blocks/sensing_blocks_test.cpp +++ b/test/blocks/sensing_blocks_test.cpp @@ -76,13 +76,14 @@ TEST_F(SensingBlocksTest, TouchingObject_Sprite_CompileTime) Sprite sprite; + EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(3)); + EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&sprite)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_touchingobject"); builder.addDropdownInput("TOUCHINGOBJECTMENU", "Sprite2"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillOnce(Return(3)); - EXPECT_CALL(m_engineMock, targetAt(3)).WillOnce(Return(&sprite)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -144,13 +145,14 @@ TEST_F(SensingBlocksTest, TouchingObject_Stage_CompileTime) Stage stage; + EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(3)); + EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&stage)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_touchingobject"); builder.addDropdownInput("TOUCHINGOBJECTMENU", "_stage_"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(3)); - EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&stage)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -354,12 +356,12 @@ TEST_F(SensingBlocksTest, TouchingObject_Invalid_CompileTime) Sprite sprite; + EXPECT_CALL(m_engineMock, findTarget("test")).WillRepeatedly(Return(-1)); ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_touchingobject"); builder.addDropdownInput("TOUCHINGOBJECTMENU", "test"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("test")).WillOnce(Return(-1)); EXPECT_CALL(m_engineMock, targetAt).WillRepeatedly(Return(nullptr)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); @@ -519,13 +521,14 @@ TEST_F(SensingBlocksTest, DistanceTo_Sprite_CompileTime) Sprite targetSprite; + EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(3)); + EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&targetSprite)); + ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("sensing_distanceto"); builder.addDropdownInput("DISTANCETOMENU", "Sprite2"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillOnce(Return(3)); - EXPECT_CALL(m_engineMock, targetAt(3)).WillOnce(Return(&targetSprite)); Compiler compiler(&m_engineMock, sprite.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(sprite.get(), block, &m_engineMock); @@ -615,13 +618,14 @@ TEST_F(SensingBlocksTest, DistanceTo_Stage_CompileTime) Stage stage; + EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(3)); + EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&stage)); + ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("sensing_distanceto"); builder.addDropdownInput("DISTANCETOMENU", "_stage_"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(3)); - EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&stage)); Compiler compiler(&m_engineMock, sprite.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(sprite.get(), block, &m_engineMock); @@ -731,12 +735,12 @@ TEST_F(SensingBlocksTest, DistanceTo_Invalid_CompileTime) auto sprite = std::make_shared(); sprite->setEngine(&m_engineMock); + EXPECT_CALL(m_engineMock, findTarget("test")).WillRepeatedly(Return(-1)); ScriptBuilder builder(m_extension.get(), m_engine, sprite); builder.addBlock("sensing_distanceto"); builder.addDropdownInput("DISTANCETOMENU", "test"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("test")).WillOnce(Return(-1)); EXPECT_CALL(m_engineMock, targetAt).WillRepeatedly(Return(nullptr)); Compiler compiler(&m_engineMock, sprite.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); @@ -1519,14 +1523,15 @@ TEST_F(SensingBlocksTest, Of_XPositionOfSprite_CompileTime) targetSprite.setX(65.41); targetSprite.setY(-56.28); + EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(4)); + EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&targetSprite)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "x position"); builder.addDropdownInput("OBJECT", "Sprite2"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillOnce(Return(4)); - EXPECT_CALL(m_engineMock, targetAt(4)).WillOnce(Return(&targetSprite)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -1580,14 +1585,15 @@ TEST_F(SensingBlocksTest, Of_YPositionOfSprite_CompileTime) targetSprite.setX(65.41); targetSprite.setY(-56.28); + EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(4)); + EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&targetSprite)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "y position"); builder.addDropdownInput("OBJECT", "Sprite2"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillOnce(Return(4)); - EXPECT_CALL(m_engineMock, targetAt(4)).WillOnce(Return(&targetSprite)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -1640,14 +1646,15 @@ TEST_F(SensingBlocksTest, Of_DirectionOfSprite_CompileTime) Sprite targetSprite; targetSprite.setDirection(73.8); + EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(4)); + EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&targetSprite)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "direction"); builder.addDropdownInput("OBJECT", "Sprite2"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillOnce(Return(4)); - EXPECT_CALL(m_engineMock, targetAt(4)).WillOnce(Return(&targetSprite)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -1701,14 +1708,15 @@ TEST_F(SensingBlocksTest, Of_CostumeNumberOfSprite_CompileTime) targetSprite.addCostume(std::make_shared("costume2", "b", "svg")); targetSprite.setCostumeIndex(1); + EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(4)); + EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&targetSprite)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "costume #"); builder.addDropdownInput("OBJECT", "Sprite2"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillOnce(Return(4)); - EXPECT_CALL(m_engineMock, targetAt(4)).WillOnce(Return(&targetSprite)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -1764,14 +1772,15 @@ TEST_F(SensingBlocksTest, Of_CostumeNameOfSprite_CompileTime) targetSprite.addCostume(std::make_shared("costume2", "b", "svg")); targetSprite.setCostumeIndex(1); + EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(4)); + EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&targetSprite)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "costume name"); builder.addDropdownInput("OBJECT", "Sprite2"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillOnce(Return(4)); - EXPECT_CALL(m_engineMock, targetAt(4)).WillOnce(Return(&targetSprite)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -1829,14 +1838,15 @@ TEST_F(SensingBlocksTest, Of_SizeOfSprite_CompileTime) Sprite targetSprite; targetSprite.setSize(47.32); + EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(4)); + EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&targetSprite)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "size"); builder.addDropdownInput("OBJECT", "Sprite2"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillOnce(Return(4)); - EXPECT_CALL(m_engineMock, targetAt(4)).WillOnce(Return(&targetSprite)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -1888,14 +1898,15 @@ TEST_F(SensingBlocksTest, Of_VolumeOfTarget_CompileTime) TargetMock target; target.setVolume(89.46); + EXPECT_CALL(m_engineMock, findTarget("test")).WillRepeatedly(Return(4)); + EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&target)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "volume"); builder.addDropdownInput("OBJECT", "test"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("test")).WillOnce(Return(4)); - EXPECT_CALL(m_engineMock, targetAt(4)).WillOnce(Return(&target)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -1952,14 +1963,15 @@ TEST_F(SensingBlocksTest, Of_VariableOfTarget_CompileTime) target.addVariable(v2); target.addVariable(v3); + EXPECT_CALL(m_engineMock, findTarget("test")).WillRepeatedly(Return(4)); + EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&target)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "var2"); builder.addDropdownInput("OBJECT", "test"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("test")).WillOnce(Return(4)); - EXPECT_CALL(m_engineMock, targetAt(4)).WillOnce(Return(&target)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -2019,14 +2031,15 @@ TEST_F(SensingBlocksTest, Of_BackdropNumberOfStage_CompileTime) stage.addCostume(std::make_shared("backdrop3", "b", "svg")); stage.setCostumeIndex(2); + EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(3)); + EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&stage)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "backdrop #"); builder.addDropdownInput("OBJECT", "_stage_"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(3)); - EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&stage)); EXPECT_CALL(m_engineMock, stage()).WillRepeatedly(Return(&stage)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); @@ -2086,14 +2099,15 @@ TEST_F(SensingBlocksTest, Of_BackdropNameOfStage_CompileTime) stage.addCostume(std::make_shared("backdrop3", "b", "svg")); stage.setCostumeIndex(2); + EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(3)); + EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&stage)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "backdrop name"); builder.addDropdownInput("OBJECT", "_stage_"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(3)); - EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&stage)); EXPECT_CALL(m_engineMock, stage()).WillRepeatedly(Return(&stage)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); @@ -2151,14 +2165,15 @@ TEST_F(SensingBlocksTest, Of_InvalidTarget_CompileTime) auto targetMock = std::make_shared(); targetMock->setEngine(&m_engineMock); + EXPECT_CALL(m_engineMock, findTarget("test")).WillRepeatedly(Return(-1)); + EXPECT_CALL(m_engineMock, targetAt(-1)).WillRepeatedly(Return(nullptr)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "volume"); builder.addDropdownInput("OBJECT", "test"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("test")).WillOnce(Return(-1)); - EXPECT_CALL(m_engineMock, targetAt(-1)).WillRepeatedly(Return(nullptr)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -2206,14 +2221,15 @@ TEST_F(SensingBlocksTest, Of_InvalidProperty_Sprite_CompileTime) Sprite targetSprite; + EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(4)); + EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&targetSprite)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "test"); builder.addDropdownInput("OBJECT", "Sprite2"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(4)); - EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&targetSprite)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -2263,14 +2279,15 @@ TEST_F(SensingBlocksTest, Of_InvalidProperty_Stage_CompileTime) Stage stage; + EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(4)); + EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&stage)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "test"); builder.addDropdownInput("OBJECT", "Sprite2"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(4)); - EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&stage)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -2320,14 +2337,15 @@ TEST_F(SensingBlocksTest, Of_Invalid_XPositionOfStage_CompileTime) Stage stage; + EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(3)); + EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&stage)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "x position"); builder.addDropdownInput("OBJECT", "_stage_"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(3)); - EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&stage)); EXPECT_CALL(m_engineMock, stage()).WillRepeatedly(Return(&stage)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); @@ -2383,14 +2401,15 @@ TEST_F(SensingBlocksTest, Of_Invalid_CostumeNumberOfStage_CompileTime) stage.addCostume(std::make_shared("backdrop3", "b", "svg")); stage.setCostumeIndex(2); + EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(3)); + EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&stage)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "costume #"); builder.addDropdownInput("OBJECT", "_stage_"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("_stage_")).WillRepeatedly(Return(3)); - EXPECT_CALL(m_engineMock, targetAt(3)).WillRepeatedly(Return(&stage)); EXPECT_CALL(m_engineMock, stage()).WillRepeatedly(Return(&stage)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); @@ -2451,14 +2470,15 @@ TEST_F(SensingBlocksTest, Of_Invalid_BackdropNameOfSprite_CompileTime) targetSprite.addCostume(std::make_shared("costume2", "b", "svg")); targetSprite.setCostumeIndex(1); + EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillRepeatedly(Return(4)); + EXPECT_CALL(m_engineMock, targetAt(4)).WillRepeatedly(Return(&targetSprite)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "backdrop name"); builder.addDropdownInput("OBJECT", "Sprite2"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("Sprite2")).WillOnce(Return(4)); - EXPECT_CALL(m_engineMock, targetAt(4)).WillOnce(Return(&targetSprite)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); @@ -2521,14 +2541,15 @@ TEST_F(SensingBlocksTest, Of_PreferPropertiesOverVariables_CompileTime) sprite.setX(-78.25); + EXPECT_CALL(m_engineMock, findTarget("test")).WillRepeatedly(Return(7)); + EXPECT_CALL(m_engineMock, targetAt(7)).WillRepeatedly(Return(&sprite)); + ScriptBuilder builder(m_extension.get(), m_engine, targetMock); builder.addBlock("sensing_of"); builder.addDropdownField("PROPERTY", "x position"); builder.addDropdownInput("OBJECT", "test"); Block *block = builder.currentBlock(); - EXPECT_CALL(m_engineMock, findTarget("test")).WillOnce(Return(7)); - EXPECT_CALL(m_engineMock, targetAt(7)).WillOnce(Return(&sprite)); Compiler compiler(&m_engineMock, targetMock.get()); auto code = compiler.compile(block, Compiler::CodeType::Reporter); Script script(targetMock.get(), block, &m_engineMock); diff --git a/test/codegen/cpp/cppexecutablecode_test.cpp b/test/codegen/cpp/cppexecutablecode_test.cpp index 170ad438b..c49fc5222 100644 --- a/test/codegen/cpp/cppexecutablecode_test.cpp +++ b/test/codegen/cpp/cppexecutablecode_test.cpp @@ -56,7 +56,7 @@ TEST_F(CppExecutableCodeTest, ScriptFunction) auto ctx = m_code->createExecutionContext(&thread); ASSERT_FALSE(m_code->isFinished(ctx.get())); - EXPECT_CALL(*m_code, runScript(ctx.get(), &m_target, m_target.variableData(), m_target.listData())); + EXPECT_CALL(*m_code, runScript(ctx.get(), &m_target, m_target.variableData(), m_target.listData(), nullptr)); m_code->run(ctx.get()); ASSERT_TRUE(m_code->isFinished(ctx.get())); @@ -84,7 +84,7 @@ TEST_F(CppExecutableCodeTest, ScriptFunction) ASSERT_FALSE(m_code->isFinished(anotherCtx.get())); ASSERT_TRUE(m_code->isFinished(ctx.get())); - EXPECT_CALL(*m_code, runScript(anotherCtx.get(), &anotherTarget, anotherTarget.variableData(), anotherTarget.listData())); + EXPECT_CALL(*m_code, runScript(anotherCtx.get(), &anotherTarget, anotherTarget.variableData(), anotherTarget.listData(), nullptr)); m_code->run(anotherCtx.get()); ASSERT_TRUE(m_code->isFinished(anotherCtx.get())); ASSERT_TRUE(m_code->isFinished(ctx.get())); @@ -102,16 +102,16 @@ TEST_F(CppExecutableCodeTest, PredicateFunction) Thread thread(&m_target, &m_engine, m_script.get()); auto ctx = m_code->createExecutionContext(&thread); - EXPECT_CALL(*m_code, runPredicate(ctx.get(), &m_target, m_target.variableData(), m_target.listData())).WillOnce(Return(true)); + EXPECT_CALL(*m_code, runPredicate(ctx.get(), &m_target, m_target.variableData(), m_target.listData(), nullptr)).WillOnce(Return(true)); ASSERT_TRUE(std::static_pointer_cast(m_code)->runPredicate(ctx.get())); - EXPECT_CALL(*m_code, runPredicate(ctx.get(), &m_target, m_target.variableData(), m_target.listData())).WillOnce(Return(true)); + EXPECT_CALL(*m_code, runPredicate(ctx.get(), &m_target, m_target.variableData(), m_target.listData(), nullptr)).WillOnce(Return(true)); ASSERT_TRUE(std::static_pointer_cast(m_code)->runPredicate(ctx.get())); - EXPECT_CALL(*m_code, runPredicate(ctx.get(), &m_target, m_target.variableData(), m_target.listData())).WillOnce(Return(false)); + EXPECT_CALL(*m_code, runPredicate(ctx.get(), &m_target, m_target.variableData(), m_target.listData(), nullptr)).WillOnce(Return(false)); ASSERT_FALSE(std::static_pointer_cast(m_code)->runPredicate(ctx.get())); - EXPECT_CALL(*m_code, runPredicate(ctx.get(), &m_target, m_target.variableData(), m_target.listData())).WillOnce(Return(false)); + EXPECT_CALL(*m_code, runPredicate(ctx.get(), &m_target, m_target.variableData(), m_target.listData(), nullptr)).WillOnce(Return(false)); ASSERT_FALSE(std::static_pointer_cast(m_code)->runPredicate(ctx.get())); } @@ -124,7 +124,7 @@ TEST_F(CppExecutableCodeTest, ReporterFunction) auto ctx = m_code->createExecutionContext(&thread); Value v = "test"; - EXPECT_CALL(*m_code, runReporter(ctx.get(), &m_target, m_target.variableData(), m_target.listData())).WillOnce(Return(v.data())); + EXPECT_CALL(*m_code, runReporter(ctx.get(), &m_target, m_target.variableData(), m_target.listData(), nullptr)).WillOnce(Return(v.data())); ASSERT_EQ(Value(std::static_pointer_cast(m_code)->runReporter(ctx.get())).toString(), v.toString()); } diff --git a/test/codegen/cpp/cppexecutablecodemock.h b/test/codegen/cpp/cppexecutablecodemock.h index 1d2063f65..f3b655308 100644 --- a/test/codegen/cpp/cppexecutablecodemock.h +++ b/test/codegen/cpp/cppexecutablecodemock.h @@ -15,9 +15,9 @@ class CppExecutableCodeMock : public CppExecutableCode { } - MOCK_METHOD(void, runScript, (ExecutionContext * ctx, Target *, ValueData **, List **)); - MOCK_METHOD(ValueData, runReporter, (ExecutionContext * ctx, Target *, ValueData **, List **)); - MOCK_METHOD(bool, runPredicate, (ExecutionContext * ctx, Target *, ValueData **, List **)); + MOCK_METHOD(void, runScript, (ExecutionContext * ctx, Target *, ValueData **, List **, void **)); + MOCK_METHOD(ValueData, runReporter, (ExecutionContext * ctx, Target *, ValueData **, List **, void **)); + MOCK_METHOD(bool, runPredicate, (ExecutionContext * ctx, Target *, ValueData **, List **, void **)); }; } // namespace libscratchcpp diff --git a/test/mocks/codebuildermock.h b/test/mocks/codebuildermock.h index 9a41bd5e9..3c0afdb82 100644 --- a/test/mocks/codebuildermock.h +++ b/test/mocks/codebuildermock.h @@ -13,6 +13,11 @@ class CodeBuilderMock : public ICodeBuilder 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)); MOCK_METHOD(CompilerConstant *, addConstValue, (const Value &), (override)); + MOCK_METHOD(CompilerValue *, addTargetPointer, (const std::string &), (override)); + MOCK_METHOD(CompilerValue *, addVariablePointer, (Variable *), (override)); + MOCK_METHOD(CompilerValue *, addListPointer, (List *), (override)); + MOCK_METHOD(CompilerValue *, addTimerPointer, (), (override)); + MOCK_METHOD(CompilerValue *, addEffectPointer, (const std::string &), (override)); MOCK_METHOD(CompilerValue *, addStringChar, (CompilerValue *, CompilerValue *), (override)); MOCK_METHOD(CompilerValue *, addStringLength, (CompilerValue *), (override)); MOCK_METHOD(CompilerValue *, addLoopIndex, (), (override));