Strings:clox 的字符串对象与内存管理
Crafting Interpreters:Strings
本章把 string 从简单的 C 字符数组提升为 clox 的 heap object,并实现 concatenation、比较、打印和对象释放。
TL;DR
- Lox 的 string 是动态对象,不能只把 char pointer 当作 Value 保存。
- Obj header 让不同 heap object 共享 type、链表和 GC 所需的基础布局。
- ObjString 保存长度、字符数组和哈希值;长度显式保存,避免每次调用 strlen。
- 字符串 concatenation 需要分配新 buffer,复制两侧内容,并以 nul terminator 结尾。
- 对象释放必须统一回收 header、字符 buffer 和对象自身,避免泄漏或重复释放。
目录
| 章节 | 内容 |
|---|---|
| Values and objects | Value 与 heap object |
| Struct inheritance | Obj header |
| Strings | ObjString 表示 |
| Operations on strings | concatenation 与比较 |
| Freeing objects | 生命周期 |
| Challenges | 扩展练习 |
| Design Note:String Encoding | 编码选择 |
Values and objects
之前的 Value 可以直接容纳 number、Boolean 和 nil。string 的大小不固定,不能嵌入固定宽度的 union;它需要在 heap 上分配,再由 Value 保存 pointer。

这样 Value 只保存对象地址,实际字符数据放在 ObjString 中。对象的生命周期不再由 C 的局部变量自动管理,后续需要 garbage collector 追踪。
Struct inheritance
clox 使用 C struct 的首字段布局模拟 object hierarchy。所有 object 都以 Obj header 开头,具体类型再扩展自己的字段:

Obj header 保存 type 和 next pointer。type 用于运行时判断 object 类型,next 把所有 allocated objects 串成链表,便于 GC 遍历。
Strings
ObjString 保存 char* chars、int length 和 uint32_t hash。长度让 string 操作不必重复扫描结尾的 nul;hash 让后续 Hash Table 能快速定位 key。
Pascal string 把长度放在字符前:

clox 仍使用 C 风格 nul-terminated chars,额外保存 length。这样可以和 C library 互操作,同时避免每次求长度。
Operations on strings
字符串相等不能只比较 pointer:两个独立分配但内容相同的 string 仍应相等。比较 length 后逐字节比较 chars;interning 加入后,可以进一步把相同内容 canonicalize 到同一个对象。
Concatenation
concatenation 的执行顺序是从 stack 取右 string,再取左 string;分配 left.length + right.length + 1 的 buffer,复制两段字符,写入 nul terminator,再创建 ObjString 并压回 stack。

临时对象在分配过程中必须保持 reachable。否则未来 GC 介入时,新建但尚未放回 stack 的对象可能被错误回收。

