Skip to content

Commit

Permalink
more consistent function/type show
Browse files Browse the repository at this point in the history
Shows unqualified names for both functions (as before) and types. Nice when an optic uses a non-exported type from some module.
  • Loading branch information
aplavin committed Dec 18, 2024
1 parent 15bb131 commit a98868d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/sugar.jl
Original file line number Diff line number Diff line change
Expand Up @@ -493,12 +493,17 @@ IndexLens(::Tuple{Properties}) = Properties()
### nice show() for optics
_shortstring(prev, o::PropertyLens{field}) where {field} = "$prev.$field"
_shortstring(prev, o::IndexLens) ="$prev[$(join(repr.(o.indices), ", "))]"
_shortstring(prev, o::Union{Function,Type}) = _isoperator(o) ? "$o$prev" : "$o($prev)"
_shortstring(prev, o::Base.Fix1) = _isoperator(o.f) ? "$(o.x) $(o.f) $prev" : "$(o.f)($(o.x), $prev)"
_shortstring(prev, o::Base.Fix2) = _isoperator(o.f) ? "$prev $(o.f) $(o.x)" : "$(o.f)($prev, $(o.x))"
_shortstring(prev, o::Union{Function,Type}) = _isoperator(o) ? "$(_fT_repr(o))$prev" : "$(_fT_repr(o))($prev)"
_shortstring(prev, o::Base.Fix1) = _isoperator(o.f) ? "$(o.x) $(_fT_repr(o.f)) $prev" : "$(_fT_repr(o.f))($(o.x), $prev)"
_shortstring(prev, o::Base.Fix2) = _isoperator(o.f) ? "$prev $(_fT_repr(o.f)) $(o.x)" : "$(_fT_repr(o.f))($prev, $(o.x))"
_shortstring(prev, o::Elements) = "$prev[∗]"
_shortstring(prev, o::Properties) = "$prev[∗ₚ]"

# compact representation of functions and types
# most notably, it deals with the module name in a consistent way: doesn't show it
# by default, it's not shown for functions but shown for types, see https://github.com/JuliaLang/julia/issues/56790
_fT_repr(o) = repr(o; context=:compact => true)

# can f be stringfied using the operator (infix) syntax?
# otherwise uses regular function call syntax
_isoperator(f::Function) = Base.isoperator(nameof(f))
Expand Down
2 changes: 2 additions & 0 deletions test/test_core.jl
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,8 @@ end
@test sprint(show, (@optic Tuple(_.a[2]))) == "(@o Tuple(_.a[2]))"
@test sprint(show, (@optic log(_).a[2])) == "(@o _.a[2]) ∘ log" # could be shorter, but difficult to dispatch correctly without piracy
@test sprint(show, (@optic log(_.a[2])); context=:compact => true) == "log(_.a[2])"
@test sprint(show, (@optic Base.tail(_.a[2])); context=:compact => true) == "tail(_.a[2])" # non-exported function
@test sprint(show, (@optic Base.Fix2(_.a[2])); context=:compact => true) == "Fix2(_.a[2])" # non-exported type
end

@testset "text/plain show" begin
Expand Down

0 comments on commit a98868d

Please sign in to comment.