packages feed

shroom-class (empty) → 0.1.0.0

raw patch · 15 files changed

+2143/−0 lines, 15 filesdep +aesondep +basedep +containers

Dependencies added: aeson, base, containers, generics-sop, openapi3, shroom-class, tasty, tasty-golden, tasty-hunit, template-haskell, text, time, universe-base

Files

+ CHANGELOG.md view
@@ -0,0 +1,6 @@+# Revision history for shroom-class++## 0.1.0.0 -- 2026-11-27++* First release. The classes that describe a type to a language model, `Describable` and+  `Surveyable`, and the Template Haskell that derives `Describable` from a type's Haddocks.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Manuel Bärenz+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++    * Redistributions of source code must retain the above copyright+      notice, this list of conditions and the following disclaimer.++    * Redistributions in binary form must reproduce the above+      copyright notice, this list of conditions and the following+      disclaimer in the documentation and/or other materials provided+      with the distribution.++    * Neither the name of the copyright holder nor the names of its+      contributors may be used to endorse or promote products derived+      from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ shroom-class.cabal view
@@ -0,0 +1,76 @@+cabal-version: 3.0+name: shroom-class+version: 0.1.0.0+synopsis: Type-description classes and Template Haskell for shroom+description:+  shroom-class holds the type-description classes of shroom:+  <https://hackage.haskell.org/package/shroom-class/docs/Data-Shroom-Class.html#t:Describable Describable>+  names a type for a model, and+  <https://hackage.haskell.org/package/shroom-class/docs/Data-Shroom-Class.html#t:Surveyable Surveyable>+  adds the properties its values must satisfy, as pure Haskell functions, and+  example values. Template Haskell+  derives+  <https://hackage.haskell.org/package/shroom-class/docs/Data-Shroom-Class.html#t:Describable Describable>+  from Haddock comments and type, constructor and field names, so what a human+  reader sees of a type is the description the+  model reads, and an empty+  <https://hackage.haskell.org/package/shroom-class/docs/Data-Shroom-Class.html#t:Surveyable Surveyable>+  instance does the rest. The package has no prompting runtime and depends on+  no HTTP client and no effect system. It is the base of+  <https://hackage.haskell.org/package/shroom shroom>, which runs prompts, and+  of <https://hackage.haskell.org/package/shroom-baikai shroom-baikai>, which+  connects them to a real model.++category: AI+license: BSD-3-Clause+license-file: LICENSE+author: Manuel Bärenz+maintainer: programming@manuelbaerenz.de+-- copyright:+build-type: Simple+extra-doc-files: CHANGELOG.md+extra-source-files: test/golden/*.golden+tested-with:+  ghc ==9.12++common opts+  ghc-options:+    -Wall+    -haddock+    -Winvalid-haddock++  build-depends:+    aeson ^>=2.2,+    base >=4.20 && <4.22,+    containers >=0.6 && <0.8,+    generics-sop ^>=0.5.1,+    openapi3 ^>=3.2,+    template-haskell >=2.22 && <2.25,+    text >=2.1.2 && <2.2,+    time ^>=1.14,+    universe-base ^>=1.1,++  default-extensions:+    OverloadedStrings+    TypeFamilies++library+  import: opts+  exposed-modules:+    Data.Shroom.Class+    Data.Shroom.Class.TH++  hs-source-dirs: src+  default-language: GHC2024++test-suite shroom-class-test+  import: opts+  type: exitcode-stdio-1.0+  hs-source-dirs: test+  main-is: Main.hs+  default-language: GHC2024+  build-depends:+    shroom-class,+    tasty >=1.4 && <1.6,+    tasty-golden ^>=2.3,+    tasty-hunit ^>=0.10,
+ src/Data/Shroom/Class.hs view
@@ -0,0 +1,810 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE DefaultSignatures #-}+{-# LANGUAGE UndecidableInstances #-}++{- |+Module      : Data.Shroom.Class+Description : Describe a Haskell type, its properties and its examples to a language model.++Classes that describe a Haskell type, its properties and its examples to a+language model. They live in a package of their own, with no dependency on+<https://hackage.haskell.org/package/effectful effectful> or on the rest of+<https://hackage.haskell.org/package/shroom shroom>, so that the module that+defines a type can carry its instances without pulling in an HTTP client or an+effect system.++'Describable' gives a type a one-sentence description and lists the types it+refers to. 'Surveyable' builds on it with properties that a value of the type+must satisfy, and with example values. 'description' renders a type from both+for a model; the @shroom@ package checks the model's answer against the+properties.++To turn a 'Surveyable' type into a prompt, give it an instance of+<https://hackage.haskell.org/package/shroom/docs/Control-Monad-Prompt-Promptable.html#t:Promptable Promptable>+from+<https://hackage.haskell.org/package/shroom/docs/Control-Monad-Prompt-Promptable.html Control.Monad.Prompt.Promptable>.++A bare 'Surveyable' instance surveys the type's fields: the properties of every+field's own type become properties of the whole value. For a user type this+takes a description derived from the Haddock comments (see+"Data.Shroom.Class.TH"), the @generics-sop@ classes, and an empty instance:++@+-- | A user with a name and an email address.+data User = User { userName :: Text, userEmail :: Text }+  deriving stock (Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++\$(deriveDescribable ''User)++instance Surveyable User+@++Here @SOP@ is "Generics.SOP". A type with properties of its own, or none at+all, names a 'Property' type instead, see 'Surveyable'.+-}+module Data.Shroom.Class (+  -- * The classes+  Describable (..),+  Surveyable (..),++  -- * Structural properties: the default+  Structural,+  structuralHolds,+  describeStructural,+  PropertyDefault (..),+  PropertyOf,++  -- * Helpers for hand-written instances+  Described (..),+  reach,+  reachableTypes,+  everyHolds,+  describeEvery,++  -- * Rendering a type for the model+  description,+  annotateFieldTypes,+  fieldNameAt,+) where++-- base++import Data.Int (Int64)+import Data.Kind (Type)+import Data.List.NonEmpty (NonEmpty)+import Data.Maybe (mapMaybe)+import Data.Proxy (Proxy (..))+import Data.Typeable (TypeRep, Typeable, typeRep)+import Data.Void (Void, absurd)+import GHC.Generics (Generically (..))+import Numeric.Natural (Natural)++-- containers+import Data.Set (Set)+import Data.Set qualified as S++-- text+import Data.Text (Text)+import Data.Text qualified as T++-- aeson+import Data.Aeson (ToJSON, Value (..), encode, toJSON)+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KM++-- text+import Data.Text.Lazy (toStrict)+import Data.Text.Lazy.Encoding (decodeUtf8)++-- openapi3+import Data.OpenApi (ToSchema, toSchema)++-- time+import Data.Time (Day, UTCTime)++-- universe-base+import Data.Universe.Class (Universe, universe)++-- generics-sop+import Generics.SOP (All, All2, Code, ConstructorInfo (..), FieldInfo (..), Generic, HasDatatypeInfo (..), I (..), K (..), NP (..), NS (..), SList (..), constructorInfo, constructorName, from, hcollapse, hmap, lengthSList, sList, unSOP)++{- | A class for giving a type a one-sentence description, so that the model+knows what the type means.++Use @$(deriveDescribable ''MyType)@ from "Data.Shroom.Class.TH" to derive+this from the Haddock comments on the type declaration.++'Typeable' is a superclass so that 'description' can tell types apart when it+lists each reachable type once.++== The descriptions that reach the model++'description' sends the requested type's own 'describeType', and then, in a+section of their own, the 'describeType' of every type it can reach through+'referencedTypes', each once. 'Data.Shroom.Class.TH.deriveDescribable' writes+'referencedTypes' for you. __A hand-written instance that does not write it contributes no reachable types:__+the types it refers to are not described to the model.+-}+class (ToJSON a, Typeable a) => Describable a where+  {- | A one- or two-sentence description of what the type represents,+    and what the constructors and fields mean.+  -}+  describeType :: Proxy a -> Text++  {- | The types whose descriptions the model also needs in order to produce+    an @a@: typically the types of its fields. 'description' follows these+    transitively and lists each type once, so an entry may refer back to the+    type itself or to another entry without harm.++    Build an entry for a field type @t@ with @'reach' \@t@, which takes the+    container and base types out and passes their elements through. Defaults+    to the empty list.+  -}+  referencedTypes :: Proxy a -> [Described]+  referencedTypes _ = []++  {- | Whether the type gets a section of its own in the list of reachable+    types. Defaults to 'True'.+  -}+  hasOwnSection :: Proxy a -> Bool+  hasOwnSection _ = True++  {- | The identity of the type that 'description' reports on, by which+    'reachableTypes' keeps that type out of its own list of reachable types.+    Defaults to the type's own 'TypeRep'. A transparent newtype wrapper (@t'Generically' X@)+    forwards to the wrapped type's, because 'description' runs at+    the wrapper while the types that refer back to @X@ name @X@ itself.++    == Writing a transparent newtype wrapper++    A transparent newtype wrapper @W a@ stands for @a@ without being a type of its own to+    the model. Its 'Describable' instance must forward 'describeType', and the+    three methods beyond it:++    * 'referencedTypes' forwards to @a@'s (@referencedTypes _ = referencedTypes (Proxy \@a)@),+      not @'reach' \@a@, which would list @a@ under itself;+    * 'hasOwnSection' is 'False', so the wrapper gets no section;+    * 'describedIdentity' forwards to @a@'s. Forget this one and 'reachableTypes'+      lists the requested type under itself.++    @t'Generically' a@ is such a wrapper, and its instances are a model for one of your own.+  -}+  describedIdentity :: Proxy a -> TypeRep+  describedIdentity = typeRep++{- | A type of which only the 'Describable' instance is known, to put types of+different kinds into one list. Used by 'referencedTypes'.+-}+data Described+  = -- | Packs the type behind the t'Proxy', together with its 'Describable' instance.+    forall t. (Describable t) => Described (Proxy t)++{- | The entries a field of type @t@ contributes to 'referencedTypes': @t@ itself+if it has a section of its own ('hasOwnSection'), otherwise whatever @t@ itself+references. So a field of type @[Speaker]@ or @Maybe Speaker@ contributes+@Speaker@, and a field of type @t'Text'@ contributes nothing:++@+referencedTypes _ = reach \@Person <> reach \@[Address] <> reach \@Text+@+-}+reach :: forall t. (Describable t) => [Described]+reach+  | hasOwnSection (Proxy @t) = [Described (Proxy @t)]+  | otherwise = referencedTypes (Proxy @t)++-- | Every type reachable from @a@ through 'referencedTypes' that has a section, see 'description'.+reachableTypes :: forall a. (Describable a) => Proxy a -> [Described]+reachableTypes p = go (S.singleton (describedIdentity p)) (referencedTypes p)+  where+    -- Breadth first: the whole frontier is emitted before anything it references.+    go _ [] = []+    go seen frontier =+      let (seen', visited) = foldl' visit (seen, []) frontier+          visited' = reverse visited+       in filter hasSection visited' <> go seen' (concatMap children visited')+    visit (seen, acc) d@(Described q)+      | typeRep q `S.member` seen = (seen, acc)+      | otherwise = (S.insert (typeRep q) seen, d : acc)+    hasSection (Described q) = hasOwnSection q+    children (Described q) = referencedTypes q++{- | A class for the properties that a value of your type must satisfy beyond+its shape, together with example values.++A property is a statement about a value that the model is told and that is+checked on the parsed answer. This is the main user-filled class. If your type+has no properties to satisfy beyond those of its fields, write a bare+@instance Surveyable@ and fill in nothing. The sections below say what each+other choice of 'Property' type means. They continue one type, a hotel booking+with a guest:++@+-- | A guest staying a number of nights.+data Booking = Booking { bookingGuest :: Guest, bookingNights :: Int }+  deriving stock (Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++\$(deriveDescribable ''Booking)+@++== The default: the properties of the fields++'Property' defaults to @t'Structural' Booking@, and 'propertyHolds' and+'describeProperties' default to 'structuralHolds' and 'describeStructural'.+These enforce the properties of the fields of the type. So with++@+instance Surveyable Booking+@++every property of @Guest@ is a property of @Booking@. The model is told about it, and+it is checked on the parsed answer. The default needs the @generics-sop@+classes t'Generics.SOP.Generic' and t'Generics.SOP.HasDatatypeInfo' for your type, both derivable+(@deriving anyclass@) from t'GHC.Generics.Generic'. Each type of a field+needs a 'Surveyable' instance of its own.++== Opting out: @type Property Booking = Void@++If you don't require the type to fulfil any properties, not even those of its+fields, write++@+instance Surveyable Booking where+  type Property Booking = Void+@++and nothing else: 'propertyHolds' and 'describeProperties' are then filled in+(vacuously) as well. This needs neither the @generics-sop@ instances for your+type nor 'Surveyable' instances for its fields.++== A custom 'Property' replaces the default++If you require a property of your own, name a 'Property' type for it. Say a+booking is for at least one night:++@+data BookingProperty = AtLeastOneNight+  deriving (Bounded, Enum, Universe)++instance Surveyable Booking where+  type Property Booking = BookingProperty+  propertyHolds booking AtLeastOneNight = bookingNights booking >= 1+  describeProperties _ AtLeastOneNight = Just \"A booking is for at least one night.\"+@++This replaces the default entirely: the properties of the fields are neither+told to the model nor checked. (A @Booking@ with a property of its own loses the+properties of its @Guest@ this way.) A custom 'Property' also needs __both__+'propertyHolds' and 'describeProperties' written out. Leaving one out is a+compile error naming 'PropertyDefault' (@No instance for ‘PropertyDefault+BookingProperty Booking’@), not a silent default of 'True' or 'Nothing'.++To keep the properties of the fields next to your own, combine the two with+'Either' and hand the structural half to 'structuralHolds' and+'describeStructural':++@+instance Surveyable Booking where+  type Property Booking = Either BookingProperty (Structural Booking)+  propertyHolds booking (Left AtLeastOneNight) = bookingNights booking >= 1+  propertyHolds booking (Right p) = structuralHolds booking p+  describeProperties _ (Left AtLeastOneNight) = Just \"A booking is for at least one night.\"+  describeProperties proxy (Right p) = describeStructural proxy p+@++All four equations are needed, or the instance is an incomplete pattern match.++== Container fields contribute no properties++If a field of your type is a list, a 'NonEmpty', a 'Set' or a 'Maybe', then+under a bare instance the properties of its elements are neither checked nor+told to the model: a @[Speaker]@ or a @Maybe Name@ field contributes none,+whatever properties @Speaker@ and @Name@ have. Lift them by hand with+'everyHolds' and 'describeEvery' in a custom 'Property', as the @Speakers@+example under 'everyHolds' does: it combines the type's own property with the+element's property. Add a @t'Structural'@ half for the type, as above, only+where the properties of the type's own fields are wanted too.++== Recursive types++A type that is directly or mutually recursive must not use the structural+default. \"Directly recursive\" means a field of its own type that is not under a+list, 'NonEmpty' or 'Maybe', like the @Neg Expr@ in @data Expr = Lit Int | Neg+Expr@; \"mutually recursive\" means the same through another type's bare+instance. With a bare @instance Surveyable Expr@, 'description' and the+@shroom@ package's check of a value's properties never finish, because the+properties of @Expr@ contain the properties of @Expr@. Opt out on the recursive+type with @type Property Expr = Void@, or give it a custom 'Property' that does+not contain @t'Structural' Expr@.++== A field of a type without shroom classes++If a field of your type has a type without 'Describable' and 'Surveyable'+instances, such as a type from a third-party package, a bare instance does not+compile. For a record++@+data Hotel = Hotel { hotelName :: Text, hotelVersion :: Version }+@++with the field type @Version@ from "Data.Version", GHC reports at+@instance Surveyable Hotel@++@+No instance for ‘Surveyable Version’+  arising from the superclasses of an instance declaration+In the instance declaration for ‘Surveyable Hotel’+@++and @\$(deriveDescribable ''Hotel)@ reports @No instance for ‘Describable+Version’@ at its splice. Either give the field type its own instances, or a+@newtype@ around it to avoid an orphan instance. Or opt out on the enclosing+type with @type Property Hotel = Void@, as in the section \"Opting out\" above. That removes the 'Surveyable' error only, as+'Data.Shroom.Class.TH.deriveDescribable' still needs a 'Describable' instance for the field type.+-}+class (Describable a, Universe (Property a)) => Surveyable a where+  {- | The type of properties for @a@, which must have a 'Universe' instance.+    Defaults to @t'Structural' a@, the properties of @a@'s fields; see the+    class for the other choices.+  -}+  type Property a :: Type++  type Property a = Structural a++  {- | Whether the property holds for the value, used to validate a parsed+    response. Written out unless 'Property' is its default or 'Void'.++    Hint: If you have an "informal" property (like "is an english name")+    that can't be easily checked with code,+    you can still include it in 'describeProperties' and return 'True' here.+  -}+  propertyHolds :: a -> Property a -> Bool+  default propertyHolds :: (PropertyDefault (Property a) a) => a -> Property a -> Bool+  propertyHolds = defaultHolds++  {- | Human-readable description of a property, used in the prompt, or+    'Nothing' for none. Written out unless 'Property' is its default or 'Void'.+  -}+  describeProperties :: Proxy a -> Property a -> Maybe Text+  default describeProperties :: (PropertyDefault (Property a) a) => Proxy a -> Property a -> Maybe Text+  describeProperties = defaultDescribe++  {- | Representative example values, included in the prompt when non-empty.+    Defaults to the empty set.+  -}+  examples :: Proxy a -> Set a+  examples _ = S.empty++-- Instances for common base types, so that a type with a field of one of them+-- can derive its own instances. Each describes the type in a short plain+-- sentence and has no properties: 'Property' is 'Void', written out explicitly.+-- They set 'hasOwnSection' to 'False': they need no section, as their+-- 'describeType' is a sentence that the types using them already quote.+--+-- They live in this module itself, not a sibling: here they are not orphans,+-- and modules importing only "Data.Shroom.Class" see them.++instance Describable Text where+  describeType _ = "A piece of text."+  hasOwnSection _ = False++instance Surveyable Text where+  type Property Text = Void++instance Describable Int where+  describeType _ = "A whole number."+  hasOwnSection _ = False++instance Surveyable Int where+  type Property Int = Void++instance Describable Integer where+  describeType _ = "A whole number."+  hasOwnSection _ = False++instance Surveyable Integer where+  type Property Integer = Void++instance Describable Int64 where+  describeType _ = "A whole number."+  hasOwnSection _ = False++instance Surveyable Int64 where+  type Property Int64 = Void++instance Describable Word where+  describeType _ = "A non-negative whole number."+  hasOwnSection _ = False++instance Surveyable Word where+  type Property Word = Void++instance Describable Natural where+  describeType _ = "A non-negative whole number."+  hasOwnSection _ = False++instance Surveyable Natural where+  type Property Natural = Void++instance Describable Double where+  describeType _ = "A number, possibly with a fractional part."+  hasOwnSection _ = False++instance Surveyable Double where+  type Property Double = Void++instance Describable Float where+  describeType _ = "A number, possibly with a fractional part."+  hasOwnSection _ = False++instance Surveyable Float where+  type Property Float = Void++instance Describable Bool where+  describeType _ = "A truth value: true or false."+  hasOwnSection _ = False++instance Surveyable Bool where+  type Property Bool = Void++instance Describable Char where+  describeType _ = "A single character."+  hasOwnSection _ = False++instance Surveyable Char where+  type Property Char = Void++instance Describable UTCTime where+  describeType _ = "A point in time, in UTC."+  hasOwnSection _ = False++instance Surveyable UTCTime where+  type Property UTCTime = Void++instance Describable Day where+  describeType _ = "A calendar date."+  hasOwnSection _ = False++instance Surveyable Day where+  type Property Day = Void++-- The containers set 'hasOwnSection' to 'False' like the base types: the types+-- using them already quote their 'describeType'.++-- | A list, described through its element type.+instance (Describable a) => Describable [a] where+  describeType _ = "A list of values of the following type: " <> describeType (Proxy @a)+  referencedTypes _ = reach @a+  hasOwnSection _ = False++-- | A list has no properties of its own. The properties of its elements are not lifted, see 'Surveyable'.+instance (Describable a) => Surveyable [a] where+  type Property [a] = Void++-- | A non-empty list, described through its element type.+instance (Describable a) => Describable (NonEmpty a) where+  describeType _ = "A non-empty list of values of the following type: " <> describeType (Proxy @a)+  referencedTypes _ = reach @a+  hasOwnSection _ = False++-- | A non-empty list has no properties of its own. The properties of its elements are not lifted, see 'Surveyable'.+instance (Describable a) => Surveyable (NonEmpty a) where+  type Property (NonEmpty a) = Void++-- | A set, described through its element type.+instance (Describable a) => Describable (Set a) where+  describeType _ = "A set of distinct values of the following type: " <> describeType (Proxy @a)+  referencedTypes _ = reach @a+  hasOwnSection _ = False++-- | A set has no properties of its own. The properties of its elements are not lifted, see 'Surveyable'.+instance (Describable a) => Surveyable (Set a) where+  type Property (Set a) = Void++-- | An optional value, described through its element type.+instance (Describable a) => Describable (Maybe a) where+  describeType _ = "A value that may be absent (null), and otherwise of the following type: " <> describeType (Proxy @a)+  referencedTypes _ = reach @a+  hasOwnSection _ = False++-- | An optional value has no properties of its own. The properties of its element are not lifted, see 'Surveyable'.+instance (Describable a) => Surveyable (Maybe a) where+  type Property (Maybe a) = Void++{- | Forwards to the wrapped type.++These two instances (this one and the one for 'Surveyable') let+@deriving via t'Generically' X instance Promptable X@+(<https://hackage.haskell.org/package/shroom/docs/Control-Monad-Prompt-Promptable.html#t:Promptable Promptable>+is in the @shroom@ package) find the superclass instances it needs: a @deriving via@+coerces only the class's own method. They live here, with the classes, so they+are not orphans.++'ToJSON' for @t'Generically' a@ is @aeson@'s own, which is always the+"GHC.Generics"-based encoding with default options, hence the extra context+(satisfied wherever @a@ derives t'GHC.Generics.Generic').+-}+instance (Describable a, ToJSON (Generically a)) => Describable (Generically a) where+  describeType _ = describeType (Proxy @a)++  -- Like a container, but transparent: @a@ is the type being described, so it+  -- must not appear as a section of its own under it ('reach' would list it).+  -- The three methods below are the contract of a transparent newtype wrapper, see+  -- 'describedIdentity'.+  referencedTypes _ = referencedTypes (Proxy @a)+  hasOwnSection _ = False+  describedIdentity _ = describedIdentity (Proxy @a)++-- | Forwards to the wrapped type, see the 'Describable' instance.+instance (Surveyable a, ToJSON (Generically a)) => Surveyable (Generically a) where+  type Property (Generically a) = Property a+  propertyHolds (Generically x) = propertyHolds x+  describeProperties _ = describeProperties (Proxy @a)+  examples _ = S.mapMonotonic Generically (examples (Proxy @a))++{- | Check that one of an element type's properties holds for every element+of a container. Use it to lift the element's properties into the container's+own 'Property' type, as one side of an 'Either':++@+instance Surveyable Speakers where+  type Property Speakers = Either SpeakersProperty SpeakerProperty+  propertyHolds s (Left SpeakersBetween3And10) = ...+  propertyHolds s (Right p) = everyHolds (speakers s) p+  describeProperties _ (Left SpeakersBetween3And10) = ...+  describeProperties _ (Right p) = describeEvery \"Every speaker\" (Proxy \@Speaker) p+@++In the @type Property@ instance, name the element's concrete property type (here+@SpeakerProperty@) rather than writing @Property Speaker@: GHC rejects the+latter without @UndecidableInstances@, as a type family application is no+smaller than the instance's own left-hand side.++The elements of a container are otherwise neither described nor checked, see+'Surveyable'. Vacuously 'True' for an empty container.+-}+everyHolds :: (Foldable f, Surveyable a) => f a -> Property a -> Bool+everyHolds xs p = all (`propertyHolds` p) xs++{- | Describe an element's property as a property of every element of a+container, to be used from 'describeProperties' alongside 'everyHolds'.+Returns 'Nothing' when the element has no description for the property.+See 'everyHolds' for the pattern.+-}+describeEvery ::+  (Surveyable a) =>+  {- | The label for the elements. It is joined to the element's own description with+  a colon, so @\"Every speaker\"@ turns \"The speaker's last name must not be+  empty.\" into \"Every speaker: The speaker's last name must not be empty.\".+  -}+  Text ->+  Proxy a ->+  Property a ->+  Maybe Text+describeEvery label p prop = (\d -> label <> ": " <> d) <$> describeProperties p prop++{- | The properties of one field type @x@, wrapped in a newtype so that a+sum over fields ('NS') can carry them. A data type rather than a type family+application, which a partially applied 'Property' could not be.+-}+newtype PropertyOf x = PropertyOf (Property x)++deriving instance (Eq (Property x)) => Eq (PropertyOf x)++deriving instance (Show (Property x)) => Show (PropertyOf x)++{- | The properties of a type that follow from its structure: the properties of+every field of every constructor, each a property of the field's own type.++A t'Structural' value picks a constructor of @a@, then one of that+constructor's fields, then one of the properties of the field's type. It is the+default 'Property' of 'Surveyable', where its use and requirements are+explained. It is a newtype, not a type family, so that naming it as a+'Property' needs no @UndecidableInstances@ in the user's module.++Its 'Universe' lists every field property of every constructor, in+constructor and then field order. A constructor without fields, and a field+whose own 'Property' is empty, contribute nothing.+-}+newtype Structural a = Structural (NS (NS PropertyOf) (Code a))++deriving instance (Eq (NS (NS PropertyOf) (Code a))) => Eq (Structural a)++deriving instance (Show (NS (NS PropertyOf) (Code a))) => Show (Structural a)++instance (All2 Surveyable (Code a)) => Universe (Structural a) where+  universe = Structural <$> universeConstructors++universeConstructors :: forall xss. (All2 Surveyable xss) => [NS (NS PropertyOf) xss]+universeConstructors = case sList :: SList xss of+  SNil -> []+  SCons -> (Z <$> universeFields) ++ (S <$> universeConstructors)++universeFields :: forall xs. (All Surveyable xs) => [NS PropertyOf xs]+universeFields = case sList :: SList xs of+  SNil -> []+  SCons -> (Z . PropertyOf <$> universe) ++ (S <$> universeFields)++{- | Check a structural property of a value.++A property of constructor @c@, field @f@ holds vacuously (as in 'everyHolds')+for a value built with a different constructor than @c@. For a value built+with @c@, it holds exactly when the field's own 'propertyHolds' does.+-}+structuralHolds :: (Generic a, All2 Surveyable (Code a)) => a -> Structural a -> Bool+structuralHolds x (Structural p) = holdsConstructor (unSOP (from x)) p++holdsConstructor :: (All2 Surveyable xss) => NS (NP I) xss -> NS (NS PropertyOf) xss -> Bool+holdsConstructor (Z vs) (Z ps) = holdsField vs ps+holdsConstructor (S vs) (S ps) = holdsConstructor vs ps+holdsConstructor _ _ = True++holdsField :: (All Surveyable xs) => NP I xs -> NS PropertyOf xs -> Bool+holdsField (I v :* _) (Z (PropertyOf p)) = propertyHolds v p+holdsField (_ :* vs) (S ps) = holdsField vs ps+holdsField Nil p = case p of {}++{- | Describe a structural property: the field's own 'describeProperties',+prefixed with where it lives.++* A record field is named @Field lastName: …@, a positional one by its+  position and constructor, @Field 2 of Pair: …@.+* For a type with several constructors, the constructor is named as well:+  @Constructor FruitApple, field kernels: …@ or+  @Constructor FruitBanana, field 1: …@.++'Nothing' exactly when the field's own description of the property is.+-}+describeStructural :: forall a. (HasDatatypeInfo a, All2 Surveyable (Code a)) => Proxy a -> Structural a -> Maybe Text+describeStructural _ (Structural p) = describeConstructor multi (constructorInfo (datatypeInfo (Proxy @a))) p+  where+    multi = lengthSList (Proxy @(Code a)) > 1++describeConstructor :: (All2 Surveyable xss) => Bool -> NP ConstructorInfo xss -> NS (NS PropertyOf) xss -> Maybe Text+describeConstructor multi (c :* _) (Z ps) = describeField prefix 0 ps+  where+    conName = T.pack (constructorName c)+    prefix i = case fieldNameAt i c of+      Just name+        | multi -> "Constructor " <> conName <> ", field " <> name+        | otherwise -> "Field " <> name+      Nothing+        | multi -> "Constructor " <> conName <> ", field " <> T.pack (show (i + 1))+        | otherwise -> "Field " <> T.pack (show (i + 1)) <> " of " <> conName+describeConstructor multi (_ :* cs) (S ps) = describeConstructor multi cs ps+describeConstructor _ Nil p = case p of {}++describeField :: (All Surveyable xs) => (Int -> Text) -> Int -> NS PropertyOf xs -> Maybe Text+describeField prefix i (Z p) = (\d -> prefix i <> ": " <> d) <$> describeOne p+describeField prefix i (S ps) = describeField prefix (i + 1) ps++describeOne :: forall x. (Surveyable x) => PropertyOf x -> Maybe Text+describeOne (PropertyOf p) = describeProperties (Proxy @x) p++-- | The name of the record field at a position, 'Nothing' for a positional constructor.+fieldNameAt ::+  -- | The position of the field, counting from 0.+  Int ->+  ConstructorInfo xs ->+  Maybe Text+fieldNameAt i (Record _ fields) = case drop i (hcollapse (hmap (\(FieldInfo name) -> K (T.pack name)) fields)) of+  name : _ -> Just name+  [] -> Nothing+fieldNameAt _ _ = Nothing++{- | A class for those property types that have default 'propertyHolds' and+'describeProperties' implementations.++Exported only because GHC names it in the error for a custom 'Property' whose+instance leaves 'propertyHolds' or 'describeProperties' out, see 'Surveyable'.+Do not write instances of this class.+-}+class PropertyDefault p a where+  -- | The default 'propertyHolds'.+  defaultHolds :: a -> p -> Bool++  -- | The default 'describeProperties'.+  defaultDescribe :: Proxy a -> p -> Maybe Text++-- | No properties: nothing to check, nothing to describe.+instance PropertyDefault Void a where+  defaultHolds _ = absurd+  defaultDescribe _ = absurd++-- | The properties of the fields, see t'Structural'.+instance (Generic a, HasDatatypeInfo a, All2 Surveyable (Code a)) => PropertyDefault (Structural a) a where+  defaultHolds = structuralHolds+  defaultDescribe = describeStructural++{- | Render a type for the model: its description, its properties and its+example values, if any.++The text goes to the model next to the JSON schema;+<https://hackage.haskell.org/package/shroom/docs/Control-Monad-Prompt-Effect.html#v:runPrompt runPrompt>+(from the @shroom@ package) sends it as the prompt text. Field descriptions are annotated+with their JSON types, see 'annotateFieldTypes'.++After the examples comes a section with the 'describeType' of every type the+requested type reaches through 'referencedTypes', see 'Describable'. Each type+is listed once, told apart by its 'TypeRep' (so @Choice Fuel@ and @Choice Phase@+are two types), breadth first and in the order 'referencedTypes' lists them,+and never the requested type itself, also when it is recursive. The section is+absent when nothing is reachable.+-}+description :: (Surveyable a, ToSchema a) => Proxy a -> Text+description p =+  T.unlines $+    [ ""+    , "Produce a value of the following type:"+    , annotateFieldTypes (toJSON (toSchema p)) (describeType p)+    ]+      <> propSection+      <> examplesSection+      <> reachableSection+  where+    reachable = reachableTypes p+    reachableSection+      | null reachable = []+      | otherwise =+          "The types above refer to the following types:"+            : concatMap (\(Described q) -> ["", T.pack (show (typeRep q)) <> ":", describeType q]) reachable+    propDescs = mapMaybe (describeProperties p) universe+    propSection+      | null propDescs = []+      | otherwise =+          "The following properties MUST hold in your response:"+            : fmap ("- " <>) propDescs+    examplesSection+      | S.null (examples p) = []+      | otherwise =+          "Example valid JSON responses:"+            : (toStrict . decodeUtf8 . encode <$> S.toList (examples p))++{- | Annotate each field line of a type description with its JSON type.++For each line @- fieldName: doc@ in the description, look up @fieldName@ in the+@properties@ map of the schema and insert the JSON type in parentheses:+@- fieldName (string): doc@. Lines that do not match the pattern or lack a+known type are left unchanged.+-}+annotateFieldTypes ::+  -- | The OpenAPI schema of the type.+  Value ->+  -- | The description of the type, as 'describeType' gives it.+  Text ->+  Text+annotateFieldTypes schema = T.unlines . fmap annotateLine . T.lines+  where+    -- Extract {"fieldName": {"type": "..."}} from the schema+    schemaProps :: KM.KeyMap Value+    schemaProps = case schema of+      Object km -> case KM.lookup "properties" km of+        Just (Object props) -> props+        _ -> KM.empty+      _ -> KM.empty++    fieldType :: Text -> Text+    fieldType fieldName = case KM.lookup (Key.fromText fieldName) schemaProps of+      Just (Object fp) -> case KM.lookup "type" fp of+        Just (String t) -> t+        _ -> typeFromRef fp+      _ -> ""++    -- For $ref fields (nested objects), there's no "type" key but we can say "object"+    typeFromRef :: KM.KeyMap Value -> Text+    typeFromRef fp+      | KM.member "$ref" fp = "object"+      | otherwise = ""++    annotateLine :: Text -> Text+    annotateLine line = case T.stripPrefix "- " line of+      Nothing -> line+      Just rest ->+        let (fieldName, afterColon) = T.breakOn ":" rest+            trimmed = T.strip fieldName+            t = fieldType trimmed+         in if T.null t || T.null afterColon+              then line+              else "- " <> trimmed <> " (" <> t <> ")" <> afterColon
+ src/Data/Shroom/Class/TH.hs view
@@ -0,0 +1,334 @@+{-# LANGUAGE TemplateHaskell #-}++{- |+Module      : Data.Shroom.Class.TH+Description : Derive Describable instances from Haddock comments with Template Haskell.++'deriveDescribable' generates a complete 'Describable' instance for a type from its+Haddock comments and its fields. 'deriveDescribableExp' generates the+'describeType' body alone, for a hand-written instance.++The type's own module must be compiled with the @-haddock@ GHC flag, because the+splices read the Haddock comments from the compiler. See 'deriveDescribable'.+-}+module Data.Shroom.Class.TH (deriveDescribable, deriveDescribableExp) where++-- base+import Data.Kind qualified as Kind+import Data.List (nub)+import Data.Typeable (Typeable)++-- template-haskell+import Language.Haskell.TH++-- text+import Data.Text (pack)++-- shroom+import Data.Shroom.Class (Describable (describeType, referencedTypes), reach)++{- | Generate a complete 'Describable' instance for a type: 'describeType' from+the type's Haddock comment, 'referencedTypes' from its fields. Use it when the+description needs no customising:++@+-- | A user with a name and an email address.+data User = User { userName :: Text, userEmail :: Text }++\$(deriveDescribable ''User)+@++This generates:++@+instance Describable User where+  describeType = \\_ -> pack "A user with a name and an email address.\\n..."+  referencedTypes _ = reach \@Text <> (reach \@Text <> mempty)+@++'referencedTypes' is the concatenation, in declaration order, of @'reach' \@t@ for+the type @t@ of every field of every constructor, record and positional alike. So+the types of the fields reach the model through 'Data.Shroom.Class.description':+each is described once, in a section after the examples, however often and however+deeply it is used.++__Every field type must have a 'Describable' instance__, from an earlier splice or+the same one; a field type without one is a compile-time error (\"No instance for+'Describable' …\"). Splice order therefore matters. Mutually recursive types+are derived in a single splice, @\$(concat \<$\> traverse deriveDescribable [''A, ''B])@; a+self-recursive type needs nothing special.++A parameterised type derives too, with one @'Describable' a@ constraint for each type+variable of kind t'Data.Kind.Type':++@+-- | One of two alternatives.+data Choice a = Pick a | Skip++\$(deriveDescribable ''Choice)+@++generates @instance ('Describable' a) => 'Describable' (Choice a)@, where a field of type+@a@ contributes @'reach' \@a@, so that @Choice Fuel@ makes @Fuel@ reachable.++A type variable of any other kind (a t'GHC.TypeLits.Symbol' or t'GHC.TypeLits.Nat' unit, a dimension, or an+unannotated phantom parameter, which GHC2024 makes poly-kinded) can never be the+type of a field, so it needs no 'Describable'. It is annotated with its kind in the+instance head and needs only 'Typeable', as does each kind variable its kind+mentions:++@+-- | An amount in some unit.+newtype Measure (unit :: Symbol) = Measure Double++-- | A value tagged by a phantom parameter.+newtype Tagged a = Tagged Double++\$(deriveDescribable ''Measure)+\$(deriveDescribable ''Tagged)+@++generates @instance 'Typeable' unit => 'Describable' (Measure (unit :: Symbol))@ and+@instance ('Typeable' k, 'Typeable' a) => 'Describable' (Tagged (a :: k))@. The+generated code uses type applications and the instance head's type+variables, so the module needs @TypeApplications@ and @ScopedTypeVariables@ (both+in @GHC2021@ and @GHC2024@).++To override 'describeType' manually, write the 'Describable' instance by hand.+You can use 'deriveDescribableExp' for the body, and modify it as needed, but+then also write 'referencedTypes'.++@+instance Describable MyType where+  describeType = \$(deriveDescribableExp ''MyType)+  referencedTypes _ = reach \@Inner+@++The module that declares the type must be compiled with the @-haddock@ GHC flag,+which GHC does not set by default. Add @ghc-options: -haddock@ to the+@.cabal@ stanza of the library, executable or test suite that holds the type. Without it,+GHC discards the comments and the splice fails with the error below.++__Error__: A compile-time error is raised if no Haddock documentation is found.+-}+deriveDescribable ::+  -- | The type to describe, as a quoted name such as @''User@.+  Name ->+  Q [Dec]+deriveDescribable name = do+  body <- deriveDescribableExp name+  (typeVars, fieldTypes) <- getTypeShape name+  let describeTypeClause = ValD (VarP 'describeType) (NormalB body) []+      -- referencedTypes = \_ -> reach @T1 <> (reach @T2 <> (... <> mempty)),+      -- with no list literal, which OverloadedLists would make ambiguous+      referencedTypesBody =+        LamE+          [WildP]+          ( foldr+              (\fieldType rest -> InfixE (Just (AppTypeE (VarE 'reach) fieldType)) (VarE '(<>)) (Just rest))+              (VarE 'mempty)+              fieldTypes+          )+      referencedTypesClause = ValD (VarP 'referencedTypes) (NormalB referencedTypesBody) []+      -- A Type-kinded variable appears bare in the head and needs Describable. Any other variable+      -- is annotated with its kind in the head and needs only Typeable, as do the kind variables+      -- of those kinds (a poly-kinded `a :: k` needs `Typeable k` as well to be Typeable itself).+      headArg (v, Nothing) = VarT v+      headArg (v, Just kind) = SigT (VarT v) kind+      describableVars = [v | (v, Nothing) <- typeVars]+      kindVars =+        nub+          [ kv+          | (_, Just kind) <- typeVars+          , kv <- freeKindVars kind+          , kv `notElem` describableVars+          ]+      instanceHead = foldl AppT (ConT name) (headArg <$> typeVars)+      context =+        concat+          [ case mkind of+              Nothing -> [AppT (ConT ''Describable) (VarT v)]+              Just _ -> [AppT (ConT ''Typeable) (VarT v)]+          | (v, mkind) <- typeVars+          ]+          <> [AppT (ConT ''Typeable) (VarT kv) | kv <- kindVars]+  pure+    [ InstanceD+        Nothing+        context+        (AppT (ConT ''Describable) instanceHead)+        [describeTypeClause, referencedTypesClause]+    ]++-- | The type variables a kind mentions, each once, in order of appearance.+freeKindVars :: Kind -> [Name]+freeKindVars = nub . go+  where+    go (VarT v) = [v]+    go (AppT a b) = go a <> go b+    go (SigT t k) = go t <> go k+    go (ForallT _ _ t) = go t+    go (InfixT a _ b) = go a <> go b+    go _ = []++-- | The type variables and constructors of a data or newtype declaration; empty for any other declaration.+reifyCons :: Name -> Q ([TyVarBndr BndrVis], [Con])+reifyCons name = do+  info <- reify name+  pure $ case info of+    TyConI (DataD _ _ tvs _ cs _) -> (tvs, cs)+    TyConI (NewtypeD _ _ tvs _ c _) -> (tvs, [c])+    _ -> ([], [])++-- | The fields of a constructor in order: 'Just' the name for a record field, 'Nothing' for a positional one.+conFields :: Con -> [(Maybe Name, Type)]+conFields (NormalC _ bts) = [(Nothing, t) | (_, t) <- bts]+conFields (RecC _ vbts) = [(Just n, t) | (n, _, t) <- vbts]+conFields (InfixC (_, t1) _ (_, t2)) = [(Nothing, t1), (Nothing, t2)]+conFields (ForallC _ _ c) = conFields c+conFields (GadtC _ bts _) = [(Nothing, t) | (_, t) <- bts]+conFields (RecGadtC _ vbts _) = [(Just n, t) | (n, _, t) <- vbts]++{- | The type variables of a type, each with its kind unless that is @Type@ ('Nothing'),+and the types of all fields of all its constructors, in declaration order.+-}+getTypeShape :: Name -> Q ([(Name, Maybe Kind)], [Type])+getTypeShape name = do+  (binders, cons) <- reifyCons name+  pure (binderKind <$> binders, concatMap (fmap snd . conFields) cons)+  where+    binderKind (PlainTV v _) = (v, Nothing)+    binderKind (KindedTV v _ k)+      | isTypeKind k = (v, Nothing)+      | otherwise = (v, Just k)++    isTypeKind StarT = True+    isTypeKind (ConT k) = k == ''Kind.Type+    isTypeKind _ = False++{- | Produce the 'describeType' method body for a type, using its Haddock+documentation comment.  Use this inside a manually written+'Describable' instance:++@+instance Describable MyType where+  describeType = \$(deriveDescribableExp ''MyType)+  referencedTypes _ = reach \@Inner+@++__This returns the 'describeType' body only.__ It does not collect the referenced types:+a hand-written instance must write 'referencedTypes' itself, or its field types are not+described to the model. For a record, write the @'reach' \@t@ of each of its field types,+as 'deriveDescribable' generates. A transparent newtype wrapper forwards to the wrapped type's+'referencedTypes' instead, see 'Describable'.++For a type with several constructors, each constructor is listed as+@- Constructor: doc@ (by name alone if undocumented), followed by its documented+fields indented beneath it.  For a single-constructor type, the constructor's own+doc, if any, is a line of its own right after the type's doc, and the documented+fields are listed directly.  A documented record field is listed as+@- fieldName: doc@, a documented positional field as @- field N: doc@ with @N@ counting+from 1; an undocumented field adds nothing.++Which Haddock layout documents what, for a constructor with positional fields (GHC's+rule for H98 constructors):++@+data Shape+  = -- | Documents the constructor Circle.+    Circle Double+  | Square Double -- ^ Documents the constructor Square, not its argument.+  | -- | Documents the constructor Rect.+    Rect+      Double+      -- ^ Documents the first argument of Rect.+      Double+      -- ^ Documents the second argument of Rect.+@++A one-line trailing comment after the constructor and all its arguments, as on+@Square@, documents the constructor (it renders as @- Square: doc@). A positional+argument's doc is collected only when the constructor has a leading Haddock comment+or each argument stands on a line of its own with its own trailing comment, as on+@Rect@, which renders its two arguments as @- field 1: …@ and @- field 2: …@. An+argument documented in any other way is not collected, because GHC does not attach+the comment to the argument. A leading comment on each argument (a Haddock comment on+the line above the argument's type) is collected the same way; this is the layout+that fourmolu rewrites the trailing comments into, and it renders unchanged.++Prefer 'deriveDescribable' for the common case where a full instance is needed.+-}+deriveDescribableExp ::+  -- | The type to describe, as a quoted name such as @''MyType@.+  Name ->+  Q Exp+deriveDescribableExp name = do+  mdoc <- getDoc (DeclDoc name)+  doc <- case mdoc of+    Nothing ->+      fail $+        "deriveDescribable: No Haddock documentation found for '"+          <> nameBase name+          <> "'.\n"+          <> "Make sure to:\n"+          <> "  1. Add a Haddock comment above the type declaration (-- | ...).\n"+          <> "  2. Compile with the -haddock GHC flag (e.g. add 'ghc-options: -haddock' to your .cabal file).\n"+          <> "  3. Separate the type declaration from this splice with $(pure []) if they are in the same module."+    Just d -> pure d+  constructorDocs <- getConstructorDocs name+  -- Build: \_ -> pack "<doc>"+  -- Haddock docs have a leading space, no trailing newline, and escape "/" as "\/"+  let unescapeHaddock [] = []+      unescapeHaddock ('\\' : '/' : rest) = '/' : unescapeHaddock rest+      unescapeHaddock (c : rest) = c : unescapeHaddock rest+      normalizeDoc = (++ "\n") . dropWhile (== ' ') . unescapeHaddock+      renderField indent (fn, fd) = indent <> "- " <> fn <> ": " <> normalizeDoc fd+      -- A sum lists every constructor (by name alone if undocumented),+      -- with its documented fields indented beneath it.+      renderConstructor (cn, mcd, fields) =+        "- "+          <> cn+          <> maybe "\n" ((": " <>) . normalizeDoc) mcd+          <> concatMap (renderField "  ") fields+      -- A single constructor is the type itself, so its own doc (if any) is a line of its own,+      -- and its fields are listed directly.+      constructorLines = case constructorDocs of+        [(_, mcd, fields)] -> maybe "" normalizeDoc mcd <> concatMap (renderField "") fields+        cons -> concatMap renderConstructor cons+      fullDoc = normalizeDoc doc <> constructorLines+      docLit = litE (stringL fullDoc)+  [|\_ -> pack $docLit|]++{- | Collect, for each constructor of a type, its name, its Haddock (if any), and+the (label, doc) pairs of its documented fields: a record field is labelled by its+name, a positional field (read with @'ArgDoc'@) by @field N@ with @N@ counting from 1.+Undocumented fields are left out.++A one-line trailing comment after a constructor and all its arguments documents the+constructor, not its last argument. GHC attaches argument docs only if the constructor+has a leading Haddock comment, or each argument stands on a line of its own with its+own trailing comment.+-}+getConstructorDocs :: Name -> Q [(String, Maybe String, [(String, String)])]+getConstructorDocs name = do+  (_, cons) <- reifyCons name+  mapM collect cons+  where+    collect con = do+      let cn = conName con+      cdoc <- getDoc (DeclDoc cn)+      recordPairs <- mapM (\fn -> (nameBase fn,) <$> getDoc (DeclDoc fn)) [n | (Just n, _) <- conFields con]+      positionalPairs <-+        mapM+          (\i -> ("field " <> show (i + 1),) <$> getDoc (ArgDoc cn i))+          [0 .. length [() | (Nothing, _) <- conFields con] - 1]+      pure (nameBase cn, cdoc, [(fn, d) | (fn, Just d) <- recordPairs <> positionalPairs])++    conName (NormalC n _) = n+    conName (RecC n _) = n+    conName (InfixC _ n _) = n+    conName (ForallC _ _ c) = conName c+    conName (GadtC (n : _) _ _) = n+    conName (GadtC [] _ _) = mkName ""+    conName (RecGadtC (n : _) _ _) = n+    conName (RecGadtC [] _ _) = mkName ""
+ test/Main.hs view
@@ -0,0 +1,734 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE TemplateHaskell #-}++module Main (main) where++-- base+import Data.Int (Int64)+import Data.List.NonEmpty (NonEmpty)+import Data.Maybe (fromMaybe)+import Data.Proxy (Proxy (..))+import Data.Typeable (Typeable, typeRep)+import Data.Void (Void)+import GHC.Generics (Generic, Generically (..))+import GHC.TypeLits (Symbol)++-- containers+import Data.Set qualified as S++-- text+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Encoding (encodeUtf8)++-- aeson+import Data.Aeson (ToJSON)++-- openapi3+import Data.OpenApi (ToSchema)++-- universe-base+import Data.Universe.Class (Universe, universe)++-- generics-sop+import Generics.SOP qualified as SOP++-- tasty+import Test.Tasty (defaultMain, testGroup)++-- tasty-golden+import Test.Tasty.Golden (goldenVsString)++-- tasty-hunit+import Test.Tasty.HUnit (assertBool, testCase, (@?=))++-- shroom-class++import Data.Shroom.Class+import Data.Shroom.Class.TH (deriveDescribable)++-- | A person with a name and an age.+data Person = Person+  { personName :: Text+  -- ^ The person's full name.+  , personAge :: Int+  -- ^ The person's age in years.+  }+  deriving (Eq, Ord, Show, Generic, ToJSON, ToSchema)+  deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)++-- | A contact address that is an email address.+newtype Email = Email+  { emailAddress :: Text+  -- ^ The email address, which must contain an at sign.+  }+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A property of an 'Email' that should hold.+data EmailProperty = EmailNotEmpty | EmailHasAtSign+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++-- | How a message should be delivered.+data Delivery+  = -- | Send the message by post.+    Post+  | -- | Send the message by email.+    ByEmail+  | -- | Do not send the message at all.+    Hold+  deriving (Eq, Ord, Show, Generic, ToJSON, ToSchema)+  deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)++-- | A piece of fruit.+data Fruit+  = -- | An apple.+    FruitApple+      { appleVariety :: Text+      -- ^ The variety of the apple.+      , appleSweetness :: Int+      -- ^ How sweet the apple is, from 1 to 10.+      }+  | -- | A banana, with its length in centimetres.+    FruitBanana Int+  | -- | A pear.+    FruitPear+      { pearRipe :: Bool+      -- ^ Whether the pear is ripe.+      }+  | FruitLemon+  deriving (Eq, Ord, Show, Generic, ToJSON, ToSchema)+  deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)++$(deriveDescribable ''Person)++instance Surveyable Person++$(deriveDescribable ''Email)++instance Surveyable Email where+  type Property Email = EmailProperty+  propertyHolds email EmailNotEmpty = not (T.null (emailAddress email))+  propertyHolds email EmailHasAtSign = T.elem '@' (emailAddress email)+  describeProperties _ EmailNotEmpty = Just "The email address is not empty."+  describeProperties _ EmailHasAtSign = Just "The email address must contain an '@' character."+  examples _ = S.fromList [Email "ada@example.org", Email "alan@example.com"]++$(deriveDescribable ''Delivery)++instance Surveyable Delivery++$(deriveDescribable ''Fruit)++instance Surveyable Fruit++-- | A name.+newtype Name = Name Text+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A property of a 'Name' that should hold; the second one is informal and undescribed.+data NameProperty = NameNotEmpty | NameIsReal+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++instance Describable Name where+  describeType _ = "A name."++instance Surveyable Name where+  type Property Name = NameProperty+  propertyHolds (Name n) NameNotEmpty = not (T.null n)+  propertyHolds _ NameIsReal = True+  describeProperties _ NameNotEmpty = Just "The name must not be empty."+  describeProperties _ NameIsReal = Nothing++-- | A hand-written product, surveyed structurally by the default.+data Contact = Contact+  { contactName :: Name+  , contactEmail :: Email+  }+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable Contact where+  describeType _ = "A contact."++instance Surveyable Contact++-- | A hand-written product with positional fields, surveyed with the structural property written out by hand.+data Pair = Pair Name Email+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable Pair where+  describeType _ = "A pair."++instance Surveyable Pair where+  type Property Pair = Structural Pair+  propertyHolds = structuralHolds+  describeProperties = describeStructural++-- | A hand-written sum: a record, a positional constructor and one without fields.+data Parcel+  = Letter+      { letterTo :: Email+      , letterFrom :: Name+      }+  | Crate Name+  | Blank+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable Parcel where+  describeType _ = "A parcel."++instance Surveyable Parcel where+  type Property Parcel = Structural Parcel+  propertyHolds = structuralHolds+  describeProperties = describeStructural++-- | A registration, which combines a property of its own with those of its fields.+data Registration = Registration+  { registrationName :: Name+  , registrationEmail :: Email+  }+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++-- | A property of a whole 'Registration' that should hold.+data RegistrationProperty = RegistrationEmailMentionsName+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++instance Describable Registration where+  describeType _ = "A registration."++instance Surveyable Registration where+  type Property Registration = Either RegistrationProperty (Structural Registration)+  propertyHolds (Registration (Name n) (Email e)) (Left RegistrationEmailMentionsName) = T.toLower n `T.isInfixOf` T.toLower e+  propertyHolds r (Right p) = structuralHolds r p+  describeProperties _ (Left RegistrationEmailMentionsName) = Just "The email address must contain the registrant's name."+  describeProperties px (Right p) = describeStructural px p++-- * Reachable types++-- | A street: the leaf of the reachable-types tree.+newtype Street = Street {streetName :: Text}+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A record nesting a record.+data Address = Address {addressStreet :: Street, addressCity :: Text}+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | An enum.+data Mood = Happy | Grumpy+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A sum whose constructors refer to types that are also reachable another way.+data Shape = Circle Street | Square Address+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A recursive type.+data Tree = Leaf Int | Node [Tree]+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A record that reaches all of the above, some of them twice, and base types.+data Household = Household+  { householdAddress :: Address+  , householdShapes :: [Shape]+  , householdMood :: Maybe Mood+  , householdTree :: Tree+  , householdNote :: Text+  , householdSize :: Int+  }+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++instance Describable Street where describeType _ = "A street."++instance Surveyable Street where type Property Street = Void++instance Describable Address where+  describeType _ = "An address."+  referencedTypes _ = reach @Street <> reach @Text++instance Surveyable Address where+  type Property Address = Void+  examples _ = S.singleton (Address (Street "Main Street") "Hull")++-- No 'referencedTypes': a hand-written instance contributes no reachable types unless it says so.+instance Describable Mood where describeType _ = "A mood."++instance Surveyable Mood where type Property Mood = Void++instance Describable Shape where+  describeType _ = "A shape."+  referencedTypes _ = reach @Street <> reach @Address++instance Surveyable Shape where type Property Shape = Void++instance Describable Tree where+  describeType _ = "A tree."+  referencedTypes _ = reach @Int <> reach @[Tree]++instance Surveyable Tree where type Property Tree = Void++instance Describable Household where+  describeType _ = "A household."+  referencedTypes _ =+    reach @Address <> reach @[Shape] <> reach @(Maybe Mood) <> reach @Tree <> reach @Text <> reach @Int++instance Surveyable Household where type Property Household = Void++-- * Derived reachable types++-- | A colour of paint.+data Colour+  = -- | Like a post box.+    Red+  | -- | Like a lawn.+    Green+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | Either a value was picked, or none was.+data Choice a+  = -- | The picked value.+    Pick a+  | -- | Nothing was picked.+    Decline+  deriving stock (Eq, Ord, Show, Generic)++-- The generic defaults need the context of the parameter, which only a standalone clause can state.+deriving anyclass instance (ToJSON a) => ToJSON (Choice a)++deriving anyclass instance (ToSchema a) => ToSchema (Choice a)++-- | The size of a tile.+data Dimensions = Dimensions+  { dimWidth :: Int+  -- ^ The width in millimetres.+  , dimHeight :: Int+  -- ^ The height in millimetres.+  }+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A text printed on a tile.+newtype Label = Label+  { labelText :: Text+  -- ^ The words that are printed.+  }+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | How a tile is cut.+data Cut+  = -- | Straight edges, to the given dimensions.+    Straight Dimensions+  | -- | A round tile of the given diameter in millimetres.+    Curved Int+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A ceramic tile.+data Tile = Tile+  { tileCut :: Cut+  -- ^ How the tile is cut.+  , tileSize :: Dimensions+  -- ^ The size of the tile when laid.+  , tileLabels :: [Label]+  -- ^ The labels printed on the tile.+  , tileColour :: Choice Colour+  -- ^ The chosen colour, if any.+  , tileNote :: Text+  -- ^ A note for the tiler.+  }+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A folder, holding files.+data Folder = Folder+  { folderName :: Text+  -- ^ The name of the folder.+  , folderFiles :: [File]+  -- ^ What is in the folder.+  }+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A file, which is either some text or another folder.+data File+  = -- | Some text.+    Plain Text+  | -- | A folder in place of a file.+    Directory Folder+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | An outline: a title with sub-outlines, a recursive type.+data Outline = Outline+  { outlineTitle :: Text+  -- ^ The title of the outline.+  , outlineChildren :: [Outline]+  -- ^ The sub-outlines.+  }+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A span between points, a positional sum with a doc on each argument.+data Span+  = -- | Between two points.+    Between+      -- | The first point.+      Int+      -- | The second point.+      Int+  | -- | From a point on, with one argument documented and one not.+    Starting+      -- | The point to start at.+      Int+      Text+  | Whole+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A bound, in millimetres.+newtype Bounds+  = -- | The largest allowed value.+    Bounds Int+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A point, a single positional constructor with a doc on each argument.+data Point+  = -- | A point in the plane.+    Point+      -- | The horizontal position.+      Int+      -- | The vertical position.+      Int+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- The two layouts below are the ones fourmolu would rewrite into the leading form above, so it+-- is told to leave them alone.++{- FOURMOLU_DISABLE -}++-- | How a purchase is made, a sum in the one-line form.+data Purchase+  = ByFuel Int -- ^ Bought by the litre.+  | ByVoucher Text+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | A couple, each argument on a line of its own with a trailing comment.+data Couple = Couple+  Int+  -- ^ The left one.+  Int+  -- ^ The right one.+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++{- FOURMOLU_ENABLE -}++-- | A wrapper whose constructor and field have no docs.+newtype Wrapped = Wrapped Int+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, ToSchema)++-- | An amount in some unit, a phantom parameter of kind Symbol.+newtype Measure (unit :: Symbol) = Measure+  { measureAmount :: Double+  -- ^ The amount, in the unit.+  }+  deriving stock (Eq, Ord, Show, Generic)++deriving anyclass instance ToJSON (Measure unit)++deriving anyclass instance (Typeable unit) => ToSchema (Measure unit)++-- | A value tagged by an unannotated phantom parameter, which is poly-kinded under GHC2024.+newtype Tagged a = Tagged Double+  deriving stock (Eq, Ord, Show, Generic)++deriving anyclass instance ToJSON (Tagged a)++deriving anyclass instance (Typeable k, Typeable (a :: k)) => ToSchema (Tagged a)++-- The field types are derived before the types that have them as fields.+$(deriveDescribable ''Colour)++$(deriveDescribable ''Choice)++$(deriveDescribable ''Dimensions)++$(deriveDescribable ''Label)++$(deriveDescribable ''Cut)++$(deriveDescribable ''Tile)++instance Surveyable Tile where type Property Tile = Void++-- Mutually recursive types are derived by one splice.+$(concat <$> traverse deriveDescribable [''Folder, ''File])++instance Surveyable Folder where type Property Folder = Void++instance Surveyable File where type Property File = Void++-- A self-recursive type needs nothing special.+$(deriveDescribable ''Outline)++instance Surveyable Outline where type Property Outline = Void++-- The positional types, whose fields are all base types.+$(deriveDescribable ''Span)++instance Surveyable Span where type Property Span = Void++$(deriveDescribable ''Purchase)++$(deriveDescribable ''Bounds)++$(deriveDescribable ''Couple)++$(deriveDescribable ''Point)++instance Surveyable Point where type Property Point = Void++$(deriveDescribable ''Wrapped)++-- A phantom parameter that is not of kind Type needs no Describable, only Typeable.+$(deriveDescribable ''Measure)++instance (Typeable unit) => Surveyable (Measure unit) where type Property (Measure unit) = Void++$(deriveDescribable ''Tagged)++instance (Typeable k, Typeable (a :: k)) => Surveyable (Tagged a) where type Property (Tagged a) = Void++-- | The lines of a description from the reachable-types section on, empty if it has none.+reachableLines :: Text -> [Text]+reachableLines = dropWhile (/= "The types above refer to the following types:") . T.lines++-- | The name 'description' gives a reachable type in its section header.+typeName :: Described -> String+typeName (Described q) = show (typeRep q)++{- | Every structural property of a type, with its description, and for each+given value whether each property holds.+-}+structuralReport ::+  forall a.+  (Show a, Show (Structural a), SOP.Generic a, SOP.HasDatatypeInfo a, SOP.All2 Surveyable (SOP.Code a)) =>+  Proxy a ->+  [a] ->+  Text+structuralReport p values =+  T.unlines $+    ["universe:"]+      <> [ "  " <> T.pack (show prop) <> " | " <> fromMaybe "(undescribed)" (describeStructural p prop)+         | prop <- universe @(Structural a)+         ]+      <> concat+        [ ("value " <> T.pack (show v) <> ":")+            : [ "  " <> T.pack (show prop) <> ": " <> if structuralHolds v prop then "holds" else "violated"+              | prop <- universe @(Structural a)+              ]+        | v <- values+        ]++main :: IO ()+main =+  defaultMain $+    testGroup+      "description"+      [ golden "Person" $ description (Proxy @Person)+      , golden "Email" $ description (Proxy @Email)+      , golden "Delivery" $ description (Proxy @Delivery)+      , golden "Fruit" $ description (Proxy @Fruit)+      , golden "Tile" $ description (Proxy @Tile)+      , golden "StructuralContact" $+          structuralReport+            (Proxy @Contact)+            [Contact (Name "Ada") (Email "ada@example.org"), Contact (Name "") (Email "ada@example.org"), Contact (Name "Ada") (Email "")]+      , golden "StructuralPair" $+          structuralReport+            (Proxy @Pair)+            [Pair (Name "") (Email "no-at-sign"), Pair (Name "Ada") (Email "ada@example.org")]+      , golden "StructuralParcel" $+          structuralReport+            (Proxy @Parcel)+            [Letter (Email "") (Name "Ada"), Crate (Name ""), Crate (Name "Ada"), Blank]+      , testGroup+          "base types"+          [ contains "Text" (description (Proxy @Text)) "A piece of text."+          , contains "[Int]" (description (Proxy @[Int])) "A list of values of the following type: A whole number."+          , contains "NonEmpty Bool" (description (Proxy @(NonEmpty Bool))) "A truth value: true or false."+          , contains "Set Bool" (description (Proxy @(S.Set Bool))) "A truth value: true or false."+          , contains "Int64" (description (Proxy @Int64)) "A whole number."+          , contains "Word" (description (Proxy @Word)) "A non-negative whole number."+          , contains "Maybe Text" (description (Proxy @(Maybe Text))) "A piece of text."+          , contains "[Maybe Int]" (describeType (Proxy @[Maybe Int])) "A whole number."+          ]+      , testGroup+          "reachable types"+          [ testCase "each reachable documented type is listed once, breadth first, without base types, containers or the requested type" $+              reachableLines (description (Proxy @Household))+                @?= [ "The types above refer to the following types:"+                    , ""+                    , "Address:"+                    , "An address."+                    , ""+                    , "Shape:"+                    , "A shape."+                    , ""+                    , "Mood:"+                    , "A mood."+                    , ""+                    , "Tree:"+                    , "A tree."+                    , ""+                    , "Street:"+                    , "A street."+                    ]+          , testCase "a record nesting a record lists the nested one" $+              reachableLines (description (Proxy @Address))+                @?= ["The types above refer to the following types:", "", "Street:", "A street."]+          , testCase "a recursive type terminates and is not listed under itself" $+              reachableLines (description (Proxy @Tree)) @?= []+          , testCase "a hand-written instance without referencedTypes contributes no reachable types" $+              reachableLines (description (Proxy @Mood)) @?= []+          , testCase "a list of a record, a Maybe of an enum and a base type reach what their element reaches" $ do+              map typeName (reach @[Shape]) @?= ["Shape"]+              map typeName (reach @(Maybe Mood)) @?= ["Mood"]+              map typeName (reach @[Maybe Text]) @?= []+          , testCase "a Set of an enum reaches the element's entry and gets no section of its own" $ do+              map typeName (reach @(S.Set Mood)) @?= ["Mood"]+              map typeName (reach @(S.Set Int64)) @?= []+              let sectionHeaders = filter (T.isSuffixOf ":") (reachableLines (description (Proxy @(S.Set Mood))))+              sectionHeaders @?= ["The types above refer to the following types:", "Mood:"]+          , testGroup+              "derived with deriveDescribable"+              [ testCase "every nested type is named once, breadth first: sum, record, list element, parameterised type and its argument" $+                  map typeName (reachableTypes (Proxy @Tile))+                    @?= ["Cut", "Dimensions", "Label", "Choice Colour", "Colour"]+              , testCase "Dimensions is reached through Cut and through a field of Tile, and has one section" $+                  length (filter (== "Dimensions:") (T.lines (description (Proxy @Tile)))) @?= 1+              , testCase "a parameterised type derives with a Describable context, and its argument is reachable" $ do+                  map typeName (reachableTypes (Proxy @(Choice Colour))) @?= ["Colour"]+                  map typeName (reachableTypes (Proxy @(Choice Dimensions))) @?= ["Dimensions"]+                  map typeName (reachableTypes (Proxy @(Choice Text))) @?= []+                  map typeName (reach @(Choice Colour)) @?= ["Choice Colour"]+              , testCase "mutually recursive types derived in one splice terminate, each listing the other once" $ do+                  reachableLines (description (Proxy @Folder))+                    @?= ["The types above refer to the following types:", "", "File:", "A file, which is either some text or another folder.", "- Plain: Some text.", "- Directory: A folder in place of a file.", ""]+                  map typeName (reachableTypes (Proxy @File)) @?= ["Folder"]+              , testCase "a self-recursive derived type is not listed under itself" $+                  reachableLines (description (Proxy @Outline)) @?= []+              , testCase "a Symbol-kinded phantom parameter derives, and its description renders at a concrete unit" $ do+                  describeType (Proxy @(Measure "metre"))+                    @?= T.unlines ["An amount in some unit, a phantom parameter of kind Symbol.", "- measureAmount: The amount, in the unit."]+                  assertBool "the description names the type" ("An amount in some unit" `T.isInfixOf` description (Proxy @(Measure "metre")))+                  reachableLines (description (Proxy @(Measure "second"))) @?= []+                  assertBool "two units are two types" (describedIdentity (Proxy @(Measure "metre")) /= describedIdentity (Proxy @(Measure "second")))+              , testCase "an unannotated, poly-kinded phantom parameter derives, and its description renders at concrete instantiations" $ do+                  describeType (Proxy @(Tagged Int))+                    @?= T.unlines ["A value tagged by an unannotated phantom parameter, which is poly-kinded under GHC2024."]+                  assertBool "the description names the type" ("unannotated phantom parameter" `T.isInfixOf` description (Proxy @(Tagged Int)))+                  assertBool "the description renders at a parameter of another kind" ("unannotated phantom parameter" `T.isInfixOf` description (Proxy @(Tagged "label")))+                  assertBool "the description renders at a parameter of kind Type -> Type" ("unannotated phantom parameter" `T.isInfixOf` description (Proxy @(Tagged Maybe)))+              ]+          , testGroup+              "through Generically"+              [ testCase "a recursive type promoted through Generically is not listed under itself" $+                  map typeName (reachableTypes (Proxy @(Generically Outline))) @?= []+              , testCase "the wrapper reaches what the wrapped type reaches" $+                  map typeName (reachableTypes (Proxy @(Generically Folder))) @?= ["File"]+              , testCase "a mutually recursive type through Generically lists the other type, not itself" $+                  map typeName (reachableTypes (Proxy @(Generically File))) @?= ["Folder"]+              , testCase "the wrapper has the identity of the wrapped type" $+                  describedIdentity (Proxy @(Generically Outline)) @?= describedIdentity (Proxy @Outline)+              ]+          , testCase "the section comes after the examples" $ do+              let (before, after) = break (== "The types above refer to the following types:") (T.lines (description (Proxy @Address)))+              assertBool "the examples come before the section" ("Example valid JSON responses:" `elem` before)+              length after @?= 4+          ]+      , golden "Span" $ description (Proxy @Span)+      , testGroup+          "positional constructor docs"+          [ testCase "a sum with a doc on each argument renders each documented argument under its constructor, by position" $+              describeType (Proxy @Span)+                @?= T.unlines+                  [ "A span between points, a positional sum with a doc on each argument."+                  , "- Between: Between two points."+                  , "  - field 1: The first point."+                  , "  - field 2: The second point."+                  , "- Starting: From a point on, with one argument documented and one not."+                  , "  - field 1: The point to start at."+                  , "- Whole"+                  ]+          , testCase "a sum in the one-line form documents the constructor, as before" $+              describeType (Proxy @Purchase)+                @?= T.unlines+                  [ "How a purchase is made, a sum in the one-line form."+                  , "- ByFuel: Bought by the litre."+                  , "- ByVoucher"+                  ]+          , testCase "a single constructor's own doc is rendered after the type's" $+              describeType (Proxy @Bounds)+                @?= T.unlines ["A bound, in millimetres.", "The largest allowed value."]+          , testCase "a single positional constructor lists its documented arguments directly" $+              describeType (Proxy @Point)+                @?= T.unlines+                  [ "A point, a single positional constructor with a doc on each argument."+                  , "A point in the plane."+                  , "- field 1: The horizontal position."+                  , "- field 2: The vertical position."+                  ]+          , testCase "a single positional constructor in the trailing-comment layout lists its arguments the same way" $+              describeType (Proxy @Couple)+                @?= T.unlines+                  [ "A couple, each argument on a line of its own with a trailing comment."+                  , "- field 1: The left one."+                  , "- field 2: The right one."+                  ]+          , testCase "annotateFieldTypes leaves a positional argument line alone" $ do+              let rendered = T.lines (description (Proxy @Point))+              assertBool "the first argument line is unchanged" ("- field 1: The horizontal position." `elem` rendered)+              assertBool "the second argument line is unchanged" ("- field 2: The vertical position." `elem` rendered)+          , testCase "undocumented positional fields add no lines" $+              describeType (Proxy @Wrapped) @?= "A wrapper whose constructor and field have no docs.\n"+          ]+      , testGroup+          "custom property combined with the structural one"+          [ contains "own property" (description (Proxy @Registration)) "The email address must contain the registrant's name."+          , contains "name field property" (description (Proxy @Registration)) "Field registrationName: The name must not be empty."+          , contains "email field property" (description (Proxy @Registration)) "Field registrationEmail: The email address is not empty."+          , violations "a valid value violates nothing" 0 (Registration (Name "Ada") (Email "ada@example.org"))+          , violations "an own property violation is found" 1 (Registration (Name "Ada") (Email "bob@example.org"))+          , violations "a field property violation is found" 1 (Registration (Name "") (Email "ada@example.org"))+          ]+      ]+  where+    violations name expected v =+      testCase name $+        length (filter (not . propertyHolds v) (universe @(Property Registration))) @?= expected+    contains name rendered needle =+      testCase name $+        assertBool ("expected " <> show needle <> " in " <> show rendered) (needle `T.isInfixOf` rendered)+    golden name rendered =+      goldenVsString name ("test/golden/" <> name <> ".golden") $+        pure $+          encodeUtf8 $+            TL.fromStrict rendered
+ test/golden/Delivery.golden view
@@ -0,0 +1,7 @@++Produce a value of the following type:+How a message should be delivered.+- Post: Send the message by post.+- ByEmail: Send the message by email.+- Hold: Do not send the message at all.+
+ test/golden/Email.golden view
@@ -0,0 +1,11 @@++Produce a value of the following type:+A contact address that is an email address.+- emailAddress (string): The email address, which must contain an at sign.++The following properties MUST hold in your response:+- The email address is not empty.+- The email address must contain an '@' character.+Example valid JSON responses:+{"emailAddress":"ada@example.org"}+{"emailAddress":"alan@example.com"}
+ test/golden/Fruit.golden view
@@ -0,0 +1,11 @@++Produce a value of the following type:+A piece of fruit.+- FruitApple: An apple.+  - appleVariety: The variety of the apple.+  - appleSweetness: How sweet the apple is, from 1 to 10.+- FruitBanana: A banana, with its length in centimetres.+- FruitPear: A pear.+  - pearRipe: Whether the pear is ripe.+- FruitLemon+
+ test/golden/Person.golden view
@@ -0,0 +1,6 @@++Produce a value of the following type:+A person with a name and an age.+- personName (string): The person's full name.+- personAge (integer): The person's age in years.+
+ test/golden/Span.golden view
@@ -0,0 +1,10 @@++Produce a value of the following type:+A span between points, a positional sum with a doc on each argument.+- Between: Between two points.+  - field 1: The first point.+  - field 2: The second point.+- Starting: From a point on, with one argument documented and one not.+  - field 1: The point to start at.+- Whole+
+ test/golden/StructuralContact.golden view
@@ -0,0 +1,20 @@+universe:+  Structural (Z (Z (PropertyOf NameNotEmpty))) | Field contactName: The name must not be empty.+  Structural (Z (Z (PropertyOf NameIsReal))) | (undescribed)+  Structural (Z (S (Z (PropertyOf EmailNotEmpty)))) | Field contactEmail: The email address is not empty.+  Structural (Z (S (Z (PropertyOf EmailHasAtSign)))) | Field contactEmail: The email address must contain an '@' character.+value Contact {contactName = Name "Ada", contactEmail = Email {emailAddress = "ada@example.org"}}:+  Structural (Z (Z (PropertyOf NameNotEmpty))): holds+  Structural (Z (Z (PropertyOf NameIsReal))): holds+  Structural (Z (S (Z (PropertyOf EmailNotEmpty)))): holds+  Structural (Z (S (Z (PropertyOf EmailHasAtSign)))): holds+value Contact {contactName = Name "", contactEmail = Email {emailAddress = "ada@example.org"}}:+  Structural (Z (Z (PropertyOf NameNotEmpty))): violated+  Structural (Z (Z (PropertyOf NameIsReal))): holds+  Structural (Z (S (Z (PropertyOf EmailNotEmpty)))): holds+  Structural (Z (S (Z (PropertyOf EmailHasAtSign)))): holds+value Contact {contactName = Name "Ada", contactEmail = Email {emailAddress = ""}}:+  Structural (Z (Z (PropertyOf NameNotEmpty))): holds+  Structural (Z (Z (PropertyOf NameIsReal))): holds+  Structural (Z (S (Z (PropertyOf EmailNotEmpty)))): violated+  Structural (Z (S (Z (PropertyOf EmailHasAtSign)))): violated
+ test/golden/StructuralPair.golden view
@@ -0,0 +1,15 @@+universe:+  Structural (Z (Z (PropertyOf NameNotEmpty))) | Field 1 of Pair: The name must not be empty.+  Structural (Z (Z (PropertyOf NameIsReal))) | (undescribed)+  Structural (Z (S (Z (PropertyOf EmailNotEmpty)))) | Field 2 of Pair: The email address is not empty.+  Structural (Z (S (Z (PropertyOf EmailHasAtSign)))) | Field 2 of Pair: The email address must contain an '@' character.+value Pair (Name "") (Email {emailAddress = "no-at-sign"}):+  Structural (Z (Z (PropertyOf NameNotEmpty))): violated+  Structural (Z (Z (PropertyOf NameIsReal))): holds+  Structural (Z (S (Z (PropertyOf EmailNotEmpty)))): holds+  Structural (Z (S (Z (PropertyOf EmailHasAtSign)))): violated+value Pair (Name "Ada") (Email {emailAddress = "ada@example.org"}):+  Structural (Z (Z (PropertyOf NameNotEmpty))): holds+  Structural (Z (Z (PropertyOf NameIsReal))): holds+  Structural (Z (S (Z (PropertyOf EmailNotEmpty)))): holds+  Structural (Z (S (Z (PropertyOf EmailHasAtSign)))): holds
+ test/golden/StructuralParcel.golden view
@@ -0,0 +1,35 @@+universe:+  Structural (Z (Z (PropertyOf EmailNotEmpty))) | Constructor Letter, field letterTo: The email address is not empty.+  Structural (Z (Z (PropertyOf EmailHasAtSign))) | Constructor Letter, field letterTo: The email address must contain an '@' character.+  Structural (Z (S (Z (PropertyOf NameNotEmpty)))) | Constructor Letter, field letterFrom: The name must not be empty.+  Structural (Z (S (Z (PropertyOf NameIsReal)))) | (undescribed)+  Structural (S (Z (Z (PropertyOf NameNotEmpty)))) | Constructor Crate, field 1: The name must not be empty.+  Structural (S (Z (Z (PropertyOf NameIsReal)))) | (undescribed)+value Letter {letterTo = Email {emailAddress = ""}, letterFrom = Name "Ada"}:+  Structural (Z (Z (PropertyOf EmailNotEmpty))): violated+  Structural (Z (Z (PropertyOf EmailHasAtSign))): violated+  Structural (Z (S (Z (PropertyOf NameNotEmpty)))): holds+  Structural (Z (S (Z (PropertyOf NameIsReal)))): holds+  Structural (S (Z (Z (PropertyOf NameNotEmpty)))): holds+  Structural (S (Z (Z (PropertyOf NameIsReal)))): holds+value Crate (Name ""):+  Structural (Z (Z (PropertyOf EmailNotEmpty))): holds+  Structural (Z (Z (PropertyOf EmailHasAtSign))): holds+  Structural (Z (S (Z (PropertyOf NameNotEmpty)))): holds+  Structural (Z (S (Z (PropertyOf NameIsReal)))): holds+  Structural (S (Z (Z (PropertyOf NameNotEmpty)))): violated+  Structural (S (Z (Z (PropertyOf NameIsReal)))): holds+value Crate (Name "Ada"):+  Structural (Z (Z (PropertyOf EmailNotEmpty))): holds+  Structural (Z (Z (PropertyOf EmailHasAtSign))): holds+  Structural (Z (S (Z (PropertyOf NameNotEmpty)))): holds+  Structural (Z (S (Z (PropertyOf NameIsReal)))): holds+  Structural (S (Z (Z (PropertyOf NameNotEmpty)))): holds+  Structural (S (Z (Z (PropertyOf NameIsReal)))): holds+value Blank:+  Structural (Z (Z (PropertyOf EmailNotEmpty))): holds+  Structural (Z (Z (PropertyOf EmailHasAtSign))): holds+  Structural (Z (S (Z (PropertyOf NameNotEmpty)))): holds+  Structural (Z (S (Z (PropertyOf NameIsReal)))): holds+  Structural (S (Z (Z (PropertyOf NameNotEmpty)))): holds+  Structural (S (Z (Z (PropertyOf NameIsReal)))): holds
+ test/golden/Tile.golden view
@@ -0,0 +1,39 @@++Produce a value of the following type:+A ceramic tile.+- tileCut (object): How the tile is cut.+- tileSize (object): The size of the tile when laid.+- tileLabels (array): The labels printed on the tile.+- tileColour (object): The chosen colour, if any.+- tileNote (string): A note for the tiler.++The types above refer to the following types:++Cut:+How a tile is cut.+- Straight: Straight edges, to the given dimensions.+- Curved: A round tile of the given diameter in millimetres.+++Dimensions:+The size of a tile.+- dimWidth: The width in millimetres.+- dimHeight: The height in millimetres.+++Label:+A text printed on a tile.+- labelText: The words that are printed.+++Choice Colour:+Either a value was picked, or none was.+- Pick: The picked value.+- Decline: Nothing was picked.+++Colour:+A colour of paint.+- Red: Like a post box.+- Green: Like a lawn.+