quchen / prettyprinter

A modern, extensible and well-documented prettyprinter.
BSD 2-Clause "Simplified" License
293 stars 34 forks source link

Proposal: Add PrettyAnn typeclass #222

Open BinderDavid opened 2 years ago

BinderDavid commented 2 years ago

As discussed in #102, there is currently no way to use the Pretty typeclass in combination with annotations. In that issue, several alternatives were discussed, which were either backwards incompatible or otherwise potentially computationally expensive. But the first issue also mentioned the "obvious" version of the Pretty typeclass. Namely:

class Pretty a ann where
    pretty :: a -> Doc ann

But changing the definition of the typeclass would be obviously backwards incompatible. So I propose the following change:

Add a PrettyAnn typeclass

Add the following typeclass to the library

class PrettyAnn a ann where
    prettyAnn :: a -> Doc ann

together with the obvious instances for primitives, strings, text etc. Just like for Pretty right now.

I see the following benefits:

And the following downsides:

Kleidukos commented 2 years ago

Thank you for bringing this up, I think it's a good proposal if we want to introduce minimal disruption whilst allowing to retain annotations.

sjakobi commented 2 years ago

@BinderDavid Could you clarify which instances you think are obvious?

I imagine that users would want to use concrete annotations for certain primitive types. Wouldn't this be inhibited by the instances that we could provide from prettyprinter?

BinderDavid commented 2 years ago

My original idea was that for every instance of Pretty T that is currently defined in the library, the corresponding instance PrettyAnn T ann should also be provided. This means, of course, that no annotations are used in these instances for these types T, since the implementation is polymorphic in the annotations.

Whether this is desirable depends, of course, on the way the prettyprinter library is used. Personally, I always have newtype wrappers like newtype Var = MkVar String instead of type definitions type Var = String which can be used to generate the appropriate semantic annotations. I don't know whether the use case of generating concrete annotations for plain Strings/Numbers/Lists is prevalent?

The instance could also be declared Overlappable, so the user could provide an overlapping instance instance {-# OVERLAPPING #-} PrettyAnn T ConreteAnnot, no? I would have to check how Overlappable instances interact with MultiParam typeclasses. I haven't looked at the details in a while. (Edit: That probably doesn't make sense)

I wrote this proposal to see whether there is some general interest in adding such a typeclass. If there is some favorable reception of the idea, I could implement a PR which can be the basis of a discussion of details.