目录
正在加载目录…
正在阅读专栏 Crafting Interpreters:手写解释器 第 22 篇 · 共 35 篇 · 63%

Strings:clox 的字符串对象与内存管理

发布于 2026-09-16 19:17 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 3,578 · 预计阅读 8 分钟 👁 10 次阅读

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 objectsValue 与 heap object
Struct inheritanceObj header
StringsObjString 表示
Operations on stringsconcatenation 与比较
Freeing objects生命周期
Challenges扩展练习
Design Note:String Encoding编码选择

Values and objects

之前的 Value 可以直接容纳 number、Boolean 和 nil。string 的大小不固定,不能嵌入固定宽度的 union;它需要在 heap 上分配,再由 Value 保存 pointer。

value

这样 Value 只保存对象地址,实际字符数据放在 ObjString 中。对象的生命周期不再由 C 的局部变量自动管理,后续需要 garbage collector 追踪。

Struct inheritance

clox 使用 C struct 的首字段布局模拟 object hierarchy。所有 object 都以 Obj header 开头,具体类型再扩展自己的字段:

obj

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 把长度放在字符前:

pstring

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。

viola

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

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

c
  VAL_NUMBER,

Code block 2

c
  VAL_OBJ

Code block 3

c
} ValueType;

Code block 4

text
    double number;

Code block 5

c
    Obj* obj;

Code block 6

text
  } as;

Code block 7

c
#define IS_NUMBER(value)  ((value).type == VAL_NUMBER)

Code block 8

c
#define IS_OBJ(value)     ((value).type == VAL_OBJ)

Code block 9

c
#define AS_BOOL(value)    ((value).as.boolean)

Code block 10

c
#define IS_OBJ(value)     ((value).type == VAL_OBJ)

Code block 11

c
#define AS_OBJ(value)     ((value).as.obj)

Code block 12

c
#define AS_BOOL(value)    ((value).as.boolean)

Code block 13

c
#define NUMBER_VAL(value) ((Value){VAL_NUMBER, {.number = value}})

Code block 14

c
#define OBJ_VAL(object)   ((Value){VAL_OBJ, {.obj = (Obj*)object}})

Code block 15

