Skip to content

Commit

Permalink
function object
Browse files Browse the repository at this point in the history
  • Loading branch information
hsl4125 committed Jan 15, 2022
1 parent b8aa20b commit 4fc7f02
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
6 changes: 6 additions & 0 deletions compiler/memory.c
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ static void freeObject(Obj *object) {
FREE(ObjString, object);
break;
}
case OBJ_FUNCTION: {
ObjFunction *function = (ObjFunction *) object;
freeChunk(&function->chunk);
FREE(ObjFunction, object);
break;
}
}
}

Expand Down
15 changes: 15 additions & 0 deletions compiler/object.c
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,25 @@ ObjString *copyString(const char *chars, int length) {
return allocateString(heapChars, length, hash);
}

ObjFunction *newFunction() {
ObjFunction *function = ALLOCATE_OBJ(ObjFunction, OBJ_FUNCTION);
function->arity = 0;
function->name = NULL;
initChunk(&function->chunk);
return function;
}

static void printFunction(ObjFunction *function) {
printf("<fn %s>", function->name->chars);
}

void printObject(Value value) {
switch (OBJ_TYPE(value)) {
case OBJ_STRING:
printf("%s", AS_CSTRING(value));
break;
case OBJ_FUNCTION:
printFunction(AS_FUNCTION(value));
break;
}
}
19 changes: 16 additions & 3 deletions include/object.h
Original file line number Diff line number Diff line change
@@ -1,22 +1,34 @@
#pragma once

#include "chunk.h"
#include "common.h"
#include "value.h"

#define OBJ_TYPE(value) (AS_OBJ(value)->type)
#define IS_STRING(value) isObjType(value, OBJ_STRING)
#define IS_FUNCTION(value) isObjType(value, OBJ_FUNCTION)

#define AS_STRING(value) ((ObjString *) AS_OBJ(value))
#define AS_CSTRING(value) (((ObjString *) AS_OBJ(value))->chars)
#define AS_FUNCTION(value) ((ObjFunction *) AS_OBJ(value))

typedef enum {
OBJ_STRING,
OBJ_FUNCTION,
} ObjType;

struct Obj {
ObjType type;
struct Obj *next;
};

typedef struct {
Obj obj;
int arity;
Chunk chunk;
ObjString *name;
} ObjFunction;

struct ObjString {
Obj obj;
int length;
Expand All @@ -28,6 +40,7 @@ static inline bool isObjType(Value value, ObjType type) {
return IS_OBJ(value) && AS_OBJ(value)->type == type;
}

ObjString *takeString(char *chars, int length);
ObjString *copyString(const char *chars, int length);
void printObject(Value value);
ObjString *takeString(char *chars, int length);
ObjString *copyString(const char *chars, int length);
ObjFunction *newFunction();
void printObject(Value value);

0 comments on commit 4fc7f02

Please sign in to comment.