Crystal: Wrong type suggestion by the compiler

Created on 10 Sep 2019  路  3Comments  路  Source: crystal-lang/crystal

Today, I was playing with Crystal and saw something interesting, and that could be UX bug. I posted the sample code under the error message. The expected result should be Hello, 10 something; however, compiler complains:

$ crystal run src/lorem.cr
Showing last frame. Use --error-trace for full trace.

In src/lorem.cr:9:17

 9 | private def foo() : UInt16
                 ^--
Error: type must be UInt16, not Int32

So, I believe that should be Int32, but the compiler says it should be UInt16 which makes me confused.

Sample code

require "random"

module Lorem
  class Ipsum
    def initialize
     puts "Hello, #{foo()}"
    end

    # It's just a way to define a random function
    private def foo() : UInt16
      Random.new.rand(0..99)
    end
  end
end

Lorem::Ipsum.new

Extra

$ crystal -v
Crystal 0.30.1 [5e6a1b672] (2019-08-12)

LLVM: 4.0.0
Default target: x86_64-unknown-linux-gnu

Most helpful comment

This error message should probably be "method return type is restricted to UInt16, but the method returns Int32 instead" (or something similar) which is a far far less confusing message. Also a very simple PR for someone to make :)

All 3 comments

private def foo() : UInt16
  Random.new.rand(0..99)
end

Numbers default to Int32 unless explicitly specified, so your 0..99 would cause #rand to return an Int32 number between 0 and 99. However, you have an UInt16 type restriction on the #foo method. Int32 != UInt16 hence the error.

The way to fix this would be to specify 0..99 as UInt16. I.e. 0_u16..99_u16.

This error message should probably be "method return type is restricted to UInt16, but the method returns Int32 instead" (or something similar) which is a far far less confusing message. Also a very simple PR for someone to make :)

This error message should probably be "method return type is restricted to UInt16, but the method returns Int32 instead" (or something similar) which is a far far less confusing message. Also a very simple PR for someone to make :)

After a few days later playing with Crystal, I believe this will be an attempt to improve UX. I can write the PR if you like, @RX14.

Edit: I fount the related line for this

https://github.com/crystal-lang/crystal/blob/751226ca68abf90b4c27e8702d82650a406e9442/src/compiler/crystal/semantic/call.cr#L1072-L1078

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lbguilherme picture lbguilherme  路  3Comments

nabeelomer picture nabeelomer  路  3Comments

ArthurZ picture ArthurZ  路  3Comments

relonger picture relonger  路  3Comments

will picture will  路  3Comments