Skip to content

Commit 2e10c3d

Browse files
committed
When possible, represent functions in a literal way
1 parent 69afcee commit 2e10c3d

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

lib/elixir/lib/binary/inspect.ex

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ defprotocol Binary.Inspect do
1111
printing.
1212
"""
1313

14-
@only [BitString, List, Tuple, Atom, Number, Any]
14+
@only [BitString, List, Tuple, Atom, Number, Function, Any]
1515

1616
def inspect(thing, opts)
1717
end
@@ -417,6 +417,22 @@ defimpl Binary.Inspect, for: Regex do
417417
end
418418
end
419419

420+
defimpl Binary.Inspect, for: Function do
421+
@moduledoc """
422+
Represents functions, in a literal form, when possible
423+
"""
424+
425+
def inspect(thing, _opts) do
426+
fun_info = :erlang.fun_info(thing)
427+
if fun_info[:type] == :external and
428+
fun_info[:env] == [] do
429+
"function(#{Kernel.inspect(fun_info[:module])}.#{fun_info[:name]}/#{fun_info[:arity]})"
430+
else
431+
iolist_to_binary :io_lib.format('~p', [thing])
432+
end
433+
end
434+
end
435+
420436
defimpl Binary.Inspect, for: Any do
421437
@moduledoc """
422438
For all other terms not implemented, we use the default

lib/elixir/test/elixir/binary/inspect_test.exs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,26 @@ defmodule Binary.Inspect.ListTest do
185185
end
186186
end
187187

188+
defmodule Binary.Inspect.FunctionTest do
189+
use ExUnit.Case, async: true
190+
191+
test :funs do
192+
bin = inspect(fn(x) -> x + 1 end)
193+
assert '#Fun<' ++ _ = binary_to_list(bin)
194+
end
195+
196+
test :external_elixir do
197+
bin = inspect(function(Enum.map/2))
198+
assert bin == "function(Enum.map/2)"
199+
end
200+
201+
test :external_erlang do
202+
bin = inspect(function(:lists.map/2))
203+
assert bin == "function(:lists.map/2)"
204+
end
205+
206+
end
207+
188208
defmodule Binary.Inspect.AnyTest do
189209
use ExUnit.Case, async: true
190210

0 commit comments

Comments
 (0)