Skip to content
Snippets Groups Projects
Commit 93b11e25 authored by Michal Štěpánek's avatar Michal Štěpánek
Browse files

Implement loops + create variable when assigning to non-existent var

parent 8d898e37
No related branches found
No related tags found
1 merge request!4Task 3 odevzdání
Pipeline #270204 skipped
......@@ -374,7 +374,23 @@ void ast_to_bc ( BCCompilerState * state, Ast * ast ) {
if ( index == 65535 ) {
// GLOBAL
u16 str_index = get_string_index ( state, assign -> name );
assert ( str_index != 0 );
if ( str_index == 0 ) {
// create global / local
if ( state -> scope == state -> top ) {
str_index = make_string_index ( state, assign -> name );
u16 * count = & state -> globals . global_count;
state -> globals . names [ *count ] = str_index;
++(*count);
string_write_byte ( & function -> bc, 0x0B );
string_write_u16 ( & function -> bc, str_index );
return;
} else {
index = make_local_index ( state, assign -> name );
string_write_byte ( & function -> bc, 0x09 );
string_write_u16 ( & function -> bc, index );
return;
}
}
u16 * count = & state -> globals . global_count;
size_t i;
for ( i = 0; i < *count; ++i )
......@@ -417,6 +433,31 @@ void ast_to_bc ( BCCompilerState * state, Ast * ast ) {
function -> bc . str [ cons_pos - 1 ] = (cons_len >> 8) & 255;
return;
}
case AST_LOOP: {
AstLoop * loop = (AstLoop*) ast;
BCFunction * function = & state -> constants . constants [ state -> fp ] . function;
ast_to_bc ( state, (Ast*) & (AstNull) { .base = (Ast) { .kind = AST_NULL } } );
size_t start_pos = function -> bc . len;
ast_to_bc ( state, loop -> condition );
string_write_byte ( & function -> bc, 0x0D );
string_write_u16 ( & function -> bc, 3 );
string_write_byte ( & function -> bc, 0x0E );
string_write_u16 ( & function -> bc, 0 );
size_t body_pos = function -> bc . len;
add_scope ( state );
ast_to_bc ( state, loop -> body );
remove_scope ( state );
string_write_byte ( & function -> bc, 0x0E );
string_write_u16 ( & function -> bc, 0 );
size_t after_pos = function -> bc . len;
i16 loop_len = after_pos - start_pos;
function -> bc . str [ after_pos - 2 ] = (-loop_len) & 255;
function -> bc . str [ after_pos - 1 ] = ((-loop_len) >> 8) & 255;
u16 body_len = after_pos - body_pos;
function -> bc . str [ body_pos - 2 ] = body_len & 255;
function -> bc . str [ body_pos - 1 ] = (body_len >> 8) & 255;
return;
}
default:
assert ( false );
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment