1
0
Fork 0
lesson-lisp/object.c

81 lines
1.7 KiB
C

#include "enums.h"
#include "object.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static struct Object *new(const enum Type type)
{
struct Object *const object = malloc(sizeof(struct Object));
assert(object);
memset(object, 0, sizeof(struct Object));
object->type = type;
return object;
}
struct Object *Object_new_pair(struct Object *const a, struct Object *const b)
{
struct Object *const object = new(TYPE_PAIR);
object->pair.a = a;
object->pair.b = b;
return object;
}
struct Object *Object_new_atom(const char *const s)
{
struct Object *const object = new(TYPE_ATOM);
object->s = malloc(strlen(s) + 1);
assert(object->s);
strcpy(object->s, s);
return object;
}
struct Object *Object_new_string(const char *const s)
{
struct Object *const object = new(TYPE_STRING);
object->s = malloc(strlen(s) + 1);
assert(object->s);
strcpy(object->s, s);
return object;
}
struct Object *Object_new_number(const int64_t i)
{
struct Object *const object = new(TYPE_NUMBER);
object->i = i;
return object;
}
void Object_print(struct Object *const self, const unsigned indent)
{
for (unsigned index = 0; index < indent; ++index) {
printf(" ");
}
if (!self) {
printf("NULL\n");
return;
}
printf("%s:", Type_to_str(self->type));
switch (self->type) {
case TYPE_PAIR:
printf("\n");
Object_print(self->pair.a, indent + 1);
Object_print(self->pair.b, indent + 1);
break;
case TYPE_ATOM:
case TYPE_STRING:
printf("%s\n", self->s);
break;
case TYPE_NUMBER:
printf("%li\n", self->i);
break;
default:
break;
}
}