feat: Implement compiler and virtual machine for Fig language

- Added Compiler class with methods for compiling programs, statements, and expressions.
- Introduced Proto structure to hold compiled bytecode and constants.
- Implemented expression compilation including literals, identifiers, and infix expressions.
- Developed statement compilation for variable declarations and expression statements.
- Created a VM class to execute compiled bytecode with support for arithmetic and comparison operations.
- Added Object and Value classes for handling different data types and memory management.
- Implemented String and Struct objects for enhanced data representation.
- Established a parser for parsing variable declarations and statements.
- Included tests for the VM and object representations.
This commit is contained in:
2026-02-20 14:05:56 +08:00
parent f2e899c7a7
commit 2631f76da1
31 changed files with 1722 additions and 94 deletions

View File

@@ -2,28 +2,60 @@
@file src/Bytecode/Bytecode.hpp
@brief 字节码Bytecode定义
@author PuqiAR (im@puqiar.top)
@date 2026-02-17
@date 2026-02-18
*/
#pragma once
#include <cstdint>
#pragma once
#include <cstdint>
namespace Fig
{
using OpCodeType = uint8_t;
enum class OpCode : OpCodeType
// 定长 32-bit
using Instruction = std::uint32_t;
enum class OpCode : std::uint8_t
{
LoadConst, // dst, const id
LoadLocal, // dst, slot id
StoreLocal, // slot, src(reg)
Exit, // 结束运行
LoadK, // iABx 模式: R[A] = Constants[Bx]
Return, // iA 模式: 返回 R[A] 的值
LoadLocalRef, // dst, slot
LoadRef, // dst, refReg
StoreRef, // refReg, srcReg
Mov, // iABx: R[A] = R[Bx]
Add, // iABC: R[A] = R[B] + R[C]
Sub, // iABC: R[A] = R[B] - R[C]
Mul, // iABC: R[A] = R[B] * R[C]
Div, // iABC: R[A] = R[B] / R[C]
Mod, // iABC: R[A] = R[B] % R[C]
BitXor, // iABC: R[A] = R[B] ^ R[C]
Add, // dst, a, b
Move, // dst, src
Equal, // iABC: R[A] = R[B] == R[C]
NotEqual, // iABC: R[A] = R[B] != R[C]
Greater, // iABC: R[A] = R[B] > R[C]
Less, // iABC: R[A] = R[B] < R[C]
GreaterEqual, // iABC: R[A] = R[B] >= R[C]
LessEqual, // iABC: R[A] = R[B] <= R[C]
Count, // 哨兵
};
}; // namespace Fig
namespace Op
{
// [OpCode: 8] [A: 8] [Bx: 16]
[[nodiscard]] inline constexpr Instruction iABx(OpCode op, std::uint8_t a, std::uint16_t bx)
{
return static_cast<std::uint32_t>(op) | (static_cast<std::uint32_t>(a) << 8)
| (static_cast<std::uint32_t>(bx) << 16);
}
// [OpCode: 8] [A: 8] [B: 8] [C: 8]
[[nodiscard]] inline constexpr Instruction iABC(OpCode op, std::uint8_t a, std::uint8_t b, std::uint8_t c)
{
return static_cast<std::uint32_t>(op) | (static_cast<std::uint32_t>(a) << 8)
| (static_cast<std::uint32_t>(b) << 16) | (static_cast<std::uint32_t>(c) << 24);
}
} // namespace Op
} // namespace Fig