Chapter 26.7
This commit is contained in:
parent
38e4c37f0f
commit
ad6a98f6ad
3 changed files with 18 additions and 8 deletions
|
@ -1,9 +1,10 @@
|
|||
#include <stdlib.h>
|
||||
|
||||
#include "chunk.h"
|
||||
#include "memory.h"
|
||||
#include "memory.h"
|
||||
#include "vm.h"
|
||||
|
||||
void initChunk(Chunk* chunk) {
|
||||
void initChunk(Chunk *chunk) {
|
||||
chunk->count = 0;
|
||||
chunk->capacity = 0;
|
||||
chunk->code = NULL;
|
||||
|
@ -11,18 +12,19 @@ void initChunk(Chunk* chunk) {
|
|||
initValueArray(&chunk->constants);
|
||||
}
|
||||
|
||||
void freeChunk(Chunk* chunk) {
|
||||
void freeChunk(Chunk *chunk) {
|
||||
FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);
|
||||
FREE_ARRAY(int, chunk->lines, chunk->capacity);
|
||||
freeValueArray(&chunk->constants);
|
||||
initChunk(chunk);
|
||||
}
|
||||
|
||||
void writeChunk(Chunk* chunk, uint8_t byte, int line) {
|
||||
void writeChunk(Chunk *chunk, uint8_t byte, int line) {
|
||||
if (chunk->capacity < chunk->count + 1) {
|
||||
int oldCapacity = chunk->capacity;
|
||||
chunk->capacity = GROW_CAPACITY(oldCapacity);
|
||||
chunk->code = GROW_ARRAY(uint8_t, chunk->code, oldCapacity, chunk->capacity);
|
||||
chunk->code =
|
||||
GROW_ARRAY(uint8_t, chunk->code, oldCapacity, chunk->capacity);
|
||||
chunk->lines = GROW_ARRAY(int, chunk->lines, oldCapacity, chunk->capacity);
|
||||
}
|
||||
|
||||
|
@ -31,7 +33,9 @@ void writeChunk(Chunk* chunk, uint8_t byte, int line) {
|
|||
chunk->count++;
|
||||
}
|
||||
|
||||
int addConstant(Chunk* chunk, Value value) {
|
||||
int addConstant(Chunk *chunk, Value value) {
|
||||
push(value);
|
||||
writeValueArray(&chunk->constants, value);
|
||||
pop();
|
||||
return chunk->constants.count - 1;
|
||||
}
|
||||
|
|
|
@ -58,7 +58,11 @@ static ObjString *allocateString(char *chars, int length, uint32_t hash) {
|
|||
string->length = length;
|
||||
string->chars = chars;
|
||||
string->hash = hash;
|
||||
|
||||
push(OBJ_VAL(string));
|
||||
tableSet(&vm.strings, string, NIL_VAL);
|
||||
pop();
|
||||
|
||||
return string;
|
||||
}
|
||||
|
||||
|
|
|
@ -163,8 +163,8 @@ static bool isFalsey(Value value) {
|
|||
}
|
||||
|
||||
static void concatenate() {
|
||||
ObjString *b = AS_STRING(pop());
|
||||
ObjString *a = AS_STRING(pop());
|
||||
ObjString *b = AS_STRING(peek(0));
|
||||
ObjString *a = AS_STRING(peek(1));
|
||||
|
||||
int length = a->length + b->length;
|
||||
char *chars = ALLOCATE(char, length + 1);
|
||||
|
@ -173,6 +173,8 @@ static void concatenate() {
|
|||
chars[length] = '\0';
|
||||
|
||||
ObjString *result = takeString(chars, length);
|
||||
pop();
|
||||
pop();
|
||||
push(OBJ_VAL(result));
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue