Debug OCaml code

I have also been feeling this pain recently

My first couple of attempts to use ocamldebug only resulted in cryptic errors and confusion

A small part of the problem is the docs for it tend more to “a list of things that exist” side, rather than “how to use this thing” (a common problem…).

I tried a bit harder over the weekend and managed to use it a bit.

Some thoughts:

  • it should be integrated into dune somehow, e.g. I should be able to dune exec --debug or dune test --debug and dune will output bytecode (regardless of existing project settings) and run it under ocamldebug with all necessary paths configured
  • as ever with dune docs it’s hard to know which stanzas are valid where, but adding (modes byte exe) under (tests ...) worked
  • I set a breakpoint and it worked:
(ocd) break @ Oktree 319
Loading program... done.
Breakpoint 1 at 0:569496: file lib/oktree.ml, line 318, characters 19-59
(ocd) run
Time: 71153 - pc: 0:569500 - module Oktree
Breakpoint: 1
319           <|b|>(oct, d)
  • but not entirely:
(ocd) print d
Cannot find module Oktree__.
  • it turns out I have to manually pass a lib path, so my invocation looks like: ocamldebug -I _build/install/default/lib/oktree/ _build/default/tests/test_oktree.bc … these are all tedious details that dune could handle for me
  • readline support (i.e. proper cursor navigation, up-arrow history) and colours (i.e. syntax highlighting etc) would be nice

Debugging in other langs that I’m most familiar with is Python with ipdb, where you get many of the niceties of the IPython shell (readline, syntax highlighting, tab completion menus, pretty-printing shortcuts etc). Python also has the breakpoint() function to set breakpoints from the code itself, will drop into debugger when run. And typical test framework like pytest can drop into debugger for any unhandled exception or failed assertion when running the test suite.

Also for JS in VS Code, which can be fiddly to configure to configure properly but great once it’s working, being able to set breakpoints and watch expressions and browse the stack in the IDE GUI.

6 Likes