Freeing objects
freeObject 根据 Obj.type 分派释放逻辑。ObjString 先释放 chars,再释放 object;未知类型应触发 assertion 或安全的 default 分支。统一 freeObjects 遍历 object 链表,在 VM shutdown 时释放所有对象。
Challenges
1. String interning
实现 string interning,使相同字符序列共享同一个 ObjString,并比较 lookup 成本、内存收益与弱引用清理。
2. Substrings
添加 substring 操作,决定是复制字符还是让新对象共享 backing storage。
3. Mutable strings
设计 mutable string,并说明哈希缓存、table key、aliasing 和 GC 的影响。
Design Note:String Encoding
字符串编码影响 API、内存布局和索引语义。UTF-8 以变长 byte 序列保存 Unicode code point,节省 ASCII 空间但使“第 n 个字符”的随机访问变复杂;UTF-16 或固定宽度 code point 则有不同的空间与 indexing trade-off。
语言必须明确 length 表示 bytes、code points 还是 grapheme clusters。clox 的初版主要展示 object 与 memory 管理,因此采用简单的 byte string;生产语言需要进一步定义 normalization、invalid encoding 和 slicing 的规则。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、C 和测试代码片段,便于与上文译文逐段对照。
参考资料
Code block 1
VAL_NUMBER,
Code block 2
VAL_OBJ
Code block 3
} ValueType;
Code block 4
double number;
Code block 5
Obj* obj;
Code block 6
} as;
Code block 7
#define IS_NUMBER(value) ((value).type == VAL_NUMBER)
Code block 8
#define IS_OBJ(value) ((value).type == VAL_OBJ)
Code block 9
#define AS_BOOL(value) ((value).as.boolean)
Code block 10
#define IS_OBJ(value) ((value).type == VAL_OBJ)
Code block 11
#define AS_OBJ(value) ((value).as.obj)
Code block 12
#define AS_BOOL(value) ((value).as.boolean)
Code block 13
#define NUMBER_VAL(value) ((Value){VAL_NUMBER, {.number = value}})
Code block 14
#define OBJ_VAL(object) ((Value){VAL_OBJ, {.obj = (Obj*)object}})
Code block 15
typedef struct {
Code block 16
#include "common.h"
Code block 17
typedef struct Obj Obj;
Code block 18
typedef enum {
Code block 19
#ifndef clox_object_h
#define clox_object_h
#include "common.h"
#include "value.h"
struct Obj {
ObjType type;
};
#endif
Code block 20
#include "value.h"
Code block 21
typedef enum {
OBJ_STRING,
} ObjType;
Code block 22
struct Obj {
Code block 23
#include "value.h"
Code block 24
#define OBJ_TYPE(value) (AS_OBJ(value)->type)
Code block 25
typedef enum {
Code block 26
typedef struct Obj Obj;
Code block 27
typedef struct ObjString ObjString;
Code block 28
typedef enum {
Code block 29
};
Code block 30
struct ObjString {
Obj obj;
int length;
char* chars;
};
Code block 31
#endif
Code block 32
#define OBJ_TYPE(value) (AS_OBJ(value)->type)
Code block 33
#define IS_STRING(value) isObjType(value, OBJ_STRING)
Code block 34
typedef enum {
Code block 35
};
Code block 36
static inline bool isObjType(Value value, ObjType type) {
return IS_OBJ(value) && AS_OBJ(value)->type == type;
}
Code block 37
#endif
Code block 38
IS_STRING(POP())
Code block 39
#define IS_STRING(value) isObjType(value, OBJ_STRING)
Code block 40
#define AS_STRING(value) ((ObjString*)AS_OBJ(value))
#define AS_CSTRING(value) (((ObjString*)AS_OBJ(value))->chars)
Code block 41
typedef enum {
Code block 42
[TOKEN_IDENTIFIER] = {NULL, NULL, PREC_NONE},
Code block 43
[TOKEN_STRING] = {string, NULL, PREC_NONE},
Code block 44
[TOKEN_NUMBER] = {number, NULL, PREC_NONE},
Code block 45
static void string() {
emitConstant(OBJ_VAL(copyString(parser.previous.start + 1,
parser.previous.length - 2)));
}
Code block 46
};
Code block 47
ObjString* copyString(const char* chars, int length);
Code block 48
static inline bool isObjType(Value value, ObjType type) {
Code block 49
#define clox_compiler_h
Code block 50
#include "object.h"
Code block 51
#include "vm.h"
Code block 52
#include <stdio.h>
#include <string.h>
#include "memory.h"
#include "object.h"
#include "value.h"
#include "vm.h"
ObjString* copyString(const char* chars, int length) {
char* heapChars = ALLOCATE(char, length + 1);
memcpy(heapChars, chars, length);
heapChars[length] = '\0';
return allocateString(heapChars, length);
}
Code block 53
#include "common.h"
Code block 54
#define ALLOCATE(type, count) \
(type*)reallocate(NULL, 0, sizeof(type) * (count))
Code block 55
#define GROW_CAPACITY(capacity) \
Code block 56
#include "vm.h"
Code block 57
static ObjString* allocateString(char* chars, int length) {
ObjString* string = ALLOCATE_OBJ(ObjString, OBJ_STRING);
string->length = length;
string->chars = chars;
return string;
}
Code block 58
#include "vm.h"
Code block 59
#define ALLOCATE_OBJ(type, objectType) \
(type*)allocateObject(sizeof(type), objectType)
Code block 60
static ObjString* allocateString(char* chars, int length) {
Code block 61
#define ALLOCATE_OBJ(type, objectType) \
(type*)allocateObject(sizeof(type), objectType)
Code block 62
static Obj* allocateObject(size_t size, ObjType type) {
Obj* object = (Obj*)reallocate(NULL, 0, size);
object->type = type;
return object;
}
Code block 63
static ObjString* allocateString(char* chars, int length) {
Code block 64
case VAL_NUMBER: printf("%g", AS_NUMBER(value)); break;
Code block 65
case VAL_OBJ: printObject(value); break;
Code block 66
}
Code block 67
ObjString* copyString(const char* chars, int length);
Code block 68
void printObject(Value value);
Code block 69
static inline bool isObjType(Value value, ObjType type) {
Code block 70
void printObject(Value value) {
switch (OBJ_TYPE(value)) {
case OBJ_STRING:
printf("%s", AS_CSTRING(value));
break;
}
}
Code block 71
"string" == "string"
Code block 72
case VAL_NUMBER: return AS_NUMBER(a) == AS_NUMBER(b);
Code block 73
case VAL_OBJ: {
ObjString* aString = AS_STRING(a);
ObjString* bString = AS_STRING(b);
return aString->length == bString->length &&
memcmp(aString->chars, bString->chars,
aString->length) == 0;
}
Code block 74
default: return false; // Unreachable.
Code block 75
#include <stdio.h>
Code block 76
#include <string.h>
Code block 77
#include "memory.h"
Code block 78
#include <string.h>
Code block 79
#include "object.h"
Code block 80
#include "memory.h"
Code block 81
case OP_LESS: BINARY_OP(BOOL_VAL, <); break;
Code block 82
case OP_ADD: {
if (IS_STRING(peek(0)) && IS_STRING(peek(1))) {
concatenate();
} else if (IS_NUMBER(peek(0)) && IS_NUMBER(peek(1))) {
double b = AS_NUMBER(pop());
double a = AS_NUMBER(pop());
push(NUMBER_VAL(a + b));
} else {
runtimeError(
"Operands must be two numbers or two strings.");
return INTERPRET_RUNTIME_ERROR;
}
break;
}
Code block 83
case OP_SUBTRACT: BINARY_OP(NUMBER_VAL, -); break;
Code block 84
static void concatenate() {
ObjString* b = AS_STRING(pop());
ObjString* a = AS_STRING(pop());
int length = a->length + b->length;
char* chars = ALLOCATE(char, length + 1);
memcpy(chars, a->chars, a->length);
memcpy(chars + a->length, b->chars, b->length);
chars[length] = '\0';
ObjString* result = takeString(chars, length);
push(OBJ_VAL(result));
}
Code block 85
#include <stdio.h>
Code block 86
#include <string.h>
Code block 87
#include "common.h"
Code block 88
};
Code block 89
ObjString* takeString(char* chars, int length);
Code block 90
ObjString* copyString(const char* chars, int length);
Code block 91
ObjString* takeString(char* chars, int length) {
return allocateString(chars, length);
}
Code block 92
#include "debug.h"
Code block 93
#include "object.h"
#include "memory.h"
Code block 94
#include "vm.h"
Code block 95
"st" + "ri" + "ng"
Code block 96
0000 OP_CONSTANT 0 "st"
0002 OP_CONSTANT 1 "ri"
0004 OP_ADD
0005 OP_CONSTANT 2 "ng"
0007 OP_ADD
0008 OP_RETURN
Code block 97
struct Obj {
ObjType type;
Code block 98
struct Obj* next;
Code block 99
};
Code block 100
Value* stackTop;
Code block 101
Obj* objects;
Code block 102
} VM;
Code block 103
resetStack();
Code block 104
vm.objects = NULL;
Code block 105
}
Code block 106
object->type = type;
Code block 107
object->next = vm.objects;
vm.objects = object;
Code block 108
return object;
Code block 109
} InterpretResult;
Code block 110
extern VM vm;
Code block 111
void initVM();
Code block 112
void freeVM() {
Code block 113
freeObjects();
Code block 114
}
Code block 115
void* reallocate(void* pointer, size_t oldSize, size_t newSize);
Code block 116
void freeObjects();
Code block 117
#endif
Code block 118
void freeObjects() {
Obj* object = vm.objects;
while (object != NULL) {
Obj* next = object->next;
freeObject(object);
object = next;
}
}
Code block 119
static void freeObject(Obj* object) {
switch (object->type) {
case OBJ_STRING: {
ObjString* string = (ObjString*)object;
FREE_ARRAY(char, string->chars, string->length + 1);
FREE(ObjString, object);
break;
}
}
}
Code block 120
(type*)reallocate(NULL, 0, sizeof(type) * (count))
Code block 121
#define FREE(type, pointer) reallocate(pointer, sizeof(type), 0)
Code block 122
#define GROW_CAPACITY(capacity) \
Code block 123
#include "common.h"
Code block 124
#include "object.h"
Code block 125
#define ALLOCATE(type, count) \
Code block 126
#include "memory.h"
Code block 127
#include "vm.h"
Code block 128
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
参考资料
- 原文:Strings
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)