diff --git a/src/engine/internal/codegen/cpp/CMakeLists.txt b/src/engine/internal/codegen/cpp/CMakeLists.txt index bf3e3434..28f7593c 100644 --- a/src/engine/internal/codegen/cpp/CMakeLists.txt +++ b/src/engine/internal/codegen/cpp/CMakeLists.txt @@ -12,4 +12,16 @@ target_sources(scratchcpp cppconstant.h cppcodebuilder.cpp cppcodebuilder.h + cppcodegenerator.cpp + cppcodegenerator.h + cppcodestream.h + cpptypeinfo.h + cppidentifier.h + cppconstidentifier.h + cppnamedidentifier.h + cppassignment.h + cppfunctioncall.h + cppswitch.h ) + +add_subdirectory(instructions) diff --git a/src/engine/internal/codegen/cpp/cppassignment.h b/src/engine/internal/codegen/cpp/cppassignment.h new file mode 100644 index 00000000..636bb2f6 --- /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/cppcodebuilder.cpp b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp index 482e0e2a..00008ba0 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.cpp +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.cpp @@ -3,7 +3,9 @@ #include #include "cppcodebuilder.h" +#include "cppcompilercontext.h" #include "cppexecutablecode.h" +#include "cppinstruction.h" #include "cppconstant.h" #include "../typeutils.h" @@ -12,28 +14,83 @@ 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_instructionBuilder(m_codeGen), + 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(); + + while (ins) + ins = m_instructionBuilder.process(ins); + + std::cout << m_codeGen.finalize(); + return std::make_shared(m_ctx); } 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) @@ -45,212 +102,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) @@ -264,86 +350,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) @@ -352,3 +501,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 ef08d824..3f2bdb5e 100644 --- a/src/engine/internal/codegen/cpp/cppcodebuilder.h +++ b/src/engine/internal/codegen/cpp/cppcodebuilder.h @@ -2,14 +2,20 @@ #pragma once +#include + #include "../icodebuilder.h" +#include "cppinstruction.h" +#include "cppinstructionlist.h" +#include "cppcodegenerator.h" +#include "instructions/instructionbuilder.h" +#include "../codeanalyzer.h" namespace libscratchcpp { class CppCompilerContext; class CppValue; -class CppInstruction; class CppCodeBuilder : public ICodeBuilder { @@ -108,12 +114,25 @@ 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; 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; + bool m_loopCondition = false; // whether we're currently compiling a loop condition }; } // namespace libscratchcpp diff --git a/src/engine/internal/codegen/cpp/cppcodegenerator.cpp b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp new file mode 100644 index 00000000..e442a967 --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.cpp @@ -0,0 +1,600 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include +#include + +#include "cppcodegenerator.h" +#include "cppassignment.h" +#include "cppfunctioncall.h" +#include "cppswitch.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 }, + { Compiler::StaticType::Unknown, CppIdentifier::Type::ValueData } +}; + +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::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) +{ + if (value->isConst()) { + if (!TypeUtils::isSingleType(targetType)) + return createValue(value); + else + return castConstValue(value->constValue(), targetType); + } + + if (value->isRawValue) + return castRawValue(value, targetType); + + 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) +{ + 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(); + + if (retValue) + m_identifiers[retValue] = m_strings.back(); + } + + m_codeStream.beginLine(); + + std::unique_ptr strAssignment; + + if (retType != CppIdentifier::Type::StringPtr) { + strAssignment = std::make_unique(m_codeStream, getNamedIdentifier(retValue, retType, "ret", true)); + } + + createCall(name, strRet, ctxArg, targetArg, args); + + if (strAssignment) + strAssignment->close(); + + 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, bool isReference) +{ + auto it = m_identifiers.find(value); + + if (it == m_identifiers.cend()) { + auto identifier = std::make_shared(type, getNewIdentifierName(name), isMutable, isReference); + 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(); + + CppAssignment assignment(m_codeStream, identifier.get()); + addArrayElement(&m_stringArray, m_strings.size() - 1); + assignment.close(); + 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) +{ + 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) +{ + assert(value->isRawValue); + + 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) +{ + if (value->isConst()) { + const CppNamedIdentifier *identifier = getNamedIdentifier(value, CppIdentifier::Type::ValueData, "value", true, true); + + includeHeader(Header::Value); + + // Value constant = Value(...); + const CppNamedIdentifier *valueObj = createNamedIdentifier(CppIdentifier::Type::Value, "constant", true); + m_codeStream.beginLine(); + + 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(); + + CppAssignment valueAssignment(m_codeStream, identifier); + CppFunctionCall dataCall(m_codeStream, valueObj, "data"); + dataCall.close(); + + valueAssignment.close(); + m_codeStream.endLine(); + return identifier; + } else if (value->isRawValue) { + const CppNamedIdentifier *identifier = getNamedIdentifier(value, CppIdentifier::Type::ValueData, "value", false); + + includeHeader(Header::ValueData); + + // 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"); + } + + switch (value->type()) { + case Compiler::StaticType::Number: { + // value.numberValue = rawValue; + CppAssignment valueAssignment(m_codeStream, identifier, "numberValue"); + break; + } + + case Compiler::StaticType::Bool: { + // value.boolValue = rawValue; + CppAssignment valueAssignment(m_codeStream, identifier, "boolValue"); + break; + } + + case Compiler::StaticType::String: { + // value.stringValue = rawValue; + CppAssignment valueAssignment(m_codeStream, identifier, "stringValue"); + break; + } + + case Compiler::StaticType::Pointer: { + // value.pointerValue = rawValue; + 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(); + return identifier; + } else { + return getNamedIdentifier(value, CppIdentifier::Type::ValueData, "value", false); + } +} + +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 00000000..4fc016b7 --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppcodegenerator.h @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include +#include +#include + +#include "cppnamedidentifier.h" +#include "cppconstidentifier.h" +#include "cppcodestream.h" + +namespace libscratchcpp +{ + +class CppValue; + +class LIBSCRATCHCPP_TEST_EXPORT 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); + + 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); + + 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, 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); + + 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 00000000..e8139537 --- /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 00000000..44957514 --- /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 00000000..6d4bf93f --- /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 00000000..b373ca9a --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppidentifier.h @@ -0,0 +1,67 @@ +// 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, + ValueType, + 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::ValueType, { "ValueType", false, 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 00000000..a0ac1b4e --- /dev/null +++ b/src/engine/internal/codegen/cpp/cppnamedidentifier.h @@ -0,0 +1,31 @@ +// 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, bool isReference = false) : + CppIdentifier(type), + name(name), + isMutable(isMutable), + isReference(isReference) + { + } + + virtual bool isNamed() const override final { return true; } + + std::string name; + bool isMutable = true; + bool isReference = false; +}; + +} // 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 00000000..d0411e0a --- /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 00000000..fc720a91 --- /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 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 00000000..bdf67e3a --- /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 00000000..23b9130a --- /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 00000000..1a7b496e --- /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 00000000..78f56135 --- /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 00000000..8f92c8f8 --- /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 00000000..aebb9814 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/functions.cpp @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "functions.h" +#include "../cppinstruction.h" +#include "../cppcodegenerator.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) +{ + // 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(); +} 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 00000000..850ca00a --- /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 00000000..65c6df83 --- /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(CppCodeGenerator &codeGen) +{ + // Create groups + 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) +{ + // 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 00000000..bf817b8f --- /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(CppCodeGenerator &codeGen); + + 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 00000000..7b0e58e4 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/instructiongroup.cpp @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "instructiongroup.h" + +using namespace libscratchcpp::cppins; + +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 new file mode 100644 index 00000000..57df5957 --- /dev/null +++ b/src/engine/internal/codegen/cpp/instructions/instructiongroup.h @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "processresult.h" + +namespace libscratchcpp +{ + +class CppCodeGenerator; + +namespace cppins +{ + +class InstructionGroup +{ + public: + InstructionGroup(CppCodeGenerator &codeGen); + + virtual ProcessResult process(CppInstruction *ins) = 0; + + protected: + CppCodeGenerator &m_codeGen; +}; + +} // namespace cppins + +} // namespace libscratchcpp 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 00000000..739c38af --- /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 00000000..eec1c9c5 --- /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 00000000..bcd3c600 --- /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 00000000..f51bccae --- /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 00000000..0b4ea7bb --- /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 00000000..d5685b54 --- /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 00000000..7c9e43e5 --- /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 00000000..fa43dcbf --- /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 00000000..b058ad3d --- /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 00000000..4d53a824 --- /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 00000000..dd491be5 --- /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 00000000..d9580476 --- /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 00000000..4572ffbe --- /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 diff --git a/test/codegen/cpp/CMakeLists.txt b/test/codegen/cpp/CMakeLists.txt index 04f3e189..7efc9ffd 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 00000000..2606b4dc --- /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); +}