[Feat] 支持运算符重载!详见文档或 Library/lang/lang.fig中的定义。通过 impl Operation for xxx实现重载

[Impl] 函数参数指定现在也接受一个 exp,逐渐改动其他中...
This commit is contained in:
2026-02-02 16:11:08 +08:00
parent 41bff72d44
commit 01c16dee3f
20 changed files with 698 additions and 355 deletions

View File

@@ -1,3 +1,4 @@
#include "Evaluator/Value/value.hpp"
#include <Evaluator/Value/LvObject.hpp>
#include <Evaluator/evaluator.hpp>
#include <Evaluator/evaluator_error.hpp>
@@ -10,16 +11,31 @@ namespace Fig
Operator op = un->op;
Ast::Expression exp = un->exp;
ObjectPtr value = eval(exp, ctx);
const auto &tryInvokeOverloadFn = [ctx, op](const ObjectPtr &rhs, const std::function<ObjectPtr()> &rollback) {
if (rhs->is<StructInstance>())
{
// 运算符重载
const TypeInfo &type = actualType(rhs);
if (ctx->hasOperatorImplemented(type, op))
{
const auto &fnOpt = ctx->getUnaryOperatorFn(type, op);
return (*fnOpt)(rhs);
}
}
return rollback();
};
switch (op)
{
case Operator::Not: {
return std::make_shared<Object>(!(*value));
return tryInvokeOverloadFn(value, [value]() { return std::make_shared<Object>(!(*value)); });
}
case Operator::Subtract: {
return std::make_shared<Object>(-(*value));
return tryInvokeOverloadFn(value, [value]() { return std::make_shared<Object>(-(*value)); });
}
case Operator::BitNot: {
return std::make_shared<Object>(bit_not((*value)));
return tryInvokeOverloadFn(value, [value]() { return std::make_shared<Object>(bit_not(*value)); });
}
default: {
throw EvaluatorError(u8"UnsupportedOpError",
@@ -28,4 +44,4 @@ namespace Fig
}
}
}
};
}; // namespace Fig