[erlang-questions] Getting typer to work for me

Kostis Sagonas kostis@REDACTED
Tue Dec 15 10:45:11 CET 2009


Torben Hoffmann wrote:
> Hi.
> 
> I have the following code:
> 
> -module(ups).
> 
> -export([fup/1]).
> 
> -spec fup(integer()) -> {'ok',integer()} | 'wrong'.
> 
> fup(1) ->
>     {ok,2};
> fup(_) ->
>     not_okay.
> 
> And I sort of expected that typer would find the problem in the fup(_) case,
> but I have to use
> dialyzer -Wspecdiffs --src ups.erl
> in order to get the warning I want (namely that the code does not match the
> spec), but the dialyzer docs warns against using this option.
> 
> Am I asking too much?

Yes, you are.

Granted that currently typer does not have proper documentation, so it's 
morally OK to fantasize whatever you want about what you like typer to 
do to your code ;-), but the fact is that typer is supposed to be just a 
type annotator of Erlang code, not a tool that detects type errors. 
Dialyzer is the tool that is supposed to do the latter.

Typer works as follows: You start with a (partially spec-annotated) set 
of Erlang files.  If the file(s) have some specs for some functions and 
these specs are not totally bogus, these are trusted and all that typer 
does is to generate specs for the rest of the functions in these files.
Only if the specs cannot possibly be correct will typer complain about 
them.  Your spec does not have that property: as far as the type system 
is concerned you have just specified something which is more constrained 
than it needs to be for the input argument and more general than reality 
in the function's returned.  But there is no serious problem here.

Try changing the spec to something really wrong:

    -spec fup(integer()) -> {'ok',atom()} | 'wrong'.

and you will see that typer does indeed complain.

Also, try the file without the spec and you will see that typer will 
give you the inferred success typing:

   -spec fup(_) -> 'not_okay' | {'ok',2}.

But typer will never return anything that differs from specs which are 
already present in the file.  These are simply returned as is.

Hope this explains things,

Kostis

PS. Unrelated to the above, but the next version of dialyzer will report 
a warning in the case of your program without the use of -Wspecdiffs.


More information about the erlang-questions mailing list