Files
ground-rewrite/src/Stringify/BytecodeValue.c

83 lines
2.9 KiB
C

#include "../../include/ground.h"
#include "../include/estr.h"
#include <inttypes.h>
char* _GroundStringifyBytecodeValue(GroundBytecodeValue* value) {
switch (value->type.type) {
case GroundType_Int: {
char* buf = malloc(snprintf(NULL, 0, "%" PRId64, value->as.Int) + 1);
if (buf == NULL) {
Ground.Flags.error = true;
Ground.Log.Error("malloc failed in Ground.Stringify.Value");
return NULL;
}
sprintf(buf, "%" PRId64, value->as.Int);
return buf;
}
case GroundType_Double: {
char* buf = malloc(snprintf(NULL, 0, "%f", value->as.Double) + 1);
if (buf == NULL) {
Ground.Flags.error = true;
Ground.Log.Error("malloc failed in Ground.Stringify.Value");
return NULL;
}
sprintf(buf, "%f", value->as.Double);
return buf;
}
case GroundType_Char: {
char* buf = malloc(snprintf(NULL, 0, "%c", value->as.Char) + 1);
if (buf == NULL) {
Ground.Flags.error = true;
Ground.Log.Error("malloc failed in Ground.Stringify.Value");
return NULL;
}
sprintf(buf, "%c", value->as.Char);
return buf;
}
case GroundType_Bool: {
char* buf = malloc(6); // max(len(true), len(false)) + 1
if (buf == NULL) {
Ground.Flags.error = true;
Ground.Log.Error("malloc failed in Ground.Stringify.Value");
return NULL;
}
sprintf(buf, value->as.Bool ? "true" : "false");
return buf;
}
case GroundType_String: {
return Ground.Stringify.String(&value->as.String);
}
case GroundType_List: {
// TODO implement list stringification
}
case GroundType_Function: {
// TODO implement function stringification
}
case GroundType_Struct: {
Estr str = CREATE_ESTR("<struct fields: { ");
for (GroundSize i = 0; i < value->as.Struct.size; i++) {
char* field = Ground.Stringify.BytecodeValue(&value->as.Struct.values[i]);
APPEND_ESTR(str, field);
free(field);
}
APPEND_ESTR(str, " }>");
return str.str;
}
case GroundType_Object: {
Estr str = CREATE_ESTR("<object fields: { ");
for (GroundSize i = 0; i < value->as.Struct.size; i++) {
char* field = Ground.Stringify.BytecodeValue(&value->as.Struct.values[i]);
APPEND_ESTR(str, field);
free(field);
}
APPEND_ESTR(str, " }>");
return str.str;
}
}
Ground.Flags.error = true;
Ground.Log.Error("FIXME implement all cases in Ground.Stringify.Value");
return NULL;
}