gleam-lang / gleam

⭐️ A friendly language for building type-safe, scalable systems!
https://gleam.run
Apache License 2.0
16.51k stars 691 forks source link

Gleam compiler crash when pattern matching bit arrays #3251

Open mooreryan opened 1 month ago

mooreryan commented 1 month ago

I have triggered a compiler crash when pattern matching on bit arrays.

Versions

Gleam version 1.2.1 OS: Ubuntu 22.04.4

Steps to reproduce

$ gleam new bit_array_crash
$ cd bit_array_crash

$ printf "import gleam/io

pub fn yo(bit_array: BitArray) {
  case bit_array {
    <<0 as n:size(8), _:bytes>> -> {
      io.debug(n)
      Nil
    }
    _ -> Nil
  }
}
" > src/bit_array_crash.gleam

$ gleam run
This is a bug in the Gleam compiler, sorry!

Please report this crash to https://github.com/gleam-lang/gleam/issues/new
and include this error message with your report.

Panic: compiler-core/src/erlang/pattern.rs:201
        Pattern segment match not recognised
Gleam version: 1.2.1
Operating system: linux

If you can also share your code and say what file you were editing or any
steps to reproduce the crash that would be a great help.

You may also want to try again with the `GLEAM_LOG=trace` environment
variable set.

The code is this:

import gleam/io

pub fn yo(bit_array: BitArray) {
  case bit_array {
    <<0 as n:size(8), _:bytes>> -> {
      io.debug(n)
      Nil
    }
    _ -> Nil
  }
}

It is the 0 as n:size(8) that seems to be the issue. Also if you change to this <<_ as n:size(8), _:bytes>> or this <<0:size(8), _ as n:bytes>>, you will also get the compiler crash.

Compiler trace

trace.txt

lpil commented 3 weeks ago

Hello! Thanks for the report.

What is your intent with the code 0 as n:size(8)? n here will always equal 0, no?

mooreryan commented 3 weeks ago

Potentially something like this:

  case n {
    <<0 as n:size(8), _:bytes>> | <<1 as n:size(8), _:bytes>> -> // ... do something with `n`
    _ -> todo
  }

But additionally, <<_ as n:size(8), _:bytes>> and <<0:size(8), _ as n:bytes>> also trigger the same crash.

(I suppose it may be rather a bug somewhere else, as the tooling (for vscode at least) is fine with all of the mentioned forms, whereas the compiler itself is the thing that crashes.)

lpil commented 3 weeks ago

Nice, thank you