Skip to content
Snippets Groups Projects
bc_interpreter.h 2.45 KiB
Newer Older
#pragma once
#include "parser.h"
#include "heap.h"

#define OPERAND_STACK_INIT_CAPACITY 512
#define FRAME_STACK_CAPACITY 512

//#define READ_BYTE(str,pos) str . str [ *pos++ ]

typedef enum {
  CONSTANT_INTEGER,
  CONSTANT_BOOLEAN,
  CONSTANT_NULL,
  CONSTANT_STRING,
  CONSTANT_FUNCTION,
  // VALUE_ARRAY,
  // VALUE_OBJECT,
  // VALUE_INVALID
} ConstantType;

typedef struct Class {
  u16 member_count;
  u16 * members;
} Class;

typedef struct Constant {
  ConstantType kind;
  union {
    i32 integer;
    bool boolean;
    Str string;
    ConstantFunction function;
  };
} Constant;

typedef struct Program {
  u16 constant_count;
  Constant * constant_pool;
  //size_t entry_point;
  u16 entry_point;
typedef struct OperandStack {
  Value ** elements;
  size_t size;
  size_t capacity;
} OperandStack;

void ostack_init ( OperandStack * stack );
Value * ostack_pop ( OperandStack * stack  );
Value * ostack_top ( OperandStack * stack  );
void ostack_push ( OperandStack * stack , Value * value );
void ostack_destroy ( OperandStack * stack );

typedef struct Frame {
  struct Frame * prev;
  size_t return_ip;
  Value * locals [];
} Frame;

typedef struct VM {
  Program program;
  Heap heap;
  size_t instruction_pointer;
} VM;

void vm_init ( VM * vm, size_t heap_size );
void vm_destroy ( VM * vm );

// void * heap_alloc_alligned ( Heap * heap, size_t len, size_t align );
// void * heap_alloc ( Heap * heap, size_t len );
// void heap_init ( Heap * heap, size_t heap_size );
// void heap_destroy ( Heap * heap );
// Value * make_null ( ASTInterpreterState * state );
// Value * make_int ( ASTInterpreterState * state, i32 val );
// Value * make_bool ( ASTInterpreterState * state, bool val );

//inline u8 read_byte ( Str str, size_t * pos );

Value * alloc_constant ( VM * vm, u16 index );
ObjectValue * create_object ( VM * vm, Class * class );

void print_operand_value ( Value * value );
void print_call ( VM * vm, u16 index, u8 arguments );

void read_header ( Str input, size_t * pos );
void read_constant_pool ( Program * program, Str input, size_t * pos );
//void read_globals ( Program * program, Str input, size_t * pos );
void parse_program ( Program * program, Str input );
void bc_function_call ( VM * vm, u8 arguments, bool is_function, Str * name );

//void bc_intepret ( VM * vm, Str input, size_t & offset );
int vm_interpret ( VM * vm, Str input );