JuliaDebug / Cthulhu.jl

The slow descent into madness
MIT License
650 stars 41 forks source link

Allow user to overload printing behavior #535

Open MilesCranmer opened 8 months ago

MilesCranmer commented 8 months ago

(x-ref https://discourse.julialang.org/t/proposed-alias-for-union-types/108205/142?u=milescranmer)

Julia’s type system is the best I’ve encountered in any language, but it can admittedly get a bit verbose at times. In particular things like optimizer options can make extensive use of type parameters and fill up multiple lines. Especially as some types stretch over the VSCode length limit in the Cthulhu labels and end up missing some information.

Therefore I was wondering if Cthulhu could permit the user to overload printing behavior for types in a Cthulhu printout, without necessarily overloading the printing behavior for all of Julia, like Float32 → F32, Tuple → Tu, etc, just to make the printouts less verbose.

For example:

import Cthulhu: type_string

## default defined in Cthulhu:
# type_string(t) = string(t)

# user aliases:
type_string(::Type{Float64}) = "F64"
type_string(::Type{Float32}) = "F32"

type_string(::Type{Missing}) = "?"

type_string(::Type{UInt8}) = "U8"

# Union{A,B} -> (A|B)
type_string(U::Union) = "(" * join(type_string.(union_to_tuple(U)), "|") * ")"
union_to_tuple(U::Union) = (union_to_tuple(U.a)..., union_to_tuple(U.b)...)
union_to_tuple(T::DataType) = (T,)

# Tuple{A,B} -> Tu{A,B}
type_string(::Type{T}) where {T<:Tuple} = "Tu{" * join(type_string.(T.parameters), ",") * "}"

# etc.

which you could have in your startup.jl. This would mean you get compact printouts like this:

julia> type_string(Tuple{Union{Float32,UInt8},Float64,Union{Float64,Missing},Missing})
"Tu{(F32|U8),F64,(?|F64),?}"

This is obviously a subjective choice to implement, but if it is simply something users can configure to their needs, it would be great!

This would be backwards compatible of course as it would simply expose an interface.

Cheers, Miles

Zentrik commented 8 months ago

If I'm remembering correctly this is the relevant line in the source code. https://github.com/JuliaDebug/Cthulhu.jl/blob/575a73286598b69c4da9fdd91b63b0ef5480d83d/TypedSyntax/src/show.jl#L121

This seems like an interesting idea and probably simple to implement.

MilesCranmer commented 8 months ago

Thanks! I made a PR in #537.

Example:

Screenshot 2024-01-17 at 21 46 24