From ba52787271b246255b8788942cdb74560f840bfe Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Mon, 6 Sep 2021 02:24:56 -0700 Subject: Chapter 19.1 - 19.2 --- clox/src/CMakeLists.txt | 1 + clox/src/object.h | 32 ++++++++++++++++++++++++++++++++ clox/src/value.h | 8 ++++++++ 3 files changed, 41 insertions(+) create mode 100644 clox/src/object.h (limited to 'clox/src') diff --git a/clox/src/CMakeLists.txt b/clox/src/CMakeLists.txt index af21222..e46b989 100644 --- a/clox/src/CMakeLists.txt +++ b/clox/src/CMakeLists.txt @@ -14,6 +14,7 @@ add_executable(Lox compiler.c scanner.h scanner.c + object.h main.c) install(TARGETS Lox) diff --git a/clox/src/object.h b/clox/src/object.h new file mode 100644 index 0000000..7ab8f3a --- /dev/null +++ b/clox/src/object.h @@ -0,0 +1,32 @@ +#ifndef OBJECT_H +#define OBJECT_H + +#include "common.h" +#include "value.h" + +#define OBJ_TYPE(value) (AS_OBJ(value)->type) + +#define IS_STRING(value) isObjType(value, OBJ_STRING) + +#define AS_STRING(value) ((ObjString *)AS_OBJ(value)) +#define AS_CSTRING(value) (((ObjString *)AS_OBJ(value))->chars) + +typedef enum { + OBJ_STRING, +} ObjType; + +struct Obj { + ObjType type; +}; + +struct ObjString { + Obj obj; + int length; + char *chars; +}; + +static inline bool isObjType(Value value, ObjType type) { + return IS_OBJ(value) && AS_OBJ(value)->type == type; +} + +#endif diff --git a/clox/src/value.h b/clox/src/value.h index 96df347..6896bea 100644 --- a/clox/src/value.h +++ b/clox/src/value.h @@ -3,10 +3,14 @@ #include "common.h" +typedef struct Obj Obj; +typedef struct ObjString ObjString; + typedef enum { VAL_BOOL, VAL_NIL, VAL_NUMBER, + VAL_OBJ, } ValueType; typedef struct { @@ -14,19 +18,23 @@ typedef struct { union { bool boolean; double number; + Obj *obj; } as; } Value; #define IS_BOOL(value) ((value).type == VAL_BOOL) #define IS_NIL(value) ((value).type == VAL_NIL) #define IS_NUMBER(value) ((value).type == VAL_NUMBER) +#define IS_OBJ(value) ((value).type == VAL_OBJ) +#define AS_OBJ(value) ((value).as.obj) #define AS_BOOL(value) ((value).as.boolean) #define AS_NUMBER(value) ((value).as.number) #define BOOL_VAL(value) ((Value){VAL_BOOL, {.boolean = value}}) #define NIL_VAL ((Value){VAL_NIL, {.number = 0}}) #define NUMBER_VAL(value) ((Value){VAL_NUMBER, {.number = value}}) +#define OBJ_VAL(value) ((Value){VAL_OBJ, {.obj = (Obj *)object}}) typedef struct { int capacity; -- cgit v1.2.3-54-g00ecf