Local Variables 22

This commit is contained in:
nazrin 2025-06-07 23:52:16 +00:00
parent 4f2211eb72
commit 72a41e81e6
18 changed files with 1335 additions and 115 deletions

View file

@ -4,6 +4,7 @@ import std.algorithm.searching;
import clox.memory;
import clox.value;
import clox.container.dynarray;
struct OpColour{
string r, g, b;
@ -16,8 +17,10 @@ enum OpCode : ubyte{
@(OpColour("255", "200", "100")) False,
@(OpColour("000", "200", "100")) Pop,
@(OpColour("060", "200", "150")) GetLocal,
@(OpColour("000", "200", "150")) GetGlobal,
@(OpColour("000", "200", "150")) DefineGlobal,
@(OpColour("060", "200", "150")) SetLocal,
@(OpColour("000", "200", "150")) SetGlobal,
@(OpColour("255", "100", "100")) Equal,
@ -39,40 +42,32 @@ enum OpCode : ubyte{
}
struct Chunk{
uint count;
uint capacity;
ubyte* code;
uint* lines;
ValueArray constants;
DynArray!ubyte code;
DynArray!uint lines;
DynArray!Value constants;
void initialise(){
count = 0;
capacity = 0;
code = null;
lines = null;
code.initialise();
lines.initialise();
constants.initialise();
}
void write(ubyte b, uint line = 0){
if(capacity < count + 1){
uint oldCapacity = capacity;
capacity = GROW_CAPACITY(oldCapacity);
code = GROW_ARRAY!ubyte(code, oldCapacity, capacity);
lines = GROW_ARRAY!uint(lines, oldCapacity, capacity);
}
code[count] = b;
lines[count] = line;
count++;
void write(in ubyte[] bytes, uint line = 0){
foreach(b; bytes)
write(b, line);
}
int addConstant(Value value){
int index = cast(int)constants.values[0 .. constants.count].countUntil(value);
void write(ubyte b, uint line = 0){
code ~= b;
lines ~= line;
}
size_t addConstant(Value value){
long index = constants[].countUntil(value);
if(index >= 0)
return index;
assert(constants.count <= ubyte.max);
constants.write(value);
constants ~= value;
return constants.count - 1;
}
void free(){
FREE_ARRAY!ubyte(code, capacity);
FREE_ARRAY!uint(lines, capacity);
code.free();
lines.free();
constants.free();
initialise();
}