gccrs icon indicating copy to clipboard operation
gccrs copied to clipboard

LiteralPatterns lose their minus prefix

Open dafaust opened this issue 3 years ago • 2 comments

(Note: this came up while testing #1244, below case will not compile without support for integer primitives in match, but it is a general problem.)

I tried this code:

extern "C" {
    fn printf(s: *const i8, ...);
}

fn foo (x: i32) {
    match x {
        -2 => {
            let a = "minus two!\n\0";
            let b = a as *const str;
            let c = b as *const i8;
            printf (c);
        },
        _ => {
            let a = "else\n\0";
            let b = a as *const str;
            let c = b as *const i8;
            printf (c);
        }
    }
}

fn main () {
    foo (-2);
    foo (2);
}

I expected to see this happen:

minus two!
else

Instead, this happened:

else
minus two!

Looking at the pattern in the AST, we have no information recording that the literal actually has a - prefix

Breakpoint 6, Rust::HIR::ASTLoweringPattern::visit (this=0x7fffffffcb00, pattern=...) at ../../gccrs/gcc/rust/hir/rust-ast-lower-pattern.cc:201
(gdb) p pattern
$4 = (Rust::AST::LiteralPattern &) @0x32b0be0: {<Rust::AST::Pattern> = {
    _vptr.Pattern = 0x2531a50 <vtable for Rust::AST::LiteralPattern+16>}, lit = {value_as_string = {
      static npos = 18446744073709551615, 
      _M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, _M_p = 0x32b0bf8 "2"}, _M_string_length = 1, {
        _M_local_buf = "2\000\377\377\377\177\000\000@\377\332\000\000\000\000", 
        _M_allocated_capacity = 140737488289842}}, type = Rust::AST::Literal::INT, 
    type_hint = Rust::CORETYPE_STR}, locus = {gcc_loc_ = 33120}, node_id = 22}

So after lowering etc. when compiling the pattern for the match, we build a case which actually matches 2 not -2.

Meta

  • What version of Rust GCC were you using, git sha if possible. master with #1244

dafaust avatar May 10 '22 19:05 dafaust

For RangePatternBoundLiteral we have

// Minus prefixed to literal (if integer or floating-point)
bool has_minus;

So I guess we need something like this for the basic LiteralPattern

dafaust avatar May 10 '22 19:05 dafaust

This is my fault: 03ec66cf1162f139ba873e5d8237a1dfad989937

Let's revert this commit and tie it into to literal code-generation properly.

philberty avatar May 11 '22 08:05 philberty