Can we peek out partially inferred typing info. from Ocaml toplevel/compiler for a program that does not compile?
I would like to know, in Ocaml, whether a partial typing info. can be drawn by some existed functionality of toplevel/compiler, for a program that does not compile? Let me explain.
In Ocaml, it's well known that inferred typed can be retrieved by -annot file. However, sometimes we have a piece of code that does not compile due to some typing error. It gives a error exported to the toplevel, of this pattern
"This expression has type A, but was expected type B"
An artificial example would be
# let x =
let y = 5 in
not y;;
Characters 32-33:
not y;;
^
Error: This expression has type int
but an expression was expected of type bool
The programmer of this piece of code should understand well the 2nd part of this message, i.e., "y is expected of type bool", because of the "not y" part. However, she/he might have some difficulty to understand the 1st part of this error message: how this "y" is inferred to have type "int"? Thus it would be interesting to have a partial set of inferred types, before the type conflicts are raised. For the example above, one would like the interpreter tells that the first "y" (from "let y = 5") is of type int, by which I will know the reason why the second "y" (from "not y") is infered to be of type int.
Could you tell me whether the described functionality is already provided by some ocaml interpreter/compiler?
In general words, my question is: can ocaml toplevel, or its interpreter, yield partially inferred types that user can retrieve in order to more efficiently find the source of their typing error?
This question might not make sense because of the non-uniqueness of the partially inferred type annotation. However, the example exampl开发者_运维问答e should show that at least for some cases, and some partially inferred types have its usage.
Thank you for your ideas.
The type annotations by generated by the -annot
switch are available even if the program did not compile. You'll see types for the expressions that the compiler got through, and some of them may be incomplete. This doesn't tell you the compiler's reasoning for inferring the types, but it does tell you how far the compiler went and lets you explore what it's inferred.
For example, with this source code:
let x = [(let y = 5 in not y); true];;
x
has the type_a list
(the compiler hasn't gotten far enough to figure out_a
).y
has the typeint
.not
has the typebool -> bool
.- The error message is that the second occurrence of
y
has the typeint
(and we've seen where it was inferred) but the context expects the typebool
(and we can see that, sincenot
is a function whose argument type isbool
).
I don't know how to see these types from the toplevel, but if you have a source file with your code, you can run ocamlc -c -annot
, open the source in a suitable editor (such as Emacs) and view the inferred types whether the compilation succeeded or not.
精彩评论