How to increase printable_limit from Macro.to_string()?

Hello all,

I need to convert AST with possible long binary to string.
Macro.to_string() uses Inspect and Inspect has the printable_limit option set to 4096 for binaries by default.
I am looking for the way to increase it so binary will not be truncated on to_string()

Thanks,
Serge

This seems like a bug in Macro.to_string to me - it should print everything out. Could you open a bug report?

1 Like

Done

Thank you,
Serge

I believe this is already fixed in master. Until that’s released you can do

Macro.to_string(v, fn
  node, _ when is_binary(node) -> inspect(node, printable_limit: :infinity)
  _, string -> string
end)
4 Likes

Now that Macro.to_string/2 is deprecated, how would one do this?

The bug is fixed so now you can use Macro.to_string/1 and if you’re trying to do something else then that would be best to discuss in a new thread where you state what you’re trying to accomplish.

This is too related to open a new thread. But when posting before, I wasn’t aware that the problem exists only for maps now. It’s basically the same issue but for maps. Opened a GH issue here:

1 Like

Ah, I see. Yeah that does look like a related bug to me :+1:

Copying over José’s answer for shortcuts:

The difference here is that maps are not valid AST. We fallback to inspect in Macro.to_string for convenience, because the goal of the macro is mostly debugging, but if you returned that from a macro, Elixir would raise accordingly. In any case, it won’t be formatted accordingly. The correct fix is to call Macro.escapeor build the correct Map ast, as shown in the result of quote do: %{1 => 2, foo: :bar}|

For me, Macro.escape did the trick:

my_map = Map.new(1..51, &{&1, "value"}) |> Macro.escape()

(quote do: unquote(my_map))
|> Macro.to_string()
|> IO.inspect(printable_limit: :infinity)
1 Like

Ironically I had a similar issue the other day. Code.quoted_to_algebra/2 offers a lot more control:

macro_to_string = 
    fn m ->
       Code.quoted_to_algebra(m,
           pretty: true,
           locals_without_parens: [field: 4, field: 3, field: 2, value: 2, value: 3]
       )
       |> Inspect.Algebra.format(:infinity)
       |> IO.iodata_to_binary()
  end

This doesn’t truncate the map. However, it still does a better job formatting the code when escaping the map to a valid AST.