add abs() builtin

This commit is contained in:
pikastech 2023-04-22 18:46:22 +08:00
parent 366c696643
commit 3d7a087598
6 changed files with 70 additions and 0 deletions

View File

@ -122,6 +122,10 @@ class SysObj:
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def input(*info) -> str: ...
@staticmethod
@PIKA_C_MACRO_IF("PIKA_GC_MARK_SWEEP_ENABLE")
def abs(val: any) -> any: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def help(name: str): ...

View File

@ -686,3 +686,24 @@ void PikaStdLib_SysObj_clear(PikaObj* self) {
void PikaStdLib_SysObj_gcdump(PikaObj* self) {
pikaGC_markDump();
}
Arg* PikaStdLib_SysObj_abs(PikaObj* self, Arg* val) {
ArgType type = arg_getType(val);
if (type == ARG_TYPE_INT) {
int64_t v = arg_getInt(val);
if (v < 0) {
v = -v;
}
return arg_newInt(v);
}
if (type == ARG_TYPE_FLOAT) {
pika_float v = arg_getFloat(val);
if (v < 0) {
v = -v;
}
return arg_newFloat(v);
}
obj_setSysOut(self, "TypeError: bad operand type for abs()");
obj_setErrorCode(self, PIKA_RES_ERR_INVALID_PARAM);
return NULL;
}

View File

@ -122,6 +122,10 @@ class SysObj:
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def input(*info) -> str: ...
@staticmethod
@PIKA_C_MACRO_IF("PIKA_GC_MARK_SWEEP_ENABLE")
def abs(val: any) -> any: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def help(name: str): ...

View File

@ -686,3 +686,24 @@ void PikaStdLib_SysObj_clear(PikaObj* self) {
void PikaStdLib_SysObj_gcdump(PikaObj* self) {
pikaGC_markDump();
}
Arg* PikaStdLib_SysObj_abs(PikaObj* self, Arg* val) {
ArgType type = arg_getType(val);
if (type == ARG_TYPE_INT) {
int64_t v = arg_getInt(val);
if (v < 0) {
v = -v;
}
return arg_newInt(v);
}
if (type == ARG_TYPE_FLOAT) {
pika_float v = arg_getFloat(val);
if (v < 0) {
v = -v;
}
return arg_newFloat(v);
}
obj_setSysOut(self, "TypeError: bad operand type for abs()");
obj_setErrorCode(self, PIKA_RES_ERR_INVALID_PARAM);
return NULL;
}

View File

@ -2828,6 +2828,16 @@ TEST_RUN_LINES_PASS(vm,
#endif
TEST_RUN_LINES(vm, minus_none, "10 - None")
TEST_RUN_LINES_PASS(vm,
abs,
"assert abs(-1) == 1\n"
"assert abs(1) == 1\n"
"assert abs(-1.0) == 1.0\n"
"assert abs(0.1) == 0.1\n"
"print('PASS')\n")
TEST_RUN_LINES(vm, abs_none, "abs(None)")
TEST_RUN_LINES(vm, abs_str, "abs('test')")
#endif

View File

@ -65,6 +65,16 @@ extern char log_buff[LOG_BUFF_MAX][LOG_SIZE];
EXPECT_EQ(pikaMemNow(), 0); \
}
#define TEST_RUN_LINES_NO_OUTPUT(_test_suite_, _test_name_, _lines_) \
TEST(_test_suite_, _test_name_) { \
PikaObj *self = newRootObj("root", New_PikaStdLib_SysObj); \
pika_platform_printf("BEGIN\r\n"); \
obj_run(self, (_lines_)); /* collect */ /* assert */ \
EXPECT_STREQ(log_buff[0], "BEGIN\r\n"); \
obj_deinit(self); \
EXPECT_EQ(pikaMemNow(), 0); \
}
#define TEST_RUN_LINES_PASS(_test_suite_, _test_name_, _lines_) \
TEST(_test_suite_, _test_name_) { \
PikaObj *self = newRootObj("root", New_PikaStdLib_SysObj); \