Skip to content

std/prettyprints: pretty print any expression (including with cycles), customizable #385

Open
@timotheecour

Description

@timotheecour

proposal

add a std/prettyprints module to allow pretty printing arbitrary expressions

design goal

As with std/jsonutils this should have:

  • sane defaults
  • provide enough options so you don't need to roll your own (eg custom depth etc)
  • customizable via hooks for the cases where existing options aren't enough
  • allows pretty-printing cyclic data structures
  • accepts any expression (including ptr|pointer|etc)
  • builtin $ stays simple (I'd still argue $ works for ref|ptr|pointer for all targets (c,cpp,js,vm) + other bugfixes Nim#14043 should be merged in some form or another but that's orhtogonal to this RFC)

unlike dollars.nim, this is not a low-level module, and can have (at least optionally) heaver dependencies (eg tables.nim) for needed functionality and to simplify implementation

eg:

type Option = ref object
  depth: int # how far to recurse
  showDistinct: bool # when true, if no `$` overload exists for a distinct type, print via undistinct
  fpFormat: string # customizes FP printing eg `"%.02f"`
  # etc... that customizes prettyprinting

pretty[T](result: var string, a: T, options: Options = nil) = ...
template pretty[T](a: T, options: Options = nil): string = pretty(result, a, options)
  # for convenience since so common

all overloads are outplace form and there's a single inplace form, just like in #191

  • distinct can be shown via undistinct depending on showDistinct
  • we use a Hash[ByteAddress] to mark already visited addresses and in case input is cyclic

I've already implemented that in a private project with extensive options, so I know it's quite doable.

sample output

  • as html, with dynamically expandable nodes:
    image

  • as a string, printed in terminal via echo
    image

links

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions