Now I'm trying to use Dialyzer and use -spec, -type.
I give the Dialyzer code below, and I expected Dialyzer to notice that "hoge (a) + 1 is invalid", but Dialyzer does not notice.
-spec hoge (X) -> bad when X :: a;
(X) -> number() when X :: number().
hoge(X) when is_number(X) -> 1;
hoge(a) -> bad.
foo() ->
_ = hoge(a) + 1.
But in a different setting
-spec hoge (X) -> bad when X :: a;
(X) -> string() when X :: number().
hoge(X) when is_number(X) -> "1";
hoge(a) -> bad.
foo() ->
_ = hoge(a) + 1.
Dialyzer let me know about this error,
test.erl:12: The call erlang:'+'('bad' | [49,...],1) will never return since it differs in the 1st argument from the success typing arguments: (number(),number())
Why Dialilzer cannot notice a type error in the first setup.
-spec hoge (X) -> bad when X :: a;
(X) -> number() when X :: number().
This contract (specification) means that "hoge is not dialed from" a "->" bad "| number () → number ()", but "'a' | number () → 'bad' | number ()"?
Here is the complete module for the first example.
-module(example).
-export([hoge/1, foo/0]).
-spec hoge (X) -> bad when X :: a;
(X) -> number() when X :: number().
hoge(X) when is_number(X) -> 1;
hoge(a) -> bad.
foo() ->
_ = hoge(a) + 1.
source
share