microlens-th 0.1.2.0 → 0.2.0.0
raw patch · 3 files changed
+144/−82 lines, 3 filesPVP ok
version bump matches the API change (PVP)
API changes (from Hackage documentation)
- Lens.Micro.TH: createClass :: Lens' LensRules Bool
- Lens.Micro.TH: defaultFieldRules :: LensRules
Files
- CHANGELOG.md +5/−0
- microlens-th.cabal +1/−1
- src/Lens/Micro/TH.hs +138/−81
CHANGELOG.md view
@@ -1,3 +1,8 @@+# 0.2.0.0++* `createClass` was removed because it doesn't seem to be useful without `lensClass`.+* `defaultFieldRules` isn't exported anymore – use `camelCaseFields`.+ # 0.1.2.0 * Package now compiles with `-O2` and other optimisations by default.
microlens-th.cabal view
@@ -1,5 +1,5 @@ name: microlens-th-version: 0.1.2.0+version: 0.2.0.0 synopsis: Automatic generation of record lenses for microlens description: This package lets you automatically generate lenses for data types; code
src/Lens/Micro/TH.hs view
@@ -28,12 +28,10 @@ DefName(..), lensRules, lensRulesFor,- defaultFieldRules, camelCaseFields, -- * Configuring lens rules lensField, simpleLenses,- createClass, generateSignatures, generateUpdateableOptics, generateLazyPatterns,@@ -89,21 +87,21 @@ -- Utilities --- | Modify element at some index in a list.+-- Modify element at some index in a list. setIx :: Int -> a -> [a] -> [a] setIx i x s | i < 0 || i >= length s = s | otherwise = let (l, _:r) = splitAt i s in l ++ [x] ++ r --- | This is like @rewrite@ from uniplate.+-- This is like @rewrite@ from uniplate. rewrite :: (Data a, Data b) => (a -> Maybe a) -> b -> b rewrite f mbA = case cast mbA of Nothing -> gmapT (rewrite f) mbA Just a -> let a' = gmapT (rewrite f) a in fromJust . cast $ fromMaybe a' (f a') --- | @fromSet@ wasn't always there, and we need compatibility with+-- @fromSet@ wasn't always there, and we need compatibility with -- containers-0.4 to compile on GHC 7.4. fromSet :: (k -> v) -> Set.Set k -> Map.Map k v #if MIN_VERSION_containers(0,5,0)@@ -121,10 +119,10 @@ {- | Generate lenses for a data type or a newtype. -To use, you have to enable Template Haskell:+To use it, you have to enable Template Haskell first: @-{-# LANGUAGE TemplateHaskell #-}+\{\-\# LANGUAGE TemplateHaskell \#\-\} @ Then, after declaring the datatype (let's say @Foo@), add @makeLenses ''Foo@ on a separate line:@@ -134,7 +132,7 @@ _x :: Int, _y :: Bool } -makeLenses ''Foo+'makeLenses' ''Foo @ This would generate the following lenses, which can be used to access the fields of @Foo@:@@ -147,7 +145,7 @@ y f foo = (\\y' -> f {_y = y'}) '<$>' f (_y foo) @ -(If you don't want a lens to be generated for some field, don't prefix it with an @_@.)+(If you don't want a lens to be generated for some field, don't prefix it with “_”.) If you want to creat lenses for many types, you can do it all in one place like this (of course, instead you just can use 'makeLenses' several times if you feel it would be more readable): @@ -159,7 +157,7 @@ 'concat' '<$>' 'mapM' 'makeLenses' [''Foo, ''Bar, ''Quux] @ -When the data type has type parameters, it's possible for a lens to do a polymorphic update – i.e. change the type of the thing along with changing the type of the field. For instance, with this type:+When the data type has type parameters, it's possible for a lens to do a polymorphic update – i.e. change the type of the thing along with changing the type of the field. For instance, with this type @ data Foo a = Foo {@@ -226,9 +224,18 @@ data Foo = Foo {slot1, slot2, slot3 :: Int} 'makeLensesFor' [(\"slot1\", \"slots\"),- (\"slot2\", \"slots\"),- (\"slot3\", \"slots\")] ''Foo+ (\"slot2\", \"slots\"),+ (\"slot3\", \"slots\")] ''Foo @++would generate++@+slots :: 'Traversal'' Foo Int+slots f foo = Foo '<$>' f (slot1 foo)+ '<*>' f (slot2 foo)+ '<*>' f (slot3 foo)+@ -} makeLensesFor :: [(String, String)] -> Name -> DecsQ makeLensesFor fields = makeFieldOptics (lensRulesFor fields)@@ -236,8 +243,12 @@ {- | Generate lenses with custom parameters. -This function lets you customise generated lenses; to see what exactly can be changed, look at 'LensRules'. 'makeLenses' is implemented with 'makeLensesWith' – it uses the 'lensRules' configuration (which you can build upon – see the “Configuring lens rules” section).+To see what exactly you can customise, look at the “Configuring lens rules” section. Usually you would build upon the 'lensRules' configuration, which is used by 'makeLenses': +@+'makeLenses' = 'makeLensesWith' 'lensRules'+@+ Here's an example of generating lenses that would use lazy patterns: @@@ -308,30 +319,50 @@ makeFields :: Name -> DecsQ makeFields = makeFieldOptics camelCaseFields --- | Generate "simple" optics even when type-changing optics are possible.--- (e.g. 'Lens'' instead of 'Lens')+{- |+Generate simple (monomorphic) lenses even when type-changing lenses are possible – i.e. 'Lens'' instead of 'Lens' and 'Traversal'' instead of 'Traversal'. Just in case, here's an example of a situation when type-changing lenses would be normally generated:++@+data Foo a = Foo { _foo :: a }+@++Generated lens:++@+foo :: 'Lens' (Foo a) (Foo b) a b+@++Generated lens with 'simpleLenses' turned on:++@+foo :: 'Lens'' (Foo a) a+@++This option is disabled by default.+-} simpleLenses :: Lens' LensRules Bool simpleLenses f r = fmap (\x -> r { _simpleLenses = x}) (f (_simpleLenses r)) --- | Indicate whether or not to supply the signatures for the generated--- lenses.------ Disabling this can be useful if you want to provide a more restricted type--- signature or if you want to supply hand-written haddocks.+{- |+Supply type signatures for the generated lenses.++This option is enabled by default. Disable it if you want to write the signature by yourself – for instance, if the signature should be more restricted, or if you want to write haddocks for the lens (as haddocks are attached to the signature and not to the definition).+-} generateSignatures :: Lens' LensRules Bool generateSignatures f r = fmap (\x -> r { _generateSigs = x}) (f (_generateSigs r)) --- | Generate "updateable" optics when 'True'. When 'False', 'Fold's will be--- generated instead of 'Traversal's and 'Getter's will be generated instead--- of 'Lens'es. This mode is intended to be used for types with invariants--- which must be maintained by "smart" constructors.+{- |+Generate “updateable” optics. When turned off, 'Fold's will be generated instead of 'Traversal's and 'Getter's will be generated instead of 'Lens'es.++This option is enabled by default. Disabling it can be useful for types with invariants (also known as “types with smart constructors”) – if you generate updateable optics, anyone would be able to use them to break your invariants.+-} generateUpdateableOptics :: Lens' LensRules Bool generateUpdateableOptics f r = fmap (\x -> r { _allowUpdates = x}) (f (_allowUpdates r)) {- |-Generate optics using lazy pattern matches. This can allow fields of an undefined value to be initialized with lenses:+Generate lenses using lazy pattern matches. This can allow fields of an undefined value to be initialized with lenses: @ data Foo = Foo {_x :: Int, _y :: Bool}@@ -341,46 +372,61 @@ @ @-> 'undefined' '&' x '.~' 8 '&' y '.~' True+>>> 'undefined' '&' x '.~' 8 '&' y '.~' True Foo {_x = 8, _y = True} @ (Without 'generateLazyPatterns', the result would be just 'undefined'.) -The downside of this flag is that it can lead to space-leaks and code-size\/compile-time increases when generated for large records. By default this flag is turned off, and strict optics are generated.+This option is disabled by default. The downside of enabling it is that it can lead to space-leaks and code-size\/compile-time increases when lenses are generated for large records. -When you have a lazy optic, you can get a strict optic from it by composing with ('$!'):+When you have a lazy lens, you can get a strict lens from it by composing with ('$!'): @-strictOptic = ('$!') . lazyOptic+strictLens = ('$!') . lazyLens @ -} generateLazyPatterns :: Lens' LensRules Bool generateLazyPatterns f r = fmap (\x -> r { _lazyPatterns = x}) (f (_lazyPatterns r)) --- | Create the class if the constructor is 'Control.Lens.Type.Simple' and the--- 'lensClass' rule matches.-createClass :: Lens' LensRules Bool-createClass f r =- fmap (\x -> r { _generateClasses = x}) (f (_generateClasses r))+{- |+This lets you choose which fields would have lenses generated for them and how would those lenses be called. To do that, you provide a function that would take a field name and output a list (possibly empty) of lenses that should be generated for that field. --- | 'Lens'' to access the convention for naming fields in our 'LensRules'.------ Defaults to stripping the _ off of the field name, lowercasing the name, and--- skipping the field if it doesn't start with an '_'. The field naming rule--- provides the names of all fields in the type as well as the current field.--- This extra generality enables field naming conventions that depend on the--- full set of names in a type.------ The field naming rule has access to the type name, the names of all the field--- of that type (including the field being named), and the name of the field--- being named.------ TypeName -> FieldNames -> FieldName -> DefinitionNames+Here's the full type of the function you have to provide:++@+'Name' -> -- The datatype lenses are being generated for+['Name'] -> -- A list of all fields of the datatype+'Name' -> -- The current field+['DefName'] -- A list of lens names+@++Most of the time you won't need the first 2 parameters, but sometimes they are useful – for instance, the list of all fields would be useful if you wanted to implement a slightly more complicated rule like “if some fields are prefixed with underscores, generate lenses for them, but if no fields are prefixed with underscores, generate lenses for /all/ fields”.++As an example, here's a function used by default. It strips “_” off the field name, lowercases the next character after “_”, and skips the field entirely if it doesn't start with “_”:++@+\\_ _ n ->+ case 'nameBase' n of+ \'_\':x:xs -> ['TopName' ('mkName' ('toLower' x : xs))]+ _ -> []+@++You can also generate classes (i.e. what 'makeFields' does) by using @'MethodName' className lensName@ instead of @'TopName' lensName@.+-} lensField :: Lens' LensRules (Name -> [Name] -> Name -> [DefName]) lensField f r = fmap (\x -> r { _fieldToDef = x}) (f (_fieldToDef r)) +{- |+Lens rules used by default (i.e. in 'makeLenses'):++* 'generateSignatures' is turned on+* 'generateUpdateableOptics' is turned on+* 'generateLazyPatterns' is turned off+* 'simpleLenses' is turned off+* 'lensField' strips “_” off the field name, lowercases the next character after “_”, and skips the field entirely if it doesn't start with “_” (you can see how it's implemented in the docs for 'lensField').+-} lensRules :: LensRules lensRules = LensRules { _simpleLenses = False@@ -396,16 +442,27 @@ _ -> [] } --- | Used in 'makeLensesFor'.-lensRulesFor ::- [(String, String)] {- ^ [(Field Name, Lens Name)] -} ->- LensRules+{- |+A modification of 'lensRules' used by 'makeLensesFor' (the only difference is that a simple lookup function is used for 'lensField').+-}+lensRulesFor+ :: [(String, String)] -- ^ \[(fieldName, lensName)\]+ -> LensRules lensRulesFor fields = lensRules & lensField .~ mkNameLookup fields mkNameLookup :: [(String,String)] -> Name -> [Name] -> Name -> [DefName] mkNameLookup kvs _ _ field = [ TopName (mkName v) | (k,v) <- kvs, k == nameBase field] +{- |+Lens rules used by 'makeFields':++* 'generateSignatures' is turned on+* 'generateUpdateableOptics' is turned on+* 'generateLazyPatterns' is turned off+* 'simpleLenses' is turned on (unlike in 'lensRules')+* 'lensField' is more complicated – it takes fields which are prefixed with the name of the type they belong to (e.g. “fooFieldName” for “Foo”), strips that prefix, and generates a class called “HasFieldName” with a single method called “fieldName”. If some fields are prefixed with underscores, underscores would be stripped too, but then fields without underscores won't have any lenses generated for them. Also note that e.g. “foolish” won't have a lens called “lish” generated for it – the prefix must be followed by a capital letter (or else it wouldn't be camel case).+-} camelCaseFields :: LensRules camelCaseFields = defaultFieldRules @@ -439,9 +496,9 @@ -- Language.Haskell.TH.Lens --- | Has a 'Name'+-- Has a 'Name' class HasName t where- -- | Extract (or modify) the 'Name' of something+ -- Extract (or modify) the 'Name' of something name :: Lens' t Name instance HasName TyVarBndr where@@ -457,9 +514,9 @@ name f (InfixC l n r) = (\n' -> InfixC l n' r) <$> f n name f (ForallC bds ctx con) = ForallC bds ctx <$> name f con --- | Provides for the extraction of free type variables, and alpha renaming.+-- Provides for the extraction of free type variables, and alpha renaming. class HasTypeVars t where- -- | When performing substitution into this traversal you're not allowed+ -- When performing substitution into this traversal you're not allowed -- to substitute in a name that is bound internally or you'll violate -- the 'Traversal' laws, when in doubt generate your names with 'newName'. typeVarsEx :: Set Name -> Traversal' t Name@@ -506,11 +563,11 @@ instance HasTypeVars t => HasTypeVars (Maybe t) where typeVarsEx s = traverse . typeVarsEx s --- | Traverse /free/ type variables+-- Traverse /free/ type variables typeVars :: HasTypeVars t => Traversal' t Name typeVars = typeVarsEx mempty --- | Substitute using a map of names in for /free/ type variables+-- Substitute using a map of names in for /free/ type variables substTypeVars :: HasTypeVars t => Map Name Name -> t -> t substTypeVars m = over typeVars $ \n -> fromMaybe n (Map.lookup n m) @@ -521,7 +578,7 @@ ------------------------------------------------------------------------ --- | Compute the field optics for the type identified by the given type name.+-- Compute the field optics for the type identified by the given type name. -- Lenses will be computed when possible, Traversals otherwise. makeFieldOptics :: LensRules -> Name -> DecsQ makeFieldOptics rules tyName =@@ -546,7 +603,7 @@ mkS tyName vars = tyName `conAppsT` map VarT (toListOf typeVars vars) --- | Compute the field optics for a deconstructed Dec+-- Compute the field optics for a deconstructed Dec -- When possible build an Iso otherwise build one optic per field. makeFieldOpticsForDec' :: LensRules -> Name -> Type -> [Con] -> DecsQ makeFieldOpticsForDec' rules tyName s cons =@@ -579,12 +636,12 @@ expandName _ _ = [] --- | Normalized the Con type into a uniform positional representation,+-- Normalized the Con type into a uniform positional representation, -- eliminating the variance between records, infix constructors, and normal -- constructors. normalizeConstructor :: Con ->- Q (Name, [(Maybe Name, Type)]) -- ^ constructor name, field name, field type+ Q (Name, [(Maybe Name, Type)]) -- constructor name, field name, field type normalizeConstructor (RecC n xs) = return (n, [ (Just fieldName, ty) | (fieldName,_,ty) <- xs])@@ -602,15 +659,15 @@ data OpticType = GetterType | LensType -- or IsoType --- | Compute the positional location of the fields involved in+-- Compute the positional location of the fields involved in -- each constructor for a given optic definition as well as the -- type of clauses to generate and the type to annotate the declaration -- with. buildScaffold ::- LensRules ->- Type {- ^ outer type -} ->- [(Name, [([DefName], Type)])] {- ^ normalized constructors -} ->- DefName {- ^ target definition -} ->+ LensRules ->+ Type {- outer type -} ->+ [(Name, [([DefName], Type)])] {- normalized constructors -} ->+ DefName {- target definition -} -> Q (OpticType, OpticStab, [(Name, Int, [Int])]) {- ^ optic type, definition type, field count, target fields -} buildScaffold rules s cons defName =@@ -698,7 +755,7 @@ stabToA (OpticStab _ _ _ a _) = a stabToA (OpticSa _ _ _ a) = a --- | Compute the s t a b types given the outer type 's' and the+-- Compute the s t a b types given the outer type 's' and the -- categorized field types. Left for fixed and Right for visited. -- These types are "raw" and will be packaged into an 'OpticStab' -- shortly after creation.@@ -719,7 +776,7 @@ unfixedTypeVars = setOf typeVars s Set.\\ fixedTypeVars --- | Build the signature and definition for a single field optic.+-- Build the signature and definition for a single field optic. -- In the case of a singleton constructor irrefutable matches are -- used to enable the resulting lenses to be used on a bottom value. makeFieldOptic ::@@ -788,7 +845,7 @@ irref = _lazyPatterns rules && length cons == 1 --- | Construct an optic clause that returns an unmodified value+-- Construct an optic clause that returns an unmodified value -- given a constructor name and the number of fields on that -- constructor. makePureClause :: Name -> Int -> ClauseQ@@ -799,7 +856,7 @@ (normalB (appE (varE 'pure) (appsE (conE conName : map varE xs)))) [] --- | Construct an optic clause suitable for a Getter or Fold+-- Construct an optic clause suitable for a Getter or Fold -- by visited the fields identified by their 0 indexed positions makeGetterClause :: Name -> Int -> [Int] -> ClauseQ makeGetterClause conName fieldCount [] = makePureClause conName fieldCount@@ -822,7 +879,7 @@ (normalB body) [] --- | Build a clause that updates the field at the given indexes+-- Build a clause that updates the field at the given indexes -- When irref is 'True' the value with me matched with an irrefutable -- pattern. This is suitable for Lens and Traversal construction makeFieldOpticClause :: Name -> Int -> [Int] -> Bool -> ClauseQ@@ -857,7 +914,7 @@ -- The field-oriented optic generation supports incorporating fields -- with distinct but unifiable types into a single definition. --- | Unify the given list of types, if possible, and return the+-- Unify the given list of types, if possible, and return the -- substitution used to unify the types for unifying the outer -- type when building a definition's type signature. unifyTypes :: [Type] -> Q (Map Name Type, Type)@@ -865,7 +922,7 @@ unifyTypes [] = fail "unifyTypes: Bug: Unexpected empty list" --- | Attempt to unify two given types using a running substitution+-- Attempt to unify two given types using a running substitution unify1 :: Map Name Type -> Type -> Type -> Q (Map Name Type, Type) unify1 sub (VarT x) y | Just r <- Map.lookup x sub = unify1 sub r y@@ -893,7 +950,7 @@ unify1 _ x y = fail ("Failed to unify types: " ++ show (x,y)) --- | Perform a limited substitution on type variables. This is used+-- Perform a limited substitution on type variables. This is used -- when unifying rank-2 fields when trying to achieve a Getter or Fold. limitedSubst :: Map Name Type -> TyVarBndr -> Q TyVarBndr limitedSubst sub (PlainTV n)@@ -908,7 +965,7 @@ _ -> fail "Unable to unify exotic higher-rank type" limitedSubst _ tv = return tv --- | Apply a substitution to a type. This is used after unifying+-- Apply a substitution to a type. This is used after unifying -- the types of the fields in unifyTypes. applyTypeSubst :: Map Name Type -> Type -> Type applyTypeSubst sub = rewrite aux@@ -930,16 +987,16 @@ , _generateSigs :: Bool , _generateClasses :: Bool -- , _allowIsos :: Bool- , _allowUpdates :: Bool -- ^ Allow Lens/Traversal (otherwise Getter/Fold)+ , _allowUpdates :: Bool -- Allow Lens/Traversal (otherwise Getter/Fold) , _lazyPatterns :: Bool- -- | Type Name -> Field Names -> Target Field Name -> Definition Names+ -- Type Name -> Field Names -> Target Field Name -> Definition Names , _fieldToDef :: Name -> [Name] -> Name -> [DefName] -- , _classyLenses :: Name -> Maybe (Name,Name) -- type name to class name and top method } {- |-Name to give to a generated lens.+Name to give to a generated lens (used in 'lensField'). -} data DefName = TopName Name -- ^ Simple top-level definiton name@@ -951,14 +1008,14 @@ ------------------------------------------------------------------------ --- | Template Haskell wants type variables declared in a forall, so+-- Template Haskell wants type variables declared in a forall, so -- we find all free type variables in a given type and declare them. quantifyType :: Cxt -> Type -> Type quantifyType c t = ForallT vs c t where vs = map PlainTV (toList (setOf typeVars t)) --- | This function works like 'quantifyType' except that it takes+-- This function works like 'quantifyType' except that it takes -- a list of variables to exclude from quantification. quantifyType' :: Set Name -> Cxt -> Type -> Type quantifyType' exclude c t = ForallT vs c t@@ -997,6 +1054,6 @@ -- Control.Lens.Internal.TH --- | Apply arguments to a type constructor.+-- Apply arguments to a type constructor. conAppsT :: Name -> [Type] -> Type conAppsT conName = foldl AppT (ConT conName)