fakir/libstd/fun.cpp

151 lines
3.1 KiB
C++
Raw Normal View History

2023-09-20 15:17:13 +00:00
#include "fun.hpp"
namespace fkstd
{
2023-09-21 20:26:13 +00:00
STDRET assert_eq(Loc loc, STDARGS args)
2023-09-20 19:21:51 +00:00
{
auto oracle = args[0];
auto expr = args[1];
if (!oracle->equals(*expr))
{
std::stringstream ss;
ss << "assertion failed: expected '"
<< oracle->string()
<< "', got '"
<< expr->string()
<< "'";
2023-09-21 20:26:13 +00:00
loc.error<assert_error>(LOG_ERROR, ss.str());
2023-09-20 19:21:51 +00:00
}
2023-09-21 20:26:13 +00:00
return std::make_shared<Constant>(TYPE_BOOL, true, loc);
2023-09-20 19:21:51 +00:00
}
2023-09-21 20:26:13 +00:00
STDRET println(Loc loc, STDARGS args)
2023-09-20 15:17:13 +00:00
{
std::string sep;
for (auto arg: args)
{
std::cout << sep << arg->string();
sep = " ";
}
if (args.size() > 0)
{
loc = args.front()->loc();
}
std::cout << std::endl;
return std::make_shared<Constant>(TYPE_INT, 0, loc);
}
2023-09-21 20:26:13 +00:00
STDRET add_int(Loc loc, STDARGS args)
{
int result = 0;
for (auto arg: args)
{
result += std::get<int>(arg->value());
}
return std::make_shared<Constant>(TYPE_INT, result, loc);
}
STDRET sub_int(Loc loc, STDARGS args)
{
if (args.empty())
{
return std::make_shared<Constant>(TYPE_INT, 0, loc);
}
if (args.size() == 1)
{
return std::make_shared<Constant>(TYPE_INT,
-std::get<int>(args[0]->value()),
loc);
}
int result = std::get<int>(args[0]->value());
for (size_t i=1; i<args.size(); i++)
{
result -= std::get<int>(args[i]->value());
}
return std::make_shared<Constant>(TYPE_INT, result, loc);
}
STDRET mul_int(Loc loc, STDARGS args)
{
int result = 1;
for (auto arg: args)
{
result *= std::get<int>(arg->value());
}
return std::make_shared<Constant>(TYPE_INT, result, loc);
}
STDRET div_int(Loc loc, STDARGS args)
{
if (args.empty())
{
return std::make_shared<Constant>(TYPE_INT, 1, loc);
}
if (args.size() == 1)
{
return std::make_shared<Constant>(TYPE_INT,
1/std::get<int>(args[0]->value()),
loc);
}
int result = std::get<int>(args[0]->value());
for (size_t i=1; i<args.size(); i++)
{
result /= std::get<int>(args[i]->value());
}
return std::make_shared<Constant>(TYPE_INT, result, loc);
}
STDRET mod_int(Loc loc, STDARGS args)
{
if (args.empty())
{
return std::make_shared<Constant>(TYPE_INT, 1, loc);
}
int result = std::get<int>(args[0]->value());
for (size_t i=1; i<args.size(); i++)
{
result %= std::get<int>(args[i]->value());
}
return std::make_shared<Constant>(TYPE_INT, result, loc);
}
STDRET pow_int(Loc loc, STDARGS args)
{
if (args.empty())
{
return std::make_shared<Constant>(TYPE_INT, 1, loc);
}
int result = std::get<int>(args[0]->value());
for (size_t i=1; i<args.size(); i++)
{
result = std::pow(result, std::get<int>(args[i]->value()));
}
return std::make_shared<Constant>(TYPE_INT, result, loc);
}
2023-09-20 15:17:13 +00:00
}