3

I wonder if is there any ways to make OCaml compiler report warnings about unused functions? I googled but there are not much topics discussed about this feature.

In particular, in the following program, there are two functions "foo" and "bar" which are declared but "bar" is not used in the "_" function. So I think that the OCaml compiler should report "bar" as an unused function.

let foo x y = x + y

let bar x y z = x + y + z         (* should be reported unused *)

let _ =
  let x = foo 1 2 in
  x
Trung Ta
  • 1,582
  • 1
  • 16
  • 25

2 Answers2

4

You need to define a (possibly-empty) .mli interface file saying what this module exports. Otherwise, you're just defining a bar function for other modules to use.

(and make sure you're compiling with warnings on, of course)

Thomas Leonard
  • 7,068
  • 2
  • 36
  • 40
  • Thanks! I tried your solution and it worked well. However, the problems is that my ML files is quite big so it is not easy and convenient to write an MLI files. Is there any options so that this feature can be enabled without using MLI file? My idea is that base on the Makefile, OCaml compiler can know which functions are unused so it can report warnings... – Trung Ta Jun 17 '15 at 09:53
  • 3
    Without an mli, there's no way for the compiler to know what you are intending to export. If your ml file is big, but exports few symbols, then you only need a small mli. If the ml exports many symbols, you can use `ocamlc -i` to generate a template mli for you. – Thomas Leonard Jun 18 '15 at 10:24
  • Thanks Thomas! I want to add another solution to generate template MLI file, that is to use the `corebuild` tool. It is mentioned in this book: [Real world Ocaml](https://realworldocaml.org/v1/en/html/files-modules-and-programs.html). This tool can be installed by using "opam install core" – Trung Ta Jun 19 '15 at 06:06
3

You can have a look at https://github.com/alainfrisch/dead_code_analyzer , which is a "global" dead code detector. It collects from .cmi files the set of exported values and from .cmt files the set of external references, thus allowing to detect exported values which are never used. (There is also some logic to analyze optional arguments and report which ones are never or always passed.)

Alain Frisch
  • 249
  • 3
  • 7