ocaml-ppx / ppx_deriving

Type-driven code generation for OCaml
MIT License
466 stars 89 forks source link

`show` breaks lines at an arbitrary column limit #291

Open iitalics opened 1 week ago

iitalics commented 1 week ago

When you use the generated function show it will break lines at ~80 columns, inserting newlines into the returned string:

type t = int list [@@deriving show]
let s = show (List.init 25 succ)
let _ = assert (s = "[1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20; 21;\n  22; 23; 24; 25]")

This is not desirable since semantically, show does not have any context for how the string will be used so it should not be making assumptions about a column limit.

The reason is that the underlying formatting function Format.asprintf uses preconfigured formatting configuration which sets a max_indent margin.

gasche commented 1 week ago

It is not clear to me that any change is desirable here. I can see some use-cases where breaking lines at 80 columns is undesired, but many use-cases where not breaking lines is undesired (because it makes the output unreadable), especially if users have observed the previous behavior and come to rely on it. I think that changing this behavior today would introduce more problems than it solves.

I don't think it is reasonable to expect users to post-process the output to implement a rendering layer. (For example there are newlines in string literals as well in the output). If they wanted to do this they would need a non-rendered intermediate representation instead of a string, at a more complex type than show provide. Or we could think of alternative show variants that bring more control on the pretty-printing logic, enabling to disable it or (for example) to set a different margin. Do you have a suggestion for how such an API could be introduced without breaking backward-compatibility? (Maybe a different deriver is the best route.)

show is a very blunt tool that does a passable job at low cost. If you want something more precise in any given direction, the answer is probably going to be a recommendation to use something else instead.