Copyright | (c) axionbuster 2025 |
---|---|
License | BSD-3-Clause |
Safe Haskell | None |
Language | GHC2021 |
M.PkMacro
Description
This module provides Template Haskell functionality to generate data types with
automatic Pack
/Unpack
instances. It uses a simple grammar to define data types
and their field mappings.
Usage
Define data types using the pkmacro
quasi-quoter. The syntax is indentation-insensitive:
-- First, set up default instancessetdefaultderives
-- Sets upGeneric
,Pack
, andUnpack
derives -- Define a newtype wrapper withPack
/Unpack
instances newtype AAA = AAAInt32
deriving stock (Generic
) deriving newtype (Pack
,Unpack
) [pkmacro| -- Regular data type with two fields data A { f1 :: Int32, -- Regular field f2 :: Int32 via AAA, -- Field with custom serialization } -- Data type with one field and explicit deriving data B { f3 :: Int32, deriving (Generic
,Show
) } -- Empty data type (creates constructor with no fields) data C {} |]
The grammar supports:
- Empty data types (no fields)
- Custom serialization via
via
clause - Multiple data types in one block
- Indentation-insensitive syntax
- Comments (both
--
and{- -}
style)
Syntax
The full syntax for data type definitions is:
data TypeName { field1 :: Type1 [via Type2], -- Field with optional via clause field2 :: Type3, -- Regular field [deriving (Class1, Class2)] -- Optional proper deriving clause [and shadow deriving (Pack
,Unpack
) with (Class3, Class4)] -- Optional shadow deriving }
Elements in square brackets are optional.
- The
via
clause specifies a different type to use for serialization deriving
adds instances to the main data typeshadow deriving
adds instances to the generated shadow type used for serialization- Multiple data types can be defined in a single quasi-quoter block
Type Syntax
Types can include:
- Simple types:
,Int32
, etc.Text
- Parameterized types:
,Maybe
a[
Int
] - Type applications:
a @k
- Promoted types:
'True
,'Just
- Type literals:
"hello"
,123
- Parenthesized types:
(a, b)
,(
Either
a b)
See: Pack
, Unpack
, setdefaultderives
, addproperderives
, and addshadowderives
.
Synopsis
- setdefaultderives :: Q [Dec]
- addproperderives :: [Name] -> Q [Dec]
- addshadowderives :: [Name] -> Q [Dec]
- pkmacro :: QuasiQuoter
Documentation
setdefaultderives :: Q [Dec] Source #
addproperderives :: [Name] -> Q [Dec] Source #
Add proper deriving clauses for subsequent data types. These instances will be derived directly on the main data type.
addproperderives
[''Generic, ''Show] -- Derive Generic and Show
addshadowderives :: [Name] -> Q [Dec] Source #
Add shadow deriving clauses for subsequent data types. These instances will be derived on the shadow data type used for serialization.
addshadowderives
[''Generic, ''Pack] -- DeriveGeneric
andPack
on shadow type
pkmacro :: QuasiQuoter Source #
See module docs (M.PkMacro) for information.