From 1a82d296e752ada05947a5184a89196bd8dc1100 Mon Sep 17 00:00:00 2001 From: pca006132 Date: Sat, 26 Mar 2022 20:58:37 +0800 Subject: [PATCH] nac3core/codegen: prevent users from modifying loop counter Fixes #211 --- nac3core/src/codegen/stmt.rs | 4 +++- nac3standalone/demo/src/loop.py | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 nac3standalone/demo/src/loop.py diff --git a/nac3core/src/codegen/stmt.rs b/nac3core/src/codegen/stmt.rs index 5c3478065..fa869d309 100644 --- a/nac3core/src/codegen/stmt.rs +++ b/nac3core/src/codegen/stmt.rs @@ -189,7 +189,8 @@ pub fn gen_for<'ctx, 'a, G: CodeGenerator>( if ctx.unifier.unioned(iter.custom.unwrap(), ctx.primitives.range) { // setup let iter_val = iter_val.into_pointer_value(); - let i = generator.gen_store_target(ctx, target)?; + let i = generator.gen_var_alloc(ctx, int32.into())?; + let user_i = generator.gen_store_target(ctx, target)?; let (start, end, step) = destructure_range(ctx, iter_val); ctx.builder.build_store(i, ctx.builder.build_int_sub(start, step, "start_init")); ctx.builder.build_unconditional_branch(test_bb); @@ -207,6 +208,7 @@ pub fn gen_for<'ctx, 'a, G: CodeGenerator>( "start_loop", ); ctx.builder.build_store(i, tmp); + ctx.builder.build_store(user_i, tmp); // // if step > 0, continue when i < end let cmp1 = ctx.builder.build_int_compare(inkwell::IntPredicate::SLT, tmp, end, "cmp1"); // if step < 0, continue when i > end diff --git a/nac3standalone/demo/src/loop.py b/nac3standalone/demo/src/loop.py new file mode 100644 index 000000000..da353239a --- /dev/null +++ b/nac3standalone/demo/src/loop.py @@ -0,0 +1,9 @@ +@extern +def output_int32(x: int32): + ... + +def run() -> int32: + for _ in range(10): + output_int32(_) + _ = 0 +