Andriamanitra / coctus

Command line tool for playing Clash of Code locally
MIT License
4 stars 2 forks source link

Stub generator produces invalid Rust code for `loop N+1` #53

Closed Andriamanitra closed 2 months ago

Andriamanitra commented 2 months ago

Describe the bug Stub generator for Rust can produce invalid code when a variable is used in an arithmetic expression describing the number of times to loop. This is because in the expression n+1 as usize the as usize cast only applies to 1 instead of n+1.

To Reproduce

$ printf "read N:int\nloop N+1 write N\n" | clash generate-stub rust --from-file -
use std::io;

macro_rules! parse_input {
    ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}
fn main() {
    let mut input_line = String::new();
    io::stdin().read_line(&mut input_line).unwrap();
    let n = parse_input!(input_line, i32);
    for i in 0..n+1 as usize {
        println!("N");
    }
}

$ printf "read N:int\nloop N+1 write N\n" | clash generate-stub rust --from-file - | rustc --emit=metadata -
error[E0308]: mismatched types
  --> <anon>:10:19
   |
10 |     for i in 0..n+1 as usize {
   |                   ^^^^^^^^^^ expected `i32`, found `usize`

Expected behavior We could add parens like (n+1) as usize. Another option would be n as usize + 1.

daxida commented 2 months ago
Expected behavior
CodinGame adds parens like (n+1) as usize.

This is not true, CG does the same and as such the stub also crashes in the IDE

image image

This is a hack (and a dirty one), that even crashes their stub before entering the IDE (and I'm not even sure why it ends up working).

You can test it yourself:

image

Andriamanitra commented 2 months ago
Expected behavior
CodinGame adds parens like (n+1) as usize.

This is not true, CG does the same and as such the stub also crashes in the IDE

Oops you're right. I've edited the issue description.

Andriamanitra commented 2 months ago

Turns out it's no longer possible to create clashes with loop N+1 so this problem only happened with one legacy clash which is now fixed.