c
typedef struct {

Code block 16

c
#include "common.h"

Code block 17

c
typedef struct Obj Obj;

Code block 18

c
typedef enum {

Code block 19

c
#ifndef clox_object_h
#define clox_object_h

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

struct Obj {
  ObjType type;
};

#endif

Code block 20

c
#include "value.h"

Code block 21

c
typedef enum {
  OBJ_STRING,
} ObjType;

Code block 22

c
struct Obj {

Code block 23

c
#include "value.h"

Code block 24

c
#define OBJ_TYPE(value)        (AS_OBJ(value)->type)

Code block 25

c
typedef enum {

Code block 26

c
typedef struct Obj Obj;

Code block 27

c
typedef struct ObjString ObjString;

Code block 28

c
typedef enum {

Code block 29

text
};

Code block 30

c
struct ObjString {
  Obj obj;
  int length;
  char* chars;
};

Code block 31

text
#endif

Code block 32

c
#define OBJ_TYPE(value)        (AS_OBJ(value)->type)

Code block 33

c
#define IS_STRING(value)       isObjType(value, OBJ_STRING)

Code block 34

c
typedef enum {

Code block 35

text
};

Code block 36

c
static inline bool isObjType(Value value, ObjType type) {
  return IS_OBJ(value) && AS_OBJ(value)->type == type;
}

Code block 37

text
#endif

Code block 38

c
IS_STRING(POP())

Code block 39

c
#define IS_STRING(value)       isObjType(value, OBJ_STRING)

Code block 40

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

Code block 41

c
typedef enum {

Code block 42

text
  [TOKEN_IDENTIFIER]    = {NULL,     NULL,   PREC_NONE},

Code block 43

text
  [TOKEN_STRING]        = {string,   NULL,   PREC_NONE},

Code block 44

text
  [TOKEN_NUMBER]        = {number,   NULL,   PREC_NONE},

Code block 45

c
static void string() {
  emitConstant(OBJ_VAL(copyString(parser.previous.start + 1,
                                  parser.previous.length - 2)));
}

Code block 46

text
};

Code block 47

c
ObjString* copyString(const char* chars, int length);

Code block 48

c
static inline bool isObjType(Value value, ObjType type) {

Code block 49

c
#define clox_compiler_h

Code block 50

c
#include "object.h"

Code block 51

c
#include "vm.h"

Code block 52

c
#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

c
#include "common.h"

Code block 54

c
#define ALLOCATE(type, count) \
    (type*)reallocate(NULL, 0, sizeof(type) * (count))

Code block 55

c
#define GROW_CAPACITY(capacity) \

Code block 56

c
#include "vm.h"

Code block 57

c
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

c
#include "vm.h"

Code block 59

c
#define ALLOCATE_OBJ(type, objectType) \
    (type*)allocateObject(sizeof(type), objectType)

Code block 60

c
static ObjString* allocateString(char* chars, int length) {

Code block 61

c
#define ALLOCATE_OBJ(type, objectType) \
    (type*)allocateObject(sizeof(type), objectType)

Code block 62

c
static Obj* allocateObject(size_t size, ObjType type) {
  Obj* object = (Obj*)reallocate(NULL, 0, size);
  object->type = type;
  return object;
}

Code block 63

c
static ObjString* allocateString(char* chars, int length) {

Code block 64

c
    case VAL_NUMBER: printf("%g", AS_NUMBER(value)); break;

Code block 65

c
    case VAL_OBJ: printObject(value); break;

Code block 66

text
  }

Code block 67

c
ObjString* copyString(const char* chars, int length);

Code block 68

c
void printObject(Value value);

Code block 69

c
static inline bool isObjType(Value value, ObjType type) {

Code block 70

c
void printObject(Value value) {
  switch (OBJ_TYPE(value)) {
    case OBJ_STRING:
      printf("%s", AS_CSTRING(value));
      break;
  }
}

Code block 71

text
"string" == "string"

Code block 72

c
    case VAL_NUMBER: return AS_NUMBER(a) == AS_NUMBER(b);

Code block 73

c
    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

c
    default:         return false; // Unreachable.

Code block 75

c
#include <stdio.h>

Code block 76

c
#include <string.h>

Code block 77

c
#include "memory.h"

Code block 78

c
#include <string.h>

Code block 79

c
#include "object.h"

Code block 80

c
#include "memory.h"

Code block 81

text
      case OP_LESS:     BINARY_OP(BOOL_VAL, <); break;

Code block 82

c
      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

text
      case OP_SUBTRACT: BINARY_OP(NUMBER_VAL, -); break;

Code block 84

c
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

c
#include <stdio.h>

Code block 86

c
#include <string.h>

Code block 87

c
#include "common.h"

Code block 88

text
};

Code block 89

c
ObjString* takeString(char* chars, int length);

Code block 90

c
ObjString* copyString(const char* chars, int length);

Code block 91

c
ObjString* takeString(char* chars, int length) {
  return allocateString(chars, length);
}

Code block 92

c
#include "debug.h"

Code block 93

c
#include "object.h"
#include "memory.h"

Code block 94

c
#include "vm.h"

Code block 95

text
"st" + "ri" + "ng"

Code block 96

text
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

c
struct Obj {
  ObjType type;

Code block 98

c
  struct Obj* next;

Code block 99

text
};

Code block 100

c
  Value* stackTop;

Code block 101

c
  Obj* objects;

Code block 102

text
} VM;

Code block 103

text
  resetStack();

Code block 104

text
  vm.objects = NULL;

Code block 105

text
}

Code block 106

text
  object->type = type;

Code block 107

text
  object->next = vm.objects;
  vm.objects = object;

Code block 108

c
  return object;

Code block 109

text
} InterpretResult;

Code block 110

text
extern VM vm;

Code block 111

c
void initVM();

Code block 112

c
void freeVM() {

Code block 113

c
  freeObjects();

Code block 114

text
}

Code block 115

text
void* reallocate(void* pointer, size_t oldSize, size_t newSize);

Code block 116

c
void freeObjects();

Code block 117

text
#endif

Code block 118

c
void freeObjects() {
  Obj* object = vm.objects;
  while (object != NULL) {
    Obj* next = object->next;
    freeObject(object);
    object = next;
  }
}

Code block 119

c
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

text
    (type*)reallocate(NULL, 0, sizeof(type) * (count))

Code block 121

c
#define FREE(type, pointer) reallocate(pointer, sizeof(type), 0)

Code block 122

c
#define GROW_CAPACITY(capacity) \

Code block 123

c
#include "common.h"

Code block 124

c
#include "object.h"

Code block 125

c
#define ALLOCATE(type, count) \

Code block 126

c
#include "memory.h"

Code block 127

c
#include "vm.h"

Code block 128

text
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {

参考资料

  • 原文:Strings
  • 系列索引
  • Robert Nystrom, Crafting Interpreters,© 2015–2021
← 返回列表
← 上一篇 Types of Values:tagged union 与动态值表示 下一篇 → Hash Tables:open addressing、tombstone 与 interning

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论