Skip to content

Commit

Permalink
Merge pull request #21 from mrufsvold/add-prettyprint
Browse files Browse the repository at this point in the history
basic pretty printing
  • Loading branch information
mrufsvold authored May 30, 2024
2 parents 19478ae + 1efbf83 commit 3509752
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/DuckDispatch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ include("TypeUtils.jl")
include("BehaviorDispatch.jl")
include("MethodDispatch.jl")
include("DuckTypeMacro.jl")
include("PrettyPrinting.jl")

@testitem "Test Basics" begin
DuckDispatch.@duck_type struct Iterable{T}
Expand Down
39 changes: 39 additions & 0 deletions src/PrettyPrinting.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# function Base.show(io::IO, ::Type{Behavior{F, S}}) where {F, S}
# print(io, "Behavior{", string(F.instance), ", ", tuple(static_fieldtypes(S)...), "}")
# end

function get_duck_type_name(::Type{D}) where {D<:DuckType}
(name, params) = if D isa UnionAll
(D.body.name.name, D.body.parameters)
else
(D.name.name, D.parameters)
end
if isempty(params)
return string(name)
end
return string(name) * "{" * (map(string, params)...) * "}"
end

function Base.show(io::IO, ::Type{D}) where {D<:DuckType}
duck_type_name = get_duck_type_name(D)
print(io, duck_type_name)
behaviors = DuckDispatch.all_behaviors_of(D)
print(io, "\n Behaviors:\n ")

number_to_show = min(3, length(behaviors)-1)
for b in Iterators.take(behaviors, number_to_show)
print(io, b)
print(io, ",","\n ")
end
print(io, behaviors[number_to_show+1])

length(behaviors) > number_to_show+1 && print(io, ",\n ... (Behaviors omitted. call `DuckDispatch.all_behaviors_of(duck_type)` to see all)")
end

function Base.show(io::IO, ::Type{Guise{D, T}}) where {D, T}
print(io, "Guise{", get_duck_type_name(D), ", ", T, "}")
end

function Base.show(io::IO, g::G) where {G<:Guise}
print(io, G, " wrapping:\n", g.data)
end

0 comments on commit 3509752

Please sign in to comment.