runtime-instances-1.0: Look up class instances at runtime.
Copyright Richard Eisenberg MIT rae@richarde.dev experimental Safe-Inferred GHC2021

Instance.Runtime.TH

Contents

Description

Synopsis

# Documentation

Arguments

 :: Q Type The class whose instances to include. This type must have the kind k -> Constraint for some k and include no variables. -> Q Exp

Build an Instances containing all in-scope ground instances for the given class. A ground instance is one that includes no type variables. Example usage:

instanceDatabase :: Instances Unqualified MyClass
instanceDatabase = $(allGroundInstances [t| MyClass |]) It is an infelicity in the design of Template Haskell that requires repeating the MyClass part; it should be inferrable. Note that this just looks at instance declarations to determine whether an instance is ground. So it would not pick up, e.g. Eq (Maybe Int), because the instance declaration looks like Eq (Maybe a). Due to a limitation of Template Haskell, this will find only instances declared in other modules or before a declaration splice in the current module. If you want to find instances declared in the current module, you can add a line $(pure [])

above the use of allGroundInstances in the file. This line forces GHC to finish processing everything above the line before looking at anything below the line, so those instances declared above the line are available below it.

Returns a list of ground (= no variables) types that satisfy the given constraint. The passed-in Type must have kind k -> Constraint for some k; all the returned types will then have kind k.

This finds only types that appear in ground instances. So if you look for Eq, you'll get Int, and Double, but not Maybe Int, even though Maybe Int is a ground type: it comes from instance ... => Eq (Maybe a), which is not a ground instance.

See also allGroundInstances, for more usage information.

# Utilities

promotedList :: [Type] -> Type Source #

Constructs a promoted list type from a list of types. Useful for synthesizing calls to instancesForInvisible using Template Haskell.