Skip to content
Snippets Groups Projects
bc_compiler.h 2.74 KiB
Newer Older
#include "heap.h"
#include "string.h"

Michal Štěpánek's avatar
Michal Štěpánek committed
#define INIT_STRING_LENGTH 256
#define MAX_SCOPE_VARIABLES 128
#define INVALID_LOCAL 65535
typedef struct String {
  u32 len;
  u32 capacity;
  u8 * str; 
} String;

typedef struct BCFunction {
  u8 parameters;
  u16 locals;
  String bc;
} BCFunction;
typedef struct BCClass {
  u16 fields;
  u16 * indexes;
} BCClass;

typedef struct BCConstant {
  ConstantType kind;
  union {
    i32 integer;
    bool boolean;
    Str string;
    BCFunction function;
    BCClass class;
  };
} BCConstant;

void string_init    ( String * str );
void string_destroy ( String * str );

void string_write_byte ( String * str, const u8  data );
void string_write_u16  ( String * str, const u16 data );
void string_write_i32  ( String * str, const i32 data );
void string_write_constant ( String * str, BCConstant constant );

typedef struct Constants {
  BCConstant constants [ 256 * 256 ];
  u16 constant_count;
  i32 bool_pos [2];
} Constants;

typedef struct Globals {
  u16 names [ 256 * 256 ];
  u16 global_count;
} Globals;

typedef struct LocalScope {
  struct LocalScope * prev;
  u16 used_locals; // locals at use in this scope
  u16 local_count; // locals at use at this time
  Str locals [];
} LocalScope;

typedef struct BCCompilerState {
  Constants constants;
  Globals globals;
  LocalScope * scope;
Michal Štěpánek's avatar
Michal Štěpánek committed
  LocalScope * top;
BCConstant create_function ( u8 parameters );
LocalScope * create_function_scope ( u8 parameters );

Michal Štěpánek's avatar
Michal Štěpánek committed
void add_scope    ( BCCompilerState * state );
void remove_scope ( BCCompilerState * state );

void convert_function_to_bc ( BCCompilerState * state, u16 index );

u16 get_string_index ( BCCompilerState * state, Str str );
u16 get_local_index  ( BCCompilerState * state, Str name );
u16 make_local_index ( BCCompilerState * state, Str name );
u16 get_or_make_class ( BCCompilerState * state, AstObject * object );
u16 get_or_make_int   ( BCCompilerState * state, i32 value );
void gen_cond_body    ( BCCompilerState * state, Ast * cons, Ast * alt );
void gen_loop         ( BCCompilerState * state, Ast * cond, Ast * body );
void gen_loop_from_bc ( BCCompilerState * state, String * cond, String * body );
void gen_bc_array_init ( BCCompilerState * state, AstArray * array, u16 size_index );
void gen_bc_get_local ( String * body, u16 index );
void gen_bc_set_local ( String * body, u16 index );
void gen_bc_constant ( BCCompilerState * state, u16 index );
void insert_constant ( BCCompilerState * state, BCConstant constant );

void bc_state_init    ( BCCompilerState * state );
void bc_state_destroy ( BCCompilerState * state );

void ast_to_bc   ( BCCompilerState * state, Ast * ast );
String generate_bc ( Ast * ast );