2023-12-09 17:24:41 +00:00
|
|
|
#include "value.h"
|
|
|
|
|
2023-12-11 17:01:22 +00:00
|
|
|
void value_init(value_t* value, type_t* type, int line)
|
2023-12-09 17:24:41 +00:00
|
|
|
{
|
|
|
|
assert(value);
|
|
|
|
assert(type);
|
|
|
|
|
|
|
|
value->type = type;
|
2023-12-11 17:01:22 +00:00
|
|
|
value->line = line;
|
2023-12-09 17:24:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void value_free(value_t* value)
|
|
|
|
{
|
|
|
|
assert(value);
|
2023-12-10 03:49:28 +00:00
|
|
|
|
|
|
|
if (value->type->kind == TYPE_STR)
|
|
|
|
{
|
|
|
|
free(value->value.str);
|
|
|
|
}
|
2023-12-09 17:24:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
int value_eq(value_t* value, value_t* rhs)
|
|
|
|
{
|
|
|
|
if (!type_eq(value->type, rhs->type))
|
|
|
|
{
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
switch (value->type->kind)
|
|
|
|
{
|
|
|
|
case TYPE_NUM: {
|
|
|
|
return value->value.num == rhs->value.num;
|
|
|
|
} break;
|
|
|
|
|
2023-12-09 21:59:24 +00:00
|
|
|
case TYPE_BOOL: {
|
|
|
|
return value->value.bool == rhs->value.bool;
|
|
|
|
} break;
|
|
|
|
|
2023-12-10 03:49:28 +00:00
|
|
|
case TYPE_STR: {
|
|
|
|
return strcmp(value->value.str, rhs->value.str) == 0;
|
|
|
|
} break;
|
|
|
|
|
2023-12-09 17:24:41 +00:00
|
|
|
default: {
|
|
|
|
fprintf(stderr, "Cannot compare value of type '%s'.\n",
|
|
|
|
TypeKindStr[value->type->kind]);
|
|
|
|
abort();
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t value_str(value_t* value, char* buffer, size_t size)
|
|
|
|
{
|
|
|
|
assert(value);
|
|
|
|
assert(buffer);
|
|
|
|
|
|
|
|
switch (value->type->kind)
|
|
|
|
{
|
|
|
|
case TYPE_NUM:
|
|
|
|
return snprintf(buffer, size, "%lf", value->value.num);
|
|
|
|
break;
|
|
|
|
|
2023-12-09 21:59:24 +00:00
|
|
|
case TYPE_BOOL:
|
|
|
|
return snprintf(buffer, size, "%s", value->value.bool ? "true" : "false");
|
|
|
|
break;
|
|
|
|
|
2023-12-10 03:49:28 +00:00
|
|
|
case TYPE_STR:
|
|
|
|
return snprintf(buffer, size, "\"%s\"", value->value.str);
|
|
|
|
break;
|
|
|
|
|
2023-12-09 21:59:24 +00:00
|
|
|
default: {
|
|
|
|
fprintf(stderr, "Cannot stringify unknown value of type '%s'.\n",
|
|
|
|
TypeKindStr[value->type->kind]);
|
|
|
|
abort();
|
|
|
|
};
|
2023-12-09 17:24:41 +00:00
|
|
|
}
|
|
|
|
}
|