Brief
I was just surprised to discover that
let x : int = 4 in x
actually produces the AST I would’ve expected from
let x : int = (4 : int) in x
This was a bit jarring, as the PPX code I’m writing attempts to move a subexpression in such a way that this extra type annotation is a problem. Does anyone have any idea why this is happening? I’d be reluctant to manipulate this in my code if I didn’t understand the motivation. I’m seeing this behavior on OCaml 5.0.0 as well as OCaml 4.13.1.
Detailed
More specifically, consider the following ocaml
session:
$ ocaml -noinit -dparsetree
OCaml version 5.0.0
Enter #help;; for help.
# let x : int = 4 in x;;
Ptop_def
[
structure_item (//toplevel//[1,0+0]..[1,0+20])
Pstr_eval
expression (//toplevel//[1,0+0]..[1,0+20])
Pexp_let Nonrec
[
<def>
pattern (//toplevel//[1,0+4]..[1,0+11]) ghost
Ppat_constraint
pattern (//toplevel//[1,0+4]..[1,0+5])
Ppat_var "x" (//toplevel//[1,0+4]..[1,0+5])
core_type (//toplevel//[1,0+8]..[1,0+11]) ghost
Ptyp_poly
core_type (//toplevel//[1,0+8]..[1,0+11])
Ptyp_constr "int" (//toplevel//[1,0+8]..[1,0+11])
[]
expression (//toplevel//[1,0+4]..[1,0+15])
Pexp_constraint
expression (//toplevel//[1,0+14]..[1,0+15])
Pexp_constant PConst_int (4,None)
core_type (//toplevel//[1,0+8]..[1,0+11])
Ptyp_constr "int" (//toplevel//[1,0+8]..[1,0+11])
[]
]
expression (//toplevel//[1,0+19]..[1,0+20])
Pexp_ident "x" (//toplevel//[1,0+19]..[1,0+20])
]
- : int = 4
Observe the Pexp_constraint
in the output. Given that I never wrote a type assertion in an expression, I didn’t expect to see a Pexp_constraint
here.
Of note: more complex patterns don’t appear to exhibit this behavior. For instance,
let (x : int, y) = (4, 5) in x
produces a tree with no Pexp_constraint
nodes.
I looked over parser.mly
in the OCaml repository and didn’t see anything there that would explain this behavior, but I’m not deeply familiar with that code base. Any ideas what prompts this behavior or whether it’d be a problem if I hacked in a mechanism to remove the (hopefully extraneous) type assertion nodes?