Chapter 19.3

This commit is contained in:
Tom Willemse 2021-09-07 22:34:21 -07:00
parent c1cbc359e9
commit 60e752c0c5
Signed by: ryuslash
GPG key ID: 7D5C407B435025C1
5 changed files with 19 additions and 8 deletions

View file

@ -15,6 +15,7 @@ add_executable(Lox
scanner.h scanner.h
scanner.c scanner.c
object.h object.h
object.c
main.c) main.c)
install(TARGETS Lox) install(TARGETS Lox)

View file

@ -190,6 +190,11 @@ static void number() {
emitConstant(NUMBER_VAL(value)); emitConstant(NUMBER_VAL(value));
} }
static void string() {
emitConstant(OBJ_VAL(
copyString(parser.previous.start + 1, parser.previous.length - 2)));
}
static void unary() { static void unary() {
TokenType operatorType = parser.previous.type; TokenType operatorType = parser.previous.type;
@ -235,7 +240,7 @@ ParseRule rules[] = {
[TOKEN_LESS] = {NULL, binary, PREC_COMPARISON}, [TOKEN_LESS] = {NULL, binary, PREC_COMPARISON},
[TOKEN_LESS_EQUAL] = {NULL, binary, PREC_COMPARISON}, [TOKEN_LESS_EQUAL] = {NULL, binary, PREC_COMPARISON},
[TOKEN_IDENTIFIER] = {NULL, NULL, PREC_NONE}, [TOKEN_IDENTIFIER] = {NULL, NULL, PREC_NONE},
[TOKEN_STRING] = {NULL, NULL, PREC_NONE}, [TOKEN_STRING] = {string, NULL, PREC_NONE},
[TOKEN_NUMBER] = {number, NULL, PREC_NONE}, [TOKEN_NUMBER] = {number, NULL, PREC_NONE},
[TOKEN_AND] = {NULL, NULL, PREC_NONE}, [TOKEN_AND] = {NULL, NULL, PREC_NONE},
[TOKEN_CLASS] = {NULL, NULL, PREC_NONE}, [TOKEN_CLASS] = {NULL, NULL, PREC_NONE},

View file

@ -1,6 +1,7 @@
#ifndef COMPILER_H #ifndef COMPILER_H
#define COMPILER_H #define COMPILER_H
#include "object.h"
#include "vm.h" #include "vm.h"
bool compile(const char *source, Chunk *chunk); bool compile(const char *source, Chunk *chunk);

View file

@ -3,16 +3,18 @@
#include "common.h" #include "common.h"
#define GROW_CAPACITY(capacity) \ #define ALLOCATE(type, count) \
((capacity) < 8 ? 8 : (capacity) * 2) (type *)reallocate(NULL, 0, sizeof(type) * (count))
#define GROW_ARRAY(type, pointer, oldCount, newCount) \ #define GROW_CAPACITY(capacity) ((capacity) < 8 ? 8 : (capacity)*2)
(type*)reallocate(pointer, sizeof(type) * (oldCount), \
sizeof(type) * (newCount))
#define FREE_ARRAY(type, pointer, oldCount) \ #define GROW_ARRAY(type, pointer, oldCount, newCount) \
(type *)reallocate(pointer, sizeof(type) * (oldCount), \
sizeof(type) * (newCount))
#define FREE_ARRAY(type, pointer, oldCount) \
reallocate(pointer, sizeof(type) * (oldCount), 0) reallocate(pointer, sizeof(type) * (oldCount), 0)
void* reallocate(void* pointer, size_t oldSize, size_t newSize); void *reallocate(void *pointer, size_t oldSize, size_t newSize);
#endif #endif

View file

@ -25,6 +25,8 @@ struct ObjString {
char *chars; char *chars;
}; };
ObjString *copyString(const char *chars, int length);
static inline bool isObjType(Value value, ObjType type) { static inline bool isObjType(Value value, ObjType type) {
return IS_OBJ(value) && AS_OBJ(value)->type == type; return IS_OBJ(value) && AS_OBJ(value)->type == type;
